List of usage examples for java.net Socket close
public synchronized void close() throws IOException
From source file:com.meh.IceProxy1.java
private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException { if (request == null) { return;/* ww w .j a v a 2 s.co m*/ } Log.d(tag, "processing"); String url = request.getRequestLine().getUri(); HttpResponse realResponse = download(url); if (realResponse == null) { return; } Log.d(tag, "downloading..."); InputStream data = realResponse.getEntity().getContent(); StatusLine line = realResponse.getStatusLine(); HttpResponse dummyresponse = new BasicHttpResponse(line); dummyresponse.setHeaders(realResponse.getAllHeaders()); Log.d(tag, "reading headers"); StringBuilder httpString = new StringBuilder(); httpString.append(dummyresponse.getStatusLine().toString()); httpString.append("\r\n"); int icyInterval = -1; for (Header h : dummyresponse.getAllHeaders()) { if (ICY_INTERVAL_HEADER.equals(h.getName())) icyInterval = Integer.parseInt(h.getValue()); else httpString.append(h.getName()).append(": ").append(h.getValue()).append("\r\n"); } httpString.append("\r\n"); Log.d(tag, "headers done"); try { byte[] buffer = new byte[1024 * 16]; int totalReadBytes = 0; //not including metadata int readBytes; byte[] httpdata = httpString.toString().getBytes(); client.getOutputStream().write(httpdata, 0, httpdata.length); //now start streaming int bytesSinceLastIcy = 0; while (isRunning && (readBytes = data.read(buffer, 0, buffer.length)) != -1) { totalReadBytes += readBytes; bytesSinceLastIcy += readBytes; if (icyInterval != -1 && bytesSinceLastIcy > icyInterval) { //the icy metadata is in the buffer\ int metadataPos = readBytes - (bytesSinceLastIcy - icyInterval); client.getOutputStream().write(buffer, 0, metadataPos); int metadataLength = buffer[metadataPos] * 16; byte[] metadata = new byte[metadataLength]; System.arraycopy(buffer, metadataPos + 1, metadata, 0, metadataLength); Log.v(tag, new String(metadata)); int remainingStart = metadataPos + 1 + metadataLength; int remainingLen = readBytes - metadataPos - metadataLength - 1; client.getOutputStream().write(buffer, remainingStart, remainingLen); bytesSinceLastIcy = remainingLen; } else client.getOutputStream().write(buffer, 0, readBytes); } } catch (Exception e) { Log.e("", e.getMessage(), e); } finally { if (data != null) { data.close(); } client.close(); } }
From source file:com.bitsofproof.supernode.core.IRCDiscovery.java
@Override public List<InetSocketAddress> discover() { List<InetSocketAddress> al = new ArrayList<InetSocketAddress>(); try {/*www. j a va2s. co m*/ log.trace("Connect to IRC server " + server); Socket socket = new Socket(server, port); PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); String[] answers = new String[] { "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname" }; String line; boolean stop = false; while (!stop && (line = reader.readLine()) != null) { log.trace("IRC receive " + line); for (int i = 0; i < answers.length; ++i) { if (line.contains(answers[i])) { stop = true; break; } } } String nick = "bop" + new SecureRandom().nextInt(Integer.MAX_VALUE); writer.println("NICK " + nick); writer.println("USER " + nick + " 8 * : " + nick); writer.flush(); log.trace("IRC send: I am " + nick); while ((line = reader.readLine()) != null) { log.trace("IRC receive " + line); if (hasCode(line, new String[] { " 004 ", " 433 " })) { break; } } log.trace("IRC send: joining " + channel); writer.println("JOIN " + channel); writer.println("NAMES"); writer.flush(); while ((line = reader.readLine()) != null) { log.trace("IRC receive " + line); if (hasCode(line, new String[] { " 353 " })) { StringTokenizer tokenizer = new StringTokenizer(line, ":"); String t = tokenizer.nextToken(); if (tokenizer.hasMoreElements()) { t = tokenizer.nextToken(); } tokenizer = new StringTokenizer(t); tokenizer.nextToken(); while (tokenizer.hasMoreTokens()) { String w = tokenizer.nextToken().substring(1); if (!tokenizer.hasMoreElements()) { continue; } try { byte[] m = ByteUtils.fromBase58WithChecksum(w); byte[] addr = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff, 0, 0, 0, 0 }; System.arraycopy(m, 0, addr, 12, 4); al.add(new InetSocketAddress(InetAddress.getByAddress(addr), chain.getPort())); } catch (ValidationException e) { log.trace(e.toString()); } } } if (hasCode(line, new String[] { " 366 " })) { break; } } writer.println("PART " + channel); writer.println("QUIT"); writer.flush(); socket.close(); } catch (UnknownHostException e) { log.error("Can not find IRC server " + server, e); } catch (IOException e) { log.error("Can not use IRC server " + server, e); } return al; }
From source file:assignment.HTTPResponse.java
public void serve(HTTPRequest httpRequest, OutputStream outputStream, Socket socket) throws IOException, ParseException, InterruptedException { PrintWriter pw = new PrintWriter(outputStream, true); JSONObject obj = new JSONObject(); if (httpRequest.getHttpMethod().equals("GET")) { String[] url = (httpRequest.getResourceURI()).split("\\?"); if (url[0].equals("/request")) { String ar1[] = url[1].split("&"); String[] name1 = ar1[0].split("="); String connId = name1[1]; String[] name2 = ar1[1].split("="); int timeout = Integer.parseInt(name2[1]); input[i][0] = connId;/*from ww w . j a v a 2s . c om*/ Date startTime = new Date(); Date parsedDate = df.parse(startTime.toString()); Date endTime = new Date(parsedDate.getTime() + (1 * timeout)); input[i][1] = startTime.toString(); input[i][2] = endTime.toString(); i++; obj.put("status", "ok"); try { Thread.currentThread().sleep(timeout); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } pw.println(obj); } else if (url[0].equals("/serverStatus")) { Date now = new Date(); long newDateTime = df.parse((new Date()).toString()).getTime(); String result = ""; JSONArray ja = new JSONArray(); for (int j = 0; j < input.length; j++) { if (input[j][0] != null) { Date end = df.parse(input[j][2]); if (end.compareTo(now) > 0) { long endDateTime = (df.parse(input[j][2])).getTime(); long diff = ((endDateTime - newDateTime) / 1000); JSONObject obj1 = new JSONObject(); obj1.put(input[j][0], diff); result += obj1; } } } pw.println(result); } else { pw.println("Request not supported."); } } else if ((httpRequest.getHttpMethod().equals("PUT")) || (httpRequest.getHttpMethod().equals("POST"))) { if (httpRequest.getResourceURI().equals("/kill")) { boolean found = false; Date now = new Date(); for (int j = 0; j < input.length; j++) { if (input[j][0] != null && input[j][0].equals(httpRequest.getBody())) { Date end = df.parse(input[j][2]); if (end.compareTo(now) > 0) { input[j][2] = now.toString(); found = true; } } } if (found) { obj.put("status", "killed"); } else { obj.put("status", "Invalid connId " + httpRequest.getBody()); } System.out.println(obj); pw.println(obj); } else { pw.println("Request not supported."); } } socket.close(); }
From source file:com.owncloud.android.network.AdvancedSslSocketFactory.java
/** * Verifies the identity of the server. * //ww w . ja v a 2 s . c o m * The server certificate is verified first. * * Then, the host name is compared with the content of the server certificate using the current host name verifier, if any. * @param socket */ private void verifyPeerIdentity(String host, int port, Socket socket) throws IOException { try { CertificateCombinedException failInHandshake = null; /// 1. VERIFY THE SERVER CERTIFICATE through the registered TrustManager (that should be an instance of AdvancedX509TrustManager) try { SSLSocket sock = (SSLSocket) socket; // a new SSLSession instance is created as a "side effect" sock.startHandshake(); } catch (RuntimeException e) { if (e instanceof CertificateCombinedException) { failInHandshake = (CertificateCombinedException) e; } else { Throwable cause = e.getCause(); Throwable previousCause = null; while (cause != null && cause != previousCause && !(cause instanceof CertificateCombinedException)) { previousCause = cause; cause = cause.getCause(); } if (cause != null && cause instanceof CertificateCombinedException) { failInHandshake = (CertificateCombinedException) cause; } } if (failInHandshake == null) { throw e; } failInHandshake.setHostInUrl(host); } /// 2. VERIFY HOSTNAME SSLSession newSession = null; boolean verifiedHostname = true; if (mHostnameVerifier != null) { if (failInHandshake != null) { /// 2.1 : a new SSLSession instance was NOT created in the handshake X509Certificate serverCert = failInHandshake.getServerCertificate(); try { mHostnameVerifier.verify(host, serverCert); } catch (SSLException e) { verifiedHostname = false; } } else { /// 2.2 : a new SSLSession instance was created in the handshake newSession = ((SSLSocket) socket).getSession(); if (!mTrustManager.isKnownServer((X509Certificate) (newSession.getPeerCertificates()[0]))) { verifiedHostname = mHostnameVerifier.verify(host, newSession); } } } /// 3. Combine the exceptions to throw, if any if (!verifiedHostname) { SSLPeerUnverifiedException pue = new SSLPeerUnverifiedException( "Names in the server certificate do not match to " + host + " in the URL"); if (failInHandshake == null) { failInHandshake = new CertificateCombinedException( (X509Certificate) newSession.getPeerCertificates()[0]); failInHandshake.setHostInUrl(host); } failInHandshake.setSslPeerUnverifiedException(pue); pue.initCause(failInHandshake); throw pue; } else if (failInHandshake != null) { SSLHandshakeException hse = new SSLHandshakeException("Server certificate could not be verified"); hse.initCause(failInHandshake); throw hse; } } catch (IOException io) { try { socket.close(); } catch (Exception x) { // NOTHING - irrelevant exception for the caller } throw io; } }
From source file:catalina.core.StandardServer.java
/** * Wait until a proper shutdown command is received, then return. *//*from w w w . j a va 2 s . com*/ public void await() { // Set up a server socket to wait on ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); } catch (IOException e) { System.err.println("StandardServer.await: create[" + port + "]: " + e); e.printStackTrace(); System.exit(1); } // Loop waiting for a connection and a valid command while (true) { // Wait for the next connection Socket socket = null; InputStream stream = null; try { socket = serverSocket.accept(); socket.setSoTimeout(10 * 1000); // Ten seconds stream = socket.getInputStream(); } catch (AccessControlException ace) { System.err.println("StandardServer.accept security exception: " + ace.getMessage()); continue; } catch (IOException e) { System.err.println("StandardServer.await: accept: " + e); e.printStackTrace(); System.exit(1); } // Read a set of characters from the socket StringBuffer command = new StringBuffer(); int expected = 1024; // Cut off to avoid DoS attack while (expected < shutdown.length()) { if (random == null) random = new Random(System.currentTimeMillis()); expected += (random.nextInt() % 1024); } while (expected > 0) { int ch = -1; try { ch = stream.read(); } catch (IOException e) { System.err.println("StandardServer.await: read: " + e); e.printStackTrace(); ch = -1; } if (ch < 32) // Control character or EOF terminates loop break; command.append((char) ch); expected--; } // Close the socket now that we are done with it try { socket.close(); } catch (IOException e) { ; } // Match against our command string boolean match = command.toString().equals(shutdown); if (match) { break; } else System.err.println("StandardServer.await: Invalid command '" + command.toString() + "' received"); } // Close the server socket and return try { serverSocket.close(); } catch (IOException e) { ; } }
From source file:de.prozesskraft.pradar.parts.PradarPartUi3.java
/** * loads variables from ini-file, tests whether server are responding and saves the responding ones to fields * @return void/* w w w . ja v a 2 s. c o m*/ */ void loadIni() { // PradarViewProcessingPage tmp = new PradarViewProcessingPage(this); java.io.File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(this.getClass()) + "/" + "../etc/pradar-gui.ini"); ArrayList<String> pradar_server_list = new ArrayList<String>(); ArrayList<String> license_server_list = new ArrayList<String>(); try { ini = new Ini(inifile); // einlesen der ini-section [pradar-server] for (int x = 1; x <= 5; x++) { if (ini.get("pradar-server", "pradar-server-" + x) != null) { pradar_server_list.add(ini.get("pradar-server", "pradar-server-" + x)); } } // einlesen der ini-section [license-server] for (int x = 1; x <= 3; x++) { if (ini.get("license-server", "license-server-" + x) != null) { license_server_list.add(ini.get("license-server", "license-server-" + x)); } } this.license_server_port_at_hostname = license_server_list; // feststelen ob aktueller user ein admin ist for (String iniUser : ini.get("roles", "admin").split(",")) { if (iniUser.equals(System.getProperty("user.name"))) { this.userAdmin = true; } } } catch (FileNotFoundException e) { log("fatal", "problems with configuration: file not found: " + inifile.getAbsolutePath()); System.exit(1); } catch (InvalidFileFormatException e1) { log("fatal", "problems with configuration: invalid file format: " + inifile.getAbsolutePath()); System.exit(1); // TODO Auto-generated catch block // e1.printStackTrace(); } catch (IOException e1) { log("fatal", "problems with configuration: problems while reading file (IOException): " + inifile.getAbsolutePath()); System.exit(1); // TODO Auto-generated catch block // e1.printStackTrace(); } // // einchecken in die DB // Socket serverSocket = null; boolean pradar_server_not_found = true; // ueber alle pradar-server aus ini-file iterieren und den ersten erfolgreichen merken fuer spaetere anfragen Iterator<String> iter_pradar_server = pradar_server_list.iterator(); while (pradar_server_not_found && iter_pradar_server.hasNext() && (this.pradar_server_port_at_hostname.size() == 0)) { String port_and_machine_as_string = iter_pradar_server.next(); String[] port_and_machine = port_and_machine_as_string.split("@"); int portNumber = Integer.parseInt(port_and_machine[0]); String machineName = port_and_machine[1]; log("info", "determining pradar-server"); log("info", "trying pradar-server " + portNumber + "@" + machineName); try { Socket serverSocket = new Socket(machineName, portNumber); // PrintWriter out = new PrintWriter(serverSocket.getOutputStream(), true); // BufferedReader in = new BufferedReader(new InputStreamReader(serverSocket.getInputStream())); // BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); // // socket einrichten und Out/Input-Streams setzen // serverSocket = new Socket(machineName, portNumber); // log("debug", "server.getOutputStream()"); // OutputStream out = serverSocket.getOutputStream(); // // log("debug", "server.getInputStream()"); // InputStream in = serverSocket.getInputStream(); // // log("debug", "new ObjectOutputStream(...)"); // ObjectOutputStream objectOut = new ObjectOutputStream(out); // // log("debug", "new ObjectInputStream(...)"); // ObjectInputStream objectIn = new ObjectInputStream(in); // log("debug", "streams fertig"); serverSocket.close(); // socket wurde erfolgreich mit dem server verbunden. pradar-server soll fuer weitere Anfragen gemerkt werden this.pradar_server_port_at_hostname.add(port_and_machine_as_string); pradar_server_not_found = false; log("info", "valid pradar-server found at " + portNumber + "@" + machineName); } catch (UnknownHostException e) { // TODO Auto-generated catch block log("warn", "unknown host " + machineName); // e.printStackTrace(); } catch (ConnectException e) { log("warn", "no pradar-server found at " + portNumber + "@" + machineName); // e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block log("warn", "input / output problems at " + portNumber + "@" + machineName); // e.printStackTrace(); } } if (pradar_server_not_found) { log("error", "no pradar-server found. talk to your administrator."); // System.exit(1); } }
From source file:fr.novia.zaproxyplugin.ZAProxy.java
/** * Wait for ZAProxy initialization, so it's ready to use at the end of this method * (otherwise, catch exception). This method is launched on the remote machine (if there is one) * //from w ww . j ava 2 s.c o m * @param timeout the time in sec to try to connect at zap proxy. * @param listener the listener to display log during the job execution in jenkins * @see <a href="https://groups.google.com/forum/#!topic/zaproxy-develop/gZxYp8Og960"> * https://groups.google.com/forum/#!topic/zaproxy-develop/gZxYp8Og960</a> */ private void waitForSuccessfulConnectionToZap(int timeout, BuildListener listener) { int timeoutInMs = getMilliseconds(timeout); int connectionTimeoutInMs = timeoutInMs; int pollingIntervalInMs = getMilliseconds(1); boolean connectionSuccessful = false; long startTime = System.currentTimeMillis(); Socket socket = null; do { try { socket = new Socket(); socket.connect(new InetSocketAddress(evaluatedZapProxyHost, evaluatedZapProxyPort), connectionTimeoutInMs); connectionSuccessful = true; } catch (SocketTimeoutException ignore) { listener.error(ExceptionUtils.getStackTrace(ignore)); throw new BuildException("Unable to connect to ZAP's proxy after " + timeout + " seconds."); } catch (IOException ignore) { // and keep trying but wait some time first... try { Thread.sleep(pollingIntervalInMs); } catch (InterruptedException e) { listener.error(ExceptionUtils.getStackTrace(ignore)); throw new BuildException("The task was interrupted while sleeping between connection polling.", e); } long ellapsedTime = System.currentTimeMillis() - startTime; if (ellapsedTime >= timeoutInMs) { listener.error(ExceptionUtils.getStackTrace(ignore)); throw new BuildException("Unable to connect to ZAP's proxy after " + timeout + " seconds."); } connectionTimeoutInMs = (int) (timeoutInMs - ellapsedTime); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { listener.error(ExceptionUtils.getStackTrace(e)); } } } } while (!connectionSuccessful); }
From source file:com.cerema.cloud2.lib.common.network.AdvancedSslSocketFactory.java
/** * Verifies the identity of the server. * /*from w w w . j a v a 2s . c om*/ * The server certificate is verified first. * * Then, the host name is compared with the content of the server certificate using the current host name verifier, * if any. * @param socket */ private void verifyPeerIdentity(String host, int port, Socket socket) throws IOException { try { CertificateCombinedException failInHandshake = null; /// 1. VERIFY THE SERVER CERTIFICATE through the registered TrustManager /// (that should be an instance of AdvancedX509TrustManager) try { SSLSocket sock = (SSLSocket) socket; // a new SSLSession instance is created as a "side effect" sock.startHandshake(); } catch (RuntimeException e) { if (e instanceof CertificateCombinedException) { failInHandshake = (CertificateCombinedException) e; } else { Throwable cause = e.getCause(); Throwable previousCause = null; while (cause != null && cause != previousCause && !(cause instanceof CertificateCombinedException)) { previousCause = cause; cause = cause.getCause(); } if (cause != null && cause instanceof CertificateCombinedException) { failInHandshake = (CertificateCombinedException) cause; } } if (failInHandshake == null) { throw e; } failInHandshake.setHostInUrl(host); } /// 2. VERIFY HOSTNAME SSLSession newSession = null; boolean verifiedHostname = true; if (mHostnameVerifier != null) { if (failInHandshake != null) { /// 2.1 : a new SSLSession instance was NOT created in the handshake X509Certificate serverCert = failInHandshake.getServerCertificate(); try { mHostnameVerifier.verify(host, serverCert); } catch (SSLException e) { verifiedHostname = false; } } else { /// 2.2 : a new SSLSession instance was created in the handshake newSession = ((SSLSocket) socket).getSession(); if (!mTrustManager.isKnownServer((X509Certificate) (newSession.getPeerCertificates()[0]))) { verifiedHostname = mHostnameVerifier.verify(host, newSession); } } } /// 3. Combine the exceptions to throw, if any if (!verifiedHostname) { SSLPeerUnverifiedException pue = new SSLPeerUnverifiedException( "Names in the server certificate do not match to " + host + " in the URL"); if (failInHandshake == null) { failInHandshake = new CertificateCombinedException( (X509Certificate) newSession.getPeerCertificates()[0]); failInHandshake.setHostInUrl(host); } failInHandshake.setSslPeerUnverifiedException(pue); pue.initCause(failInHandshake); throw pue; } else if (failInHandshake != null) { SSLHandshakeException hse = new SSLHandshakeException("Server certificate could not be verified"); hse.initCause(failInHandshake); throw hse; } } catch (IOException io) { try { socket.close(); } catch (Exception x) { // NOTHING - irrelevant exception for the caller } throw io; } }