List of usage examples for java.net Socket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:com.googlecode.jcimd.TcpNetConnectionFactory.java
@Override public Connection getConnection() throws Exception { Socket socket = SocketFactory.getDefault().createSocket(); if (logger.isDebugEnabled()) { logger.debug("Connecting to [" + host + ":" + port + "]..."); }//from ww w .j ava2 s .c o m socket.connect(new InetSocketAddress(this.host, this.port), 2000); if (logger.isDebugEnabled()) { logger.debug("Connected to [" + host + ":" + port + "]"); } if (this.timeout > 0) { socket.setSoTimeout(this.timeout); } PacketSerializer serializer = new PacketSerializer(); serializer.setSequenceNumberGenerator(new ApplicationPacketSequenceNumberGenerator()); TcpNetConnection newConnection = new TcpNetConnection(socket, serializer, this.username, this.password); this.executor.execute(newConnection); newConnection.login(); return newConnection; }
From source file:net.lightbody.bmp.proxy.jetty.http.SocketListener.java
/** Persist the connection. * This method is called by the HttpConnection in order to prepare a * connection to be persisted. For this implementation, * if the listener is low on resources, the connection read * timeout is set to lowResourcePersistTimeMs. The * customizeRequest method is used to reset this to the normal * value after a request has been read.//from w w w . j a v a 2 s. co m * @param connection The HttpConnection to use. */ public void persistConnection(HttpConnection connection) { try { Socket socket = (Socket) (connection.getConnection()); if (_lowResourcePersistTimeMs > 0 && isLowOnResources()) { socket.setSoTimeout(_lowResourcePersistTimeMs); connection.setThrottled(true); } else connection.setThrottled(false); } catch (Exception e) { LogSupport.ignore(log, e); } }
From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java
/** * Retrieves all active checks configured in the server. * /*from w w w . j ava 2 s . com*/ * @param hostname * @return List<ActiveCheck> * @throws IOException */ public List<ActiveCheck> getActiveChecks(String hostname) throws IOException { List<ActiveCheck> list = new ArrayList<ActiveCheck>(); Socket socket = null; OutputStream out = null; BufferedReader brin = null; try { socket = new Socket(zabbixServer, zabbixPort); socket.setSoTimeout(TIMEOUT); out = socket.getOutputStream(); brin = new BufferedReader(new InputStreamReader(socket.getInputStream())); // send request to Zabbix server and wait for the list of items to be returned out.write(createGetActiveChecksRequest(hostname)); while (!socket.isClosed()) { String line = brin.readLine(); if (line == null) break; // all active checks received if (line.startsWith(ZBX_EOF)) break; list.add(parseActiveCheck(hostname, line)); } } finally { if (brin != null) { brin.close(); } if (out != null) { out.close(); } if (socket != null) { socket.close(); } } return list; }
From source file:org.darkphoenixs.pool.socket.SocketConnectionFactory.java
@Override public Socket createConnection() throws Exception { Socket socket = new Socket(); try {//from w ww . j a v a 2s . c o m if (sendBufferSize > 0) socket.setSendBufferSize(sendBufferSize); if (receiveBufferSize > 0) socket.setReceiveBufferSize(receiveBufferSize); if (soTimeout > 0) socket.setSoTimeout(soTimeout); if (linger > 0) socket.setSoLinger(true, linger); if (keepAlive) socket.setKeepAlive(keepAlive); if (tcpNoDelay) socket.setTcpNoDelay(tcpNoDelay); if (performance != null) socket.setPerformancePreferences(Integer.parseInt(performance[0]), Integer.parseInt(performance[1]), Integer.parseInt(performance[2])); socket.connect(socketAddress, connectionTimeout); } catch (Exception se) { socket.close(); throw se; } return socket; }
From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java
/** * @param key/*from w w w .j ava 2 s. co m*/ * @param value * @throws IOException */ private void send(final String key, final String value) throws IOException { final long start = System.currentTimeMillis(); final StringBuilder message = new StringBuilder(head); message.append(encodeBase64(key)); message.append(middle); message.append(encodeBase64(value == null ? "" : value)); message.append(tail); logger.debug(bundle.getString("zabbix-sender-sending-message", this.zabbixHost, key, value)); logger.trace(bundle.getString("zabbix-sender-detailed-message", message)); Socket socket = null; OutputStreamWriter out = null; InputStream in = null; try { socket = new Socket(zabbixServer, zabbixPort); socket.setSoTimeout(TIMEOUT); out = new OutputStreamWriter(socket.getOutputStream()); out.write(message.toString()); out.flush(); in = socket.getInputStream(); final int read = in.read(response); final String resp = new String(response); logger.debug(bundle.getString("zabbix-sender-received-response", resp)); if (read != 2 || response[0] != 'O' || response[1] != 'K') { logger.warn(bundle.getString("zabbix-sender-unexpected-response", key, resp)); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (socket != null) { socket.close(); } } final long elapsed = System.currentTimeMillis() - start; logger.trace(bundle.getString("zabbix-sender-message-sent", elapsed)); }
From source file:org.apache.flume.instrumentation.zabbix.ZabbixSender.java
private void send(final String key, final String value) throws IOException { final StringBuilder message = new StringBuilder(head); // message.append(Base64.encode(key)); message.append(base64Encode(key));/*from w w w. j av a 2 s .com*/ message.append(middle); // message.append(Base64.encode(value == null ? "" : value)); message.append(base64Encode(value == null ? "" : value)); message.append(tail); logger.trace("sending " + message); Socket zabbix = null; OutputStreamWriter out = null; InputStream in = null; for (Map.Entry<String, Integer> zabbixServer : zabbixServers.entrySet()) { try { zabbix = new Socket(zabbixServer.getKey(), zabbixServer.getValue()); zabbix.setSoTimeout(TIMEOUT); out = new OutputStreamWriter(zabbix.getOutputStream()); out.write(message.toString()); out.flush(); in = zabbix.getInputStream(); final int read = in.read(response); logger.trace("received " + new String(response)); if (read != 2 || response[0] != 'O' || response[1] != 'K') { logger.warn( "received unexpected response '" + new String(response) + "' for key '" + key + "'"); } } catch (Exception ex) { logger.warn("Error contacting Zabbix server " + zabbixServer.getKey() + " on port " + zabbixServer.getValue()); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (zabbix != null) { zabbix.close(); } } } }
From source file:org.globus.net.BaseServer.java
public void run() { Socket socket = null; while (accept) { try {/* w w w .j a va 2 s.com*/ socket = _server.accept(); if (!accept) { break; } socket.setSoTimeout(getTimeout()); } catch (IOException e) { if (accept) { // display error message logger.error("Server died: " + e.getMessage(), e); } break; } if (this.secure) { try { socket = wrapSocket(socket); } catch (GSSException e) { logger.error("Failed to secure the socket", e); break; } } handleConnection(socket); } logger.debug("server thread stopped"); }
From source file:org.sonatype.nexus.bundle.launcher.support.DefaultNexusBundle.java
/** * Stops Nexus.//from w ww . java2s .c o m * <p/> * {@inheritDoc} * * @since 2.0 */ @Override protected void stopApplication() { // application may be in suspended state waiting for debugger to attach, if we can reasonably guess this is // the case, then we should resume the vm so that we can ask command monitor to immediately halt try { if (getConfiguration().isSuspendOnStart()) { boolean isSuspended = new TimedCondition() { @Override protected boolean isSatisfied() throws Exception { Socket socket = new Socket(); socket.setSoTimeout(5000); socket.connect(new InetSocketAddress(getConfiguration().getHostName(), getConfiguration().getDebugPort())); return true; } }.await(Time.seconds(1), Time.seconds(10), Time.seconds(1)); if (isSuspended) { // FIXME avoiding the compile time dependency for now on jdi classes (DebuggerUtils) throw new RuntimeException(format("%s (%s) looks suspended at {}:{}, CANNOT STOP THIS BUNDLE!", getName(), getConfiguration().getId(), getConfiguration().getHostName(), getConfiguration().getDebugPort())); } } terminateRemoteNexus(commandMonitorPort); try { // clear transient cache to avoid filesystem bloat when running ITs FileUtils.deleteDirectory(new File(getNexusDirectory(), "data/cache")); } catch (IOException e) { // couldn't delete directory, too bad } } finally { // Stop the launcher-controller-side monitor thread if there is one if (keepAliveThread != null) { sendStopToKeepAlive(keepAlivePort); keepAliveThread = null; } } }
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 w w . ja va 2 s .c om*/ * * 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:sintef.android.gravity.advanced.RecordFragment.java
private void sendRecording() { sendRecordingSetViewParams();//from w ww. j av a2 s .co m new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { JsonObject recordings = new JsonObject(); String id = mTestIdInput.getText().toString(); recordings.addProperty("test_id", id); JsonObject calculations = new JsonObject(); JsonArray phoneVerticalAcceleration = new JsonArray(); JsonArray phoneTotalAcceleration = new JsonArray(); JsonArray watchFallIndex = new JsonArray(); JsonArray watchDirectionAcceleration = new JsonArray(); JsonArray watchAfterFall = new JsonArray(); for (RecordEventData entry : mRecordEvents) { JsonObject object = new JsonObject(); object.addProperty("time", entry.time); object.addProperty("value", entry.value); switch (entry.type) { case RECORDING_PHONE_VERTICAL_ACCELERATION: phoneVerticalAcceleration.add(object); break; case RECORDING_PHONE_TOTAL_ACCELERATION: phoneTotalAcceleration.add(object); break; case RECORDING_WATCH_FALL_INDEX: watchFallIndex.add(object); break; case RECORDING_WATCH_DIRECTION_ACCELERATION: watchDirectionAcceleration.add(object); break; case RECORDING_WATCH_AFTER_FALL: watchAfterFall.add(object); break; } } calculations.add("phone_vertical_acceleration", phoneVerticalAcceleration); calculations.add("phone_total_acceleration", phoneTotalAcceleration); calculations.add("watch_fall_index", watchFallIndex); calculations.add("watch_direction_acceleration", watchDirectionAcceleration); calculations.add("watch_after_fall", watchAfterFall); recordings.add("calculations", calculations); /* JsonArray recordEvents = new JsonArray(); for (RecordEvent event : mRecordEvents) { JsonObject accelerometerObject = new JsonObject(); accelerometerObject.addProperty("vertical_acceleration", event.mVerAcc); accelerometerObject.addProperty("total_acceleration", event.mTotAcc); recordEvents.add(accelerometerObject); } recordings.add("record_data", recordEvents); */ Collections.sort(mRecordAlgorithm); JsonArray fallDetectedArray = new JsonArray(); for (RecordAlgorithmData algorithmData : mRecordAlgorithm) { JsonObject fallDetectedObject = new JsonObject(); fallDetectedObject.addProperty("id", algorithmData.id); fallDetectedObject.addProperty("time", algorithmData.time); fallDetectedObject.addProperty("name", algorithmData.name); fallDetectedObject.addProperty("isFall", algorithmData.isFall); fallDetectedArray.add(fallDetectedObject); } recordings.add("fall_detection", fallDetectedArray); Gson gson = new GsonBuilder().serializeNulls() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); final String ip = mServerIp.getText().toString(); final String port = mServerPort.getText().toString(); PreferencesHelper.putString(SERVER_IP, ip); PreferencesHelper.putString(SERVER_PORT, port); final String jsonData = gson.toJson(recordings); RecordHistoryFragment.saveJSONDataToDisk(id, jsonData); try { Socket socket = new Socket(ip, Integer.valueOf(port)); socket.setSoTimeout(10000); DataOutputStream DOS = null; DOS.writeBytes(jsonData); socket.close(); if (mActivity != null) mActivity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getActivity(), "Sensor data sent to server " + ip + ":" + port, Toast.LENGTH_SHORT).show(); } }); else Log.w("Record", "activity is null"); } catch (Exception e) { e.printStackTrace(); if (mActivity != null) mActivity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getActivity(), "Sensor data failed to send to " + ip + ":" + port, Toast.LENGTH_SHORT).show(); } }); else Log.w("Record", "activity is null"); } return null; } }.execute(); }