List of usage examples for java.net Socket close
public synchronized void close() throws IOException
From source file:com.tomcat.monitor.zabbix.ZabbixSender.java
public void send(final String zabbixServer, final int zabbixPort, int zabbixTimeout, final String host, final String key, final String value) throws IOException { final byte[] response = new byte[1024]; final long start = System.currentTimeMillis(); final int TIMEOUT = zabbixTimeout * 1000; final StringBuilder message = new StringBuilder("<req><host>"); message.append(new String(Base64.encodeBase64(host.getBytes()))); message.append("</host><key>"); message.append(new String(Base64.encodeBase64(key.getBytes()))); message.append("</key><data>"); message.append(new String(Base64.encodeBase64(value.getBytes()))); message.append("</data></req>"); if (log.isDebugEnabled()) { log.debug("sending " + message); }/*from w w w. ja v a 2 s . c om*/ Socket zabbix = null; OutputStreamWriter out = null; InputStream in = null; try { zabbix = new Socket(zabbixServer, zabbixPort); zabbix.setSoTimeout(TIMEOUT); out = new OutputStreamWriter(zabbix.getOutputStream()); out.write(message.toString()); out.flush(); in = zabbix.getInputStream(); final int read = in.read(response); if (log.isDebugEnabled()) { log.debug("received " + new String(response)); } if (read != 2 || response[0] != 'O' || response[1] != 'K') { log.warn("received unexpected response '" + new String(response) + "' for key '" + key + "'"); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (zabbix != null) { zabbix.close(); } } log.info("send() " + (System.currentTimeMillis() - start) + " ms"); }
From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java
/** * Test the we can ping the agent./*w w w.j a va 2 s . co m*/ * * @throws Exception * When the test failed. */ @Test public void testPing() throws Exception { final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent(); // give the agent some time to open the port Thread.sleep(100); final Socket socket = new Socket(InetAddress.getLocalHost(), org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT); final Writer out = new OutputStreamWriter(socket.getOutputStream()); out.write("agent.ping\n"); out.flush(); final InputStream in = socket.getInputStream(); final byte[] buffer = new byte[1024]; final int read = in.read(buffer); assertEquals(14, read); assertEquals('Z', buffer[0]); assertEquals('B', buffer[1]); assertEquals('X', buffer[2]); assertEquals('D', buffer[3]); assertEquals('1', buffer[13]); // we'll take the rest for granted... socket.close(); agent.stop(); }
From source file:hornet.framework.clamav.service.ClamAVCheckService.java
/** * Fermeture scuris de la socket./* w w w.j a v a 2s .co m*/ * * @param command * command * @param socket * socket * @param buffer * buffer */ private void safeClose(final TypeResponse command, final Socket socket, final BufferedReader buffer) { try { if (buffer != null) { buffer.close(); } } catch (final IOException e) { ClamAVCheckService.LOGGER.error( "Problme de fermeture du buffer lors de l'envoi de la commande'{}' l'antivirus", command, e); } try { if (socket != null) { socket.close(); } } catch (final IOException e) { ClamAVCheckService.LOGGER.error( "Problme de fermeture de la socket lors de l'envoi de la commande'{}' l'antivirus", command, e); } }
From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java
/** * Test that we can use a Java system property to configure the protocol * version on the agent./*from w w w.j ava 2 s .co m*/ * * @throws Exception * When the test failed. */ @Test public void testSetTo11() throws Exception { System.setProperty(ZabbixAgent.PROTOCOL_PROPERTY, "1.1"); assertEquals("1.1", System.getProperty(ZabbixAgent.PROTOCOL_PROPERTY)); final Agent agent = new ZabbixAgent(); // give the agent some time to open the port Thread.sleep(100); final Socket socket = new Socket(InetAddress.getLocalHost(), ZabbixAgent.DEFAULT_PORT); final Writer out = new OutputStreamWriter(socket.getOutputStream()); out.write("system.property[java.version]\n"); out.flush(); final InputStream in = socket.getInputStream(); final byte[] buffer = new byte[1024]; in.read(buffer); final String version = System.getProperty("java.version"); assertEquals(version.charAt(0), buffer[0]); assertEquals(version.charAt(1), buffer[1]); assertEquals(version.charAt(2), buffer[2]); assertEquals(version.charAt(3), buffer[3]); // we'll take the rest for granted... socket.close(); agent.stop(); }
From source file:edu.stanford.epadd.launcher.Main.java
@Override public void run() { out.println("*** running jetty 'stop' thread"); Socket accept; try {/*w w w . java 2 s.c o m*/ accept = socket.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream())); // wait for a readline String line = reader.readLine(); // any input received, stop the server jettyServer.stop(); out.println("*** Stopped the Jetty embedded web server. received: " + line); accept.close(); socket.close(); System.exit(1); // we need to explicitly system.exit because we now use Swing (due to system tray, etc). } catch (Exception e) { throw new RuntimeException(e); } }
From source file:edu.umass.cs.msocket.common.policies.GeoLoadProxyPolicy.java
/** * @throws Exception if a GNS error occurs * @see edu.umass.cs.msocket.common.policies.ProxySelectionPolicy#getNewProxy() */// w w w.j a v a 2 s.c o m @Override public List<InetSocketAddress> getNewProxy() throws Exception { // Lookup for active location service GUIDs final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient(); final GuidEntry guidEntry = gnsCredentials.getGuidEntry(); JSONArray guids; try { guids = gnsClient.fieldRead(proxyGroupName, GnsConstants.ACTIVE_LOCATION_FIELD, guidEntry); } catch (Exception e) { throw new GnsException("Could not find active location services (" + e + ")"); } // Try every location proxy in the list until one works for (int i = 0; i < guids.length(); i++) { // Retrieve the location service IP and connect to it String locationGuid = guids.getString(i); String locationIP = gnsClient.fieldRead(locationGuid, GnsConstants.LOCATION_SERVICE_IP, guidEntry) .getString(0); logger.fine("Contacting location service " + locationIP + " to request " + numProxies + " proxies"); // Location IP is stored as host:port StringTokenizer st = new StringTokenizer(locationIP, ":"); try { // Protocol is send the number of desired proxies and receive strings // containing proxy IP:port Socket s = new Socket(st.nextToken(), Integer.parseInt(st.nextToken())); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); oos.writeInt(numProxies); oos.flush(); List<InetSocketAddress> result = new LinkedList<InetSocketAddress>(); while (!s.isClosed() && result.size() < numProxies) { String proxyIP = ois.readUTF(); StringTokenizer stp = new StringTokenizer(proxyIP, ":"); result.add(new InetSocketAddress(stp.nextToken(), Integer.parseInt(stp.nextToken()))); } if (!s.isClosed()) // We receive all the proxies we need, just close the // socket s.close(); return result; } catch (Exception e) { logger.info("Failed to obtain proxy from location service" + locationIP + " (" + e + ")"); } } throw new GnsException("Could not find any location service to provide a geolocated proxy"); }
From source file:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.java
@Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { Args.notNull(host, "HTTP host"); Args.notNull(remoteAddress, "Remote address"); final Socket sock = socket != null ? socket : createSocket(context); if (localAddress != null) { sock.bind(localAddress);/*from w w w .j a v a 2 s . c om*/ } try { if (connectTimeout > 0 && sock.getSoTimeout() == 0) { sock.setSoTimeout(connectTimeout); } /* if (this.log.isDebugEnabled()) { this.log.debug("Connecting socket to " + remoteAddress + " with timeout " + connectTimeout); } */ sock.connect(remoteAddress, connectTimeout); } catch (final IOException ex) { try { sock.close(); } catch (final IOException ignore) { } throw ex; } // Setup SSL layering if necessary if (sock instanceof SSLSocket) { final SSLSocket sslsock = (SSLSocket) sock; // this.log.debug("Starting handshake"); sslsock.startHandshake(); verifyHostname(sslsock, host.getHostName()); return sock; } else { return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); } }
From source file:gobblin.tunnel.ConnectProxyServer.java
@Override void handleClientSocket(Socket clientSocket) throws IOException { final InputStream clientToProxyIn = clientSocket.getInputStream(); BufferedReader clientToProxyReader = new BufferedReader(new InputStreamReader(clientToProxyIn)); final OutputStream clientToProxyOut = clientSocket.getOutputStream(); String line = clientToProxyReader.readLine(); String connectRequest = ""; while (line != null && isServerRunning()) { connectRequest += line + "\r\n"; if (connectRequest.endsWith("\r\n\r\n")) { break; }// www .j ava2s .c o m line = clientToProxyReader.readLine(); } // connect to given host:port Matcher matcher = hostPortPattern.matcher(connectRequest); if (!matcher.find()) { try { sendConnectResponse("400 Bad Request", clientToProxyOut, null, 0); } finally { clientSocket.close(); stopServer(); } return; } String host = matcher.group(1); int port = Integer.decode(matcher.group(2)); // connect to server Socket serverSocket = new Socket(); try { serverSocket.connect(new InetSocketAddress(host, port)); addSocket(serverSocket); byte[] initialServerResponse = null; int nbytes = 0; if (mixServerAndProxyResponse) { // we want to mix the initial server response with the 200 OK initialServerResponse = new byte[64]; nbytes = serverSocket.getInputStream().read(initialServerResponse); } sendConnectResponse("200 OK", clientToProxyOut, initialServerResponse, nbytes); } catch (IOException e) { try { sendConnectResponse("404 Not Found", clientToProxyOut, null, 0); } finally { clientSocket.close(); stopServer(); } return; } final InputStream proxyToServerIn = serverSocket.getInputStream(); final OutputStream proxyToServerOut = serverSocket.getOutputStream(); _threads.add(new EasyThread() { @Override void runQuietly() throws Exception { try { IOUtils.copy(clientToProxyIn, proxyToServerOut); } catch (IOException e) { LOG.warn("Exception " + e.getMessage() + " on " + getServerSocketPort()); } } }.startThread()); try { if (nBytesToCloseSocketAfter > 0) { // Simulate proxy abruptly closing connection int leftToRead = nBytesToCloseSocketAfter; byte[] buffer = new byte[leftToRead + 256]; while (true) { int numRead = proxyToServerIn.read(buffer, 0, leftToRead); if (numRead < 0) { break; } clientToProxyOut.write(buffer, 0, numRead); clientToProxyOut.flush(); leftToRead -= numRead; if (leftToRead <= 0) { LOG.warn("Cutting connection after " + nBytesToCloseSocketAfter + " bytes"); break; } } } else { IOUtils.copy(proxyToServerIn, clientToProxyOut); } } catch (IOException e) { LOG.warn("Exception " + e.getMessage() + " on " + getServerSocketPort()); } clientSocket.close(); serverSocket.close(); }
From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java
/** * Test robustness./* w ww . jav a2 s .c o m*/ * * @throws Exception * When the test failed. */ @Test public void testMissingArgument() throws Exception { final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent(); // give the agent some time to open the port Thread.sleep(100); final Socket socket = new Socket(InetAddress.getLocalHost(), org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT); final Writer out = new OutputStreamWriter(socket.getOutputStream()); out.write("jmx\n"); out.flush(); final InputStream in = socket.getInputStream(); final byte[] buffer = new byte[1024]; final int read = in.read(buffer); assertEquals(29, read); assertEquals('Z', buffer[0]); assertEquals('B', buffer[1]); assertEquals('X', buffer[2]); assertEquals('D', buffer[3]); assertEquals('N', buffer[17]); assertEquals('O', buffer[18]); assertEquals('T', buffer[19]); // we'll take the rest for granted... socket.close(); agent.stop(); }
From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java
/** * Test robustness.// w ww . j a va 2s .co m * * @throws Exception * When the test failed. */ @Test public void testMissingClose() throws Exception { final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent(); // give the agent some time to open the port Thread.sleep(100); final Socket socket = new Socket(InetAddress.getLocalHost(), org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT); final Writer out = new OutputStreamWriter(socket.getOutputStream()); out.write("jmx[foo\n"); out.flush(); final InputStream in = socket.getInputStream(); final byte[] buffer = new byte[1024]; final int read = in.read(buffer); assertEquals(29, read); assertEquals('Z', buffer[0]); assertEquals('B', buffer[1]); assertEquals('X', buffer[2]); assertEquals('D', buffer[3]); assertEquals('N', buffer[17]); assertEquals('O', buffer[18]); assertEquals('T', buffer[19]); // we'll take the rest for granted... socket.close(); agent.stop(); }