List of usage examples for java.net Socket close
public synchronized void close() throws IOException
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * Stops running AUT./* w w w . j a v a 2 s . c om*/ * */ public void stopApplication() { try { Socket client = getSocket(); PrintStream os = new PrintStream(client.getOutputStream(), false, CHARSET_UTF_8); os.println(STOP_APPLICATION); client.close(); boolean appTerminated = false; while (!appTerminated) { try { process.exitValue(); appTerminated = true; LOGGER.info("AUT terminated."); } catch (IllegalThreadStateException e) { LOGGER.info("AUT is shutting down..."); } Thread.sleep(100); } writePerformanceLog(); Runtime.getRuntime().addShutdownHook(addConfigCleaner()); } catch (UnknownHostException e) { LOGGER.error("stopApplication UnknownHostException: ", e); } catch (IOException e) { LOGGER.error("stopApplication IOException ", e); } catch (InterruptedException e) { LOGGER.error("stopApplication ", e); } finally { if (process != null) { process.destroy(); } markApplicationStopped(); } }
From source file:com.emc.storageos.systemservices.impl.upgrade.CoordinatorClientExt.java
/** * Zookeeper leader nodes listens on 2888(see coordinator-var.xml) for follower/observers. * We depends on this behaviour to check if leader election is started * * @param nodeIP//from ww w. jav a 2s .c o m * @param port * @return */ private boolean isZookeeperLeader(String nodeIP, int port) { try { Socket sock = new Socket(); sock.connect(new InetSocketAddress(nodeIP, port), 10000); // 10 seconds timeout sock.close(); return true; } catch (IOException ex) { _log.warn("Unexpected IO errors when checking local coordinator state. {}", ex.toString()); } return false; }
From source file:audio.StreamProxy.java
private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException { if (request == null) { return;// w w w .java 2 s . c o m } Log.d(LOG_TAG, "processing"); String url = request.getRequestLine().getUri(); HttpResponse realResponse = download(url); if (realResponse == null) { return; } Log.d(LOG_TAG, "downloading..."); InputStream data = realResponse.getEntity().getContent(); StatusLine line = realResponse.getStatusLine(); HttpResponse response = new BasicHttpResponse(line); response.setHeaders(realResponse.getAllHeaders()); Log.d(LOG_TAG, "reading headers"); StringBuilder httpString = new StringBuilder(); httpString.append(response.getStatusLine().toString()); httpString.append("\n"); for (Header h : response.getAllHeaders()) { httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n"); } httpString.append("\n"); Log.d(LOG_TAG, "headers done"); try { byte[] buffer = httpString.toString().getBytes(); int readBytes; Log.d(LOG_TAG, "writing to client"); client.getOutputStream().write(buffer, 0, buffer.length); // Start streaming content. byte[] buff = new byte[1024 * 50]; while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) { client.getOutputStream().write(buff, 0, readBytes); } } catch (Exception e) { Log.e("", e.getMessage(), e); } finally { if (data != null) { data.close(); } client.close(); } }
From source file:org.alfresco.webservice.util.ContentUtils.java
/** * Streams content into the repository. Once done a content details string is returned and this can be used to update * a content property in a CML statement. * //from w w w. ja va2s .c o m * @param file the file to stream into the repository * @param host the host name of the destination repository * @param port the port name of the destination repository * @param webAppName the name of the target web application (default 'alfresco') * @param mimetype the mimetype of the file, ignored if null * @param encoding the encoding of the file, ignored if null * @return the content data that can be used to set the content property in a CML statement */ @SuppressWarnings("deprecation") public static String putContent(File file, String host, int port, String webAppName, String mimetype, String encoding) { String result = null; try { String url = "/" + webAppName + "/upload/" + URLEncoder.encode(file.getName(), "UTF-8") + "?ticket=" + AuthenticationUtils.getTicket(); if (mimetype != null) { url = url + "&mimetype=" + mimetype; } if (encoding != null) { url += "&encoding=" + encoding; } String request = "PUT " + url + " HTTP/1.1\n" + "Cookie: JSESSIONID=" + AuthenticationUtils.getAuthenticationDetails().getSessionId() + ";\n" + "Content-Length: " + file.length() + "\n" + "Host: " + host + ":" + port + "\n" + "Connection: Keep-Alive\n" + "\n"; // Open sockets and streams Socket socket = new Socket(host, port); DataOutputStream os = new DataOutputStream(socket.getOutputStream()); DataInputStream is = new DataInputStream(socket.getInputStream()); try { if (socket != null && os != null && is != null) { // Write the request header os.writeBytes(request); // Stream the content onto the server InputStream fileInputStream = new FileInputStream(file); int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = fileInputStream.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); byteCount += bytesRead; } os.flush(); fileInputStream.close(); // Read the response and deal with any errors that might occur boolean firstLine = true; String responseLine; while ((responseLine = is.readLine()) != null) { if (firstLine == true) { if (responseLine.contains("200") == true) { firstLine = false; } else if (responseLine.contains("401") == true) { throw new RuntimeException( "Content could not be uploaded because invalid credentials have been supplied."); } else if (responseLine.contains("403") == true) { throw new RuntimeException( "Content could not be uploaded because user does not have sufficient privileges."); } else { throw new RuntimeException( "Error returned from upload servlet (" + responseLine + ")"); } } else if (responseLine.contains("contentUrl") == true) { result = responseLine; break; } } } } finally { try { // Close the streams and socket if (os != null) { os.close(); } if (is != null) { is.close(); } if (socket != null) { socket.close(); } } catch (Exception e) { throw new RuntimeException("Error closing sockets and streams", e); } } } catch (Exception e) { throw new RuntimeException("Error writing content to repository server", e); } return result; }
From source file:com.meh.nprutil.StreamProxy.java
private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException { if (request == null) { return;// www . j a v a 2s . c o m } Log.d(LOG_TAG, "processing"); String url = request.getRequestLine().getUri(); HttpResponse realResponse = download(url); if (realResponse == null) { return; } Log.d(LOG_TAG, "downloading..."); InputStream data = realResponse.getEntity().getContent(); StatusLine line = realResponse.getStatusLine(); HttpResponse response = new BasicHttpResponse(line); response.setHeaders(realResponse.getAllHeaders()); Log.d(LOG_TAG, "reading headers"); StringBuilder httpString = new StringBuilder(); httpString.append(response.getStatusLine().toString()); httpString.append("\r\n"); for (Header h : response.getAllHeaders()) { httpString.append(h.getName()).append(": ").append(h.getValue()).append("\r\n"); } httpString.append("\r\n"); Log.d(LOG_TAG, "headers done"); try { byte[] buffer = httpString.toString().getBytes(); int readBytes; Log.d(LOG_TAG, "writing to client"); client.getOutputStream().write(buffer, 0, buffer.length); // Start streaming content. byte[] buff = new byte[1024 * 50]; while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) { client.getOutputStream().write(buff, 0, readBytes); } } catch (Exception e) { Log.e("", e.getMessage(), e); } finally { if (data != null) { data.close(); } client.close(); } }
From source file:com.kab.channel66.StreamProxy.java
private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException { if (request == null) { return;//from w w w . ja v a2s .c o m } Log.d(LOG_TAG, "processing"); String url = request.getRequestLine().getUri(); HttpResponse realResponse = download(url); if (realResponse == null) { return; } Log.d(LOG_TAG, "downloading..."); InputStream data = realResponse.getEntity().getContent(); StatusLine line = realResponse.getStatusLine(); HttpResponse response = new BasicHttpResponse(line); response.setHeaders(realResponse.getAllHeaders()); Log.d(LOG_TAG, "reading headers"); StringBuilder httpString = new StringBuilder(); httpString.append(response.getStatusLine().toString()); httpString.append("\n"); for (Header h : response.getAllHeaders()) { httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n"); } httpString.append("\n"); Log.d(LOG_TAG, "headers done"); try { byte[] buffer = httpString.toString().getBytes(); int readBytes = -1; Log.d(LOG_TAG, "writing to client"); client.getOutputStream().write(buffer, 0, buffer.length); // Start streaming content. byte[] buff = new byte[1024 * 50]; while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) { client.getOutputStream().write(buff, 0, readBytes); } } catch (Exception e) { Log.e("", e.getMessage(), e); } finally { if (data != null) { data.close(); } client.close(); } }
From source file:WriteObjectsFromSocket.java
ReaderWriter(Socket rs) { // ///////////////////////////////////////////// // Open a remote stream to the client // ///////////////////////////////////////////// try {// w w w. j a v a2s. co m is = new DataInputStream(rs.getInputStream()); } catch (Exception e) { System.out.println("Unable to get Stream"); return; } // ///////////////////////////////////////////// // Open the file that is to be written to // ///////////////////////////////////////////// try { File theFile = new File("/tmp", "Objects"); System.out.println("The file to be created or overwritten: " + theFile); localFile = new FileOutputStream(theFile); } catch (IOException e) { System.out.println("Open error " + e); return; } // /////////////////////////////////////////// // Look for all the double data constantly // /////////////////////////////////////////// while (writeloop) { // Look for data if we get here that is requests try { inputByte = is.readByte(); // Not the best way to do it // Consider looking for available bytes // and reading that amount. } catch (IOException e) { System.out.println("In the read loop:" + e); writeloop = false; } // /////////////////////////// // We did get something // Write The Data // /////////////////////////// try { localFile.write(inputByte); } catch (IOException e) { System.out.println("Write failed"); writeloop = false; } } // //////////////////////////////// // Close the connection and file // //////////////////////////////// try { rs.close(); is.close(); localFile.close(); } catch (Exception e) { System.out.println("Unable to close "); } System.out.println("Thread exiting"); }
From source file:com.github.lindenb.jvarkit.tools.bamviewgui.BamFileRef.java
private void showIgv(final Object chrom, final Object pos) { if (igvIP == null || igvPort == null) return;//from w ww . ja va 2 s . com Thread thread = new Thread() { @Override public void run() { PrintWriter out = null; BufferedReader in = null; Socket socket = null; try { socket = new Socket(igvIP, igvPort); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println("goto " + chrom + ":" + pos); try { Thread.sleep(5 * 1000); } catch (InterruptedException err2) { } } catch (Exception err) { LOG.info("" + err.getMessage()); } finally { if (in != null) try { in.close(); } catch (Exception err) { } if (out != null) try { out.close(); } catch (Exception err) { } if (socket != null) try { socket.close(); } catch (Exception err) { } } } }; thread.start(); }
From source file:com.mulesoft.agent.monitoring.publisher.ZabbixMonitorPublisher.java
@Override public boolean flush(@NotNull Collection<List<Metric>> listOfMetrics) { Socket zabbixConnection = null; OutputStream out = null;// ww w. jav a2s .com BufferedReader in = null; try { for (List<Metric> metrics : listOfMetrics) { for (Metric metric : metrics) { zabbixConnection = new Socket(zabbixServer, zabbixPort); StringBuilder message = new StringBuilder(); message.append(MESSAGE_START); message.append(host); message.append(MESSAGE_MIDDLE_LEFT); message.append(metric.getName().replaceAll("\\s", "").replace(":", "")); message.append(MESSAGE_MIDDLE_RIGHT); message.append(metric.getValue()); message.append(MESSAGE_END); String s = message.toString(); byte[] chars = s.getBytes(); int length = chars.length; out = zabbixConnection.getOutputStream(); out.write(new byte[] { 'Z', 'B', 'X', 'D', '\1', (byte) (length & 0xFF), (byte) ((length >> 8) & 0x00FF), (byte) ((length >> 16) & 0x0000FF), (byte) ((length >> 24) & 0x000000FF), '\0', '\0', '\0', '\0' }); out.write(chars); out.flush(); in = new BufferedReader(new InputStreamReader(zabbixConnection.getInputStream())); LOGGER.debug("Message sent to Zabbix: " + message.toString()); } } } catch (IOException e) { LOGGER.warn("Failed to establish connection to Zabbix", e); return false; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } if (zabbixConnection != null) { zabbixConnection.close(); } } catch (IOException e) { } } return true; }
From source file:com.mobilyzer.measurements.RRCTask.java
/** * Time how long it takes to do a TCP 3-way handshake, starting from the induced RRC state. * /*from w w w .j a v a 2 s . com*/ * <ol> * <li>Send a packet to initiate the RRC state desired.</li> * <li>Open a TCP connection to the echo host server.</li> * <li>Time how long it took to look it up.</li> * <li>Count the total packets sent, globally on the phone. If more packets were sent than * expected, abort and try again.</li> * <li>Otherwise, save the data for that test and move to the next inter-packet interval. * </ol> * * @param times List of inter-packet intervals, in half-second increments, at which to run the * test * @param desc Stores parameters for the RRC inference tests in general * @throws MeasurementError */ public void runTCPHandshakeTest(final Integer[] times, RRCDesc desc) throws MeasurementError { Logger.d("Active inference TCP test: about to begin"); if (times.length != desc.tcpTest.length) { desc.tcpTest = new int[times.length]; } long startTime = 0; long endTime = 0; try { // For each inter-packet interval... for (int i = 0; i < times.length; i++) { // On a failure, try again until a threshhold is reached. for (int j = 0; j < desc.GIVEUP_THRESHHOLD; j++) { checkIfWifi(); if (stopFlag) { throw new MeasurementError("Cancelled"); } PacketMonitor packetMonitor = new PacketMonitor(); // Induce DCH then wait for specified time InetAddress serverAddr; serverAddr = InetAddress.getByName(desc.echoHost); sendPacket(serverAddr, desc.MAX, desc); waitTime(times[i] * 500, true); // begin test. We test the time to do a 3-way handshake only. startTime = System.currentTimeMillis(); serverAddr = InetAddress.getByName(desc.target); // three-way handshake done when socket created Socket socket = new Socket(serverAddr, 80); endTime = System.currentTimeMillis(); // Check how many packets were sent again. If the expected number // of packets were sent, we can finish and go to the next task. // Otherwise, we have to try again. if (!packetMonitor.isTrafficInterfering(5, 4)) { socket.close(); break; } startTime = 0; endTime = 0; socket.close(); } long rtt = endTime - startTime; try { desc.setTcp(i, (int) rtt); } catch (MeasurementError e) { e.printStackTrace(); } Logger.d("Time for TCP" + rtt); } } catch (InterruptedException e1) { e1.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }