List of usage examples for java.net ServerSocket close
public void close() throws IOException
From source file:brooklyn.util.ssh.BashCommandsIntegrationTest.java
License:asdf
@Test(groups = "Integration", dependsOnMethods = "testSudo") public void testWaitForPortFreeWhenFreedAfterStart() throws Exception { ServerSocket serverSocket = openServerSocket(); try {// w ww . j a v a 2s. c o m int port = serverSocket.getLocalPort(); String cmd = BashCommands.waitForPortFree(port, Duration.THIRTY_SECONDS, false); ProcessTaskWrapper<String> t = execRequiringZeroAndReturningStdout(loc, cmd); exec.submit(t); // sleep for long enough to ensure the ssh command is definitely executing Thread.sleep(5 * 1000); assertFalse(t.isDone()); serverSocket.close(); assertTrue(Networking.isPortAvailable(port)); String output = t.get(); assertFalse(output.contains("still in use"), "output=" + output); } finally { serverSocket.close(); } }
From source file:org.openmrs.module.mirebalais.integration.MirthIT.java
private String listenForResults() throws IOException { ServerSocket listener = new ServerSocket(6660); // TODO: store this port in a global property? listener.setSoTimeout(20000); // don't wait more than 20 seconds for an incoming connection Socket mirthConnection = listener.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(mirthConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line;/*from w w w . java2 s.co m*/ while ((line = reader.readLine()) != null) { sb.append(line); } // TODO: need an acknowledgement? mirthConnection.close(); listener.close(); return sb.toString(); }
From source file:org.fabrician.enabler.DockerContainer.java
private boolean checkServerPortInUse(int port) { if (port == UNDEFINED_PORT) { return false; }//from ww w . jav a 2s. co m ServerSocket srv = null; boolean inUse = false; try { srv = new ServerSocket(port); srv.close(); } catch (Exception e) { getEngineLogger().finest("serverPortInUse: debug exception: " + e); inUse = true; } return inUse; }
From source file:org.apache.cxf.dosgi.singlebundle.AggregatedActivatorTest.java
public void testHttpServicePortInUse() throws Exception { BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.replay(bc);/* w ww. j a v a 2s . c o m*/ ServerSocket s = null; try { try { // now lets block the default port s = new ServerSocket(Integer.parseInt(AggregatedActivator.DEFAULT_HTTP_PORT)); } catch (Exception e) { // if someone else already has it, thats fine too } assertNull("Precondition failed", System.getProperty(AggregatedActivator.HTTP_PORT_PROPERTY)); new AggregatedActivator().setHttpServicePort(bc); assertTrue("The " + AggregatedActivator.HTTP_PORT_PROPERTY + " property should have been set", System.getProperty(AggregatedActivator.HTTP_PORT_PROPERTY).length() > 0); } finally { if (s != null) { s.close(); } } }
From source file:org.mapfish.print.FakeHttpd.java
public void run() { try {// ww w .ja va 2s . c o m LOGGER.info("starting"); ServerSocket serverSocket = new ServerSocket(port); LOGGER.info("started"); synchronized (starting) { starting.set(false); starting.notify(); } while (true) { Socket socket = serverSocket.accept(); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintStream output = new PrintStream(socket.getOutputStream()); final boolean stayAlive = handleHttp(input, output); input.close(); output.close(); socket.close(); if (!stayAlive) { break; } } serverSocket.close(); LOGGER.info("stopped"); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.y20k.transistor.helpers.MetadataHelper.java
private void createShoutcastProxyConnection() { closeShoutcastProxyConnection();//from ww w . j a va 2 s . co m mProxyRunning = true; final StringBuffer shoutcastProxyUri = new StringBuffer(); try { new Thread(new Runnable() { @Override public void run() { Socket proxy = null; URLConnection connection = null; try { final ServerSocket proxyServer = new ServerSocket(0, 1, InetAddress.getLocalHost()); shoutcastProxyUri.append("http://localhost:") .append(String.valueOf(proxyServer.getLocalPort())).append("/"); LogHelper.v(LOG_TAG, "createProxyConnection: " + shoutcastProxyUri.toString()); proxy = proxyServer.accept(); mProxyConnection = proxy; proxyServer.close(); connection = new URL(mStreamUri).openConnection(); shoutcastProxyReaderLoop(proxy, connection); } catch (Exception e) { LogHelper.e(LOG_TAG, "Error: Unable to create proxy server. (" + e + ")"); } mProxyRunning = false; try { if (connection != null) { ((HttpURLConnection) connection).disconnect(); } } catch (Exception ee) { LogHelper.e(LOG_TAG, "Error: Unable to disconnect HttpURLConnection. (" + ee + ")"); } try { if (proxy != null && !proxy.isClosed()) { proxy.close(); } } catch (Exception eee) { LogHelper.e(LOG_TAG, "Error: Unable to close proxy. (" + eee + ")"); } } }).start(); while (shoutcastProxyUri.length() == 0) { try { Thread.sleep(10); } catch (Exception e) { LogHelper.e(LOG_TAG, "Error: Unable to Thread.sleep. (" + e + ")"); } } mShoutcastProxy = shoutcastProxyUri.toString(); } catch (Exception e) { LogHelper.e(LOG_TAG, "createProxyConnection: Cannot create new listening socket on localhost: " + e.toString()); mProxyRunning = false; mShoutcastProxy = ""; } }
From source file:com.mirth.connect.manager.ManagerController.java
/** * Test a port to see if it is already in use. * // w w w.ja v a 2 s.c om * @param port * The port to test. * @param name * A friendly name to display in case of an error. * @return An error message, or null if the port is not in use and there was no error. */ private String testPort(String port, String name) { ServerSocket socket = null; try { socket = new ServerSocket(Integer.parseInt(port)); } catch (NumberFormatException ex) { return name + " port is invalid: " + port; } catch (IOException ex) { return name + " port is already in use: " + port; } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { return "Could not close test socket for " + name + ": " + port; } } } return null; }
From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java
private void closeQuietly(ServerSocket server) { try {//from w w w . j a va 2 s . c o m if (server != null) server.close(); } catch (Exception e) { System.err.println("Exception during SocketServer close: " + e); } }
From source file:org.apache.flink.runtime.taskmanager.TaskManagerStartupTest.java
/** * Tests that the task manager start-up fails if the network stack cannot be initialized. * @throws Exception/* w w w.j a v a 2s .c om*/ */ @Test(expected = IOException.class) public void testStartupWhenNetworkStackFailsToInitialize() throws Exception { ServerSocket blocker = null; try { blocker = new ServerSocket(0, 50, InetAddress.getByName("localhost")); final Configuration cfg = new Configuration(); cfg.setString(ConfigConstants.TASK_MANAGER_HOSTNAME_KEY, "localhost"); cfg.setInteger(ConfigConstants.TASK_MANAGER_DATA_PORT_KEY, blocker.getLocalPort()); cfg.setInteger(ConfigConstants.TASK_MANAGER_MEMORY_SIZE_KEY, 1); TaskManager.startTaskManagerComponentsAndActor(cfg, ResourceID.generate(), null, "localhost", Option.<String>empty(), Option.<LeaderRetrievalService>empty(), false, TaskManager.class); } finally { if (blocker != null) { try { blocker.close(); } catch (IOException e) { // ignore, best effort } } } }
From source file:org.apache.geode.internal.net.SSLSocketIntegrationTest.java
@Test public void configureClientSSLSocketCanTimeOut() throws Exception { final Semaphore serverCoordination = new Semaphore(0); // configure a non-SSL server socket. We will connect // a client SSL socket to it and demonstrate that the // handshake times out final ServerSocket serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress(SocketCreator.getLocalHost(), 0)); Thread serverThread = new Thread() { public void run() { serverCoordination.release(); try (Socket clientSocket = serverSocket.accept()) { System.out.println("server thread accepted a connection"); serverCoordination.acquire(); } catch (Exception e) { System.err.println("accept failed"); e.printStackTrace();// w w w . j a v a 2 s .c om } try { serverSocket.close(); } catch (IOException e) { // ignored } System.out.println("server thread is exiting"); } }; serverThread.setName("SocketCreatorJUnitTest serverSocket thread"); serverThread.setDaemon(true); serverThread.start(); serverCoordination.acquire(); SocketCreator socketCreator = SocketCreatorFactory .getSocketCreatorForComponent(SecurableCommunicationChannel.SERVER); int serverSocketPort = serverSocket.getLocalPort(); try { Awaitility.await("connect to server socket").atMost(30, TimeUnit.SECONDS).until(() -> { try { Socket clientSocket = socketCreator.connectForClient( SocketCreator.getLocalHost().getHostAddress(), serverSocketPort, 2000); clientSocket.close(); System.err.println( "client successfully connected to server but should not have been able to do so"); return false; } catch (SocketTimeoutException e) { // we need to verify that this timed out in the handshake // code System.out.println("client connect attempt timed out - checking stack trace"); StackTraceElement[] trace = e.getStackTrace(); for (StackTraceElement element : trace) { if (element.getMethodName().equals("configureClientSSLSocket")) { System.out.println("client connect attempt timed out in the appropriate method"); return true; } } // it wasn't in the configuration method so we need to try again } catch (IOException e) { // server socket may not be in accept() yet, causing a connection-refused // exception } return false; }); } finally { serverCoordination.release(); } }