List of usage examples for java.net ServerSocket close
public void close() throws IOException
From source file:org.eclipse.aether.transport.http.HttpTransporterTest.java
@Test(timeout = 1000L) public void testRequestTimeout() throws Exception { session.setConfigProperty(ConfigurationProperties.REQUEST_TIMEOUT, 100); ServerSocket server = new ServerSocket(0); newTransporter("http://localhost:" + server.getLocalPort()); try {//from w w w. j a v a 2s . co m try { transporter.get(new GetTask(URI.create("repo/file.txt"))); fail("Expected error"); } catch (SocketTimeoutException e) { assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } finally { server.close(); } }
From source file:org.cloudifysource.shell.validators.NicAddressValidator.java
@Override public void validate() throws CLIValidationException { ServerSocket serverSocket = null; try {/*www. j a v a 2 s. c om*/ if (StringUtils.isBlank(nicAddress)) { nicAddress = Constants.getHostAddress(); } if (StringUtils.isBlank(nicAddress)) { throw new IllegalArgumentException("NIC Address is empty"); } IPUtils.testOpenServerSocket(nicAddress); } catch (UnknownHostException uhe) { // thrown if the host could not be determined. throw new CLIValidationException(uhe, 121, CloudifyErrorMessages.NIC_VALIDATION_ABORTED_UNKNOWN_HOST.getName(), uhe.getMessage()); } catch (IOException ioe) { // thrown if an I/O error occurs when creating the socket or connecting to it. throw new CLIValidationException(ioe, 122, CloudifyErrorMessages.NIC_VALIDATION_ABORTED_IO_ERROR.getName(), nicAddress, ioe.getMessage()); } catch (SecurityException se) { // thrown if a security manager exists and doesn't allow the operation. throw new CLIValidationException(se, 123, CloudifyErrorMessages.NIC_VALIDATION_ABORTED_NO_PERMISSION.getName(), se.getMessage()); } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (Exception e) { //ignore } } } }
From source file:org.apache.flink.runtime.taskmanager.TaskManagerStartupTest.java
/** * Tests that the TaskManager fails synchronously when the actor system port * is in use.//from www .j ava 2 s .c om * * @throws Throwable */ @Test(expected = BindException.class) public void testStartupWhenTaskmanagerActorPortIsUsed() throws BindException { ServerSocket blocker = null; try { final String localHostName = "localhost"; final InetAddress localBindAddress = InetAddress.getByName(NetUtils.getWildcardIPAddress()); // block some port blocker = new ServerSocket(0, 50, localBindAddress); final int port = blocker.getLocalPort(); TaskManager.runTaskManager(localHostName, ResourceID.generate(), port, new Configuration(), TaskManager.class); fail("This should fail with an IOException"); } catch (IOException e) { // expected. validate the error message List<Throwable> causes = StartupUtils.getExceptionCauses(e, new ArrayList<Throwable>()); for (Throwable cause : causes) { if (cause instanceof BindException) { throw (BindException) cause; } } fail("This should fail with an exception caused by BindException"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (blocker != null) { try { blocker.close(); } catch (IOException e) { // no need to log here } } } }
From source file:org.apache.htrace.impl.TestDroppedSpans.java
/** * Test that we write to the dropped spans log when htraced is unreachable. *///from w w w. ja va 2 s . c om @Test(timeout = 60000) public void testSpansDroppedBecauseOfUnreachableHTraced() throws Exception { final String logPath = new File(tempDir.toFile(), "testSpansDroppedBecauseOfUnreachableHTraced") .getAbsolutePath(); // Open a local socket. We know that nobody is listening on this socket, so // all attempts to send to it will fail. final ServerSocket serverSocket = new ServerSocket(0); HTracedSpanReceiver rcvr = null; try { HTraceConfiguration conf = HTraceConfiguration.fromMap(new HashMap<String, String>() { { put(Conf.ADDRESS_KEY, "127.0.0.1:" + serverSocket.getLocalPort()); put(TracerId.TRACER_ID_KEY, "testSpansDroppedBecauseOfUnreachableHTraced"); put(Conf.DROPPED_SPANS_LOG_PATH_KEY, logPath); put(Conf.DROPPED_SPANS_LOG_MAX_SIZE_KEY, "78"); put(Conf.CONNECT_TIMEOUT_MS_KEY, "1"); put(Conf.IO_TIMEOUT_MS_KEY, "1"); put(Conf.FLUSH_RETRY_DELAYS_KEY, "1,1"); } }); rcvr = new HTracedSpanReceiver(conf); rcvr.receiveSpan(new MilliSpan.Builder().begin(123).end(456).description("FooBar").build()); HTracedSpanReceiver tmpRcvr = rcvr; rcvr = null; tmpRcvr.close(); List<String> lines = Files.readAllLines(Paths.get(logPath), StandardCharsets.UTF_8); Assert.assertTrue(lines.size() >= 1); Assert.assertTrue(lines.get(0).contains("Failed to flush ")); } finally { serverSocket.close(); if (rcvr != null) { rcvr.close(); } } }
From source file:org.skfiy.typhon.startup.Typhon.java
private void await() { ServerSocket serverSocket = null; try {//ww w. j a v a 2 s .c om serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress(server.getHost(), server.getPort()), 1); } catch (IOException e) { throw new TyphonException(e); } for (;;) { Socket socket = null; try { socket = serverSocket.accept(); InputStream in = socket.getInputStream(); byte[] cur = server.getShutdown().getBytes(StandardCharsets.UTF_8); byte[] buf = new byte[cur.length]; int l = in.read(buf); // if (l == cur.length && Arrays.equals(cur, buf)) { break; } } catch (IOException e) { } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { // nothing } } } } try { serverSocket.close(); } catch (IOException e) { // nothing } // ?? stop(); }
From source file:org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfigurationTests.java
@Test public void specificPortsViaPropertiesWithClash() throws Exception { int managementPort = ports.get().management; ServerSocket serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress(managementPort)); try {// w w w . jav a 2 s . com EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:" + ports.get().server, "management.port:" + ports.get().management); this.applicationContext.register(RootConfig.class, EndpointConfig.class, BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); this.thrown.expect(WebServerException.class); this.applicationContext.refresh(); } finally { serverSocket.close(); } }
From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java
protected final void doWithBlockedPort(BlockedPortAction action) throws IOException { int port = SocketUtils.findAvailableTcpPort(40000); ServerSocket serverSocket = new ServerSocket(); for (int i = 0; i < 10; i++) { try {/*from w w w.ja va 2 s . com*/ serverSocket.bind(new InetSocketAddress(port)); break; } catch (Exception ex) { } } try { action.run(port); } finally { serverSocket.close(); } }
From source file:org.apache.hadoop.hive.metastore.MetaStoreUtils.java
/** * Finds a free port on the machine, but allow the * ability to specify a port number to not use, no matter what. *//*from w ww .j a va 2s. c om*/ public static int findFreePortExcepting(int portToExclude) throws IOException { ServerSocket socket1 = null; ServerSocket socket2 = null; try { socket1 = new ServerSocket(0); socket2 = new ServerSocket(0); if (socket1.getLocalPort() != portToExclude) { return socket1.getLocalPort(); } // If we're here, then socket1.getLocalPort was the port to exclude // Since both sockets were open together at a point in time, we're // guaranteed that socket2.getLocalPort() is not the same. return socket2.getLocalPort(); } finally { if (socket1 != null) { socket1.close(); } if (socket2 != null) { socket2.close(); } } }
From source file:ext.services.network.TestNetworkUtils.java
/** * Test get connection url proxy with proxy. * //from w w w .ja v a 2 s.co m * * @throws Exception the exception */ public void testGetConnectionURLProxyWithProxy() throws Exception { final ServerSocket socket = new ServerSocket(PROXY_PORT); Thread thread = new Thread("ProxySocketAcceptThread") { @Override public void run() { try { while (!bStop) { Socket sock = socket.accept(); Log.debug("Accepted connection, sending back garbage and close socket..."); sock.getOutputStream().write(1); sock.close(); } } catch (IOException e) { Log.error(e); } } }; thread.setDaemon(true); // to finish tests even if this is still running thread.start(); Log.debug("Using local port: " + socket.getLocalPort()); try { // useful content when inet access is allowed Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "false"); HttpURLConnection connection = NetworkUtils.getConnection(new java.net.URL(URL), new Proxy(Type.SOCKS, "localhost", socket.getLocalPort(), "user", "password")); assertNotNull(connection); connection.disconnect(); } finally { bStop = true; socket.close(); thread.join(); } }
From source file:org.apache.jackrabbit.oak.remote.http.handler.RemoteServerIT.java
private int getRandomPort() throws Exception { ServerSocket serverSocket = null; try {//from w w w .j a v a2 s . com serverSocket = new ServerSocket(0); return serverSocket.getLocalPort(); } finally { if (serverSocket != null) { serverSocket.close(); } } }