List of usage examples for java.net ServerSocket close
public void close() throws IOException
From source file:com.mtgi.analytics.test.AbstractPerformanceTestCase.java
protected void testPerformance(TestCase basisJob, TestCase testJob) throws Throwable { //cache serialized form to save time on repeated test iterations byte[] controlData = serializeJob(new TestProcess(testThreads, testLoop, basisJob)); byte[] testData = serializeJob(new TestProcess(testThreads, testLoop, testJob)); StatisticsMBean controlStats = new StatisticsMBean(); controlStats.setUnits("nanoseconds"); StatisticsMBean testStats = new StatisticsMBean(); testStats.setUnits("nanoseconds"); ServerSocket listener = new ServerSocket(0); try {// w ww .j av a2s.co m int port = listener.getLocalPort(); ProcessBuilder pb = new ProcessBuilder(System.getProperty("java.home") + separator + "/bin/java", "-server", "-cp", System.getProperty("java.class.path"), TestProcess.class.getName(), String.valueOf(port)); pb.redirectErrorStream(false); //run several iterations of the test, alternating between instrumented and not //to absorb the affects of garbage collection. for (int i = 0; i < TEST_ITERATIONS; ++i) { System.out.println("iteration " + i); //switch the order of test / control runs during iteration to reduce any //bias that order might cause if (i % 2 == 0) { runTest(listener, pb, testStats, testData); runTest(listener, pb, controlStats, controlData); } else { runTest(listener, pb, controlStats, controlData); runTest(listener, pb, testStats, testData); } assertEquals("basis and test have same sample size after iteration " + i, controlStats.getCount(), testStats.getCount()); } } finally { listener.close(); } double basisNanos = controlStats.getAverageTime(); double cpuCoefficient = basisNanos / (double) expectedBasis; double expectedAverage = cpuCoefficient * averageOverhead; double expectedMax = cpuCoefficient * maxOverhead; System.out.println("control:\n" + controlStats); System.out.println("test:\n" + testStats); System.out.println("CPU Coefficient: " + cpuCoefficient); System.out.println("basisNanos: " + basisNanos); //compute the overhead as the difference between instrumented and uninstrumented //runs. we want the per-event overhead to be less than .5 ms. double delta = testStats.getAverageTime() - basisNanos; //deltaWorst, my favorite sausage. mmmmmm, dellltttaaaWwwwooorrsstt. double deltaWorst = testStats.getMaxTime() - controlStats.getMaxTime(); System.out.println("Maximum expected average overhead: " + expectedAverage); System.out.println("Average overhead: " + delta); System.out.println("Maximum expected worst case overhead: " + expectedMax); System.out.println("Worst case overhead: " + deltaWorst); assertTrue("Average overhead per method cannot exceed " + expectedAverage + "ns [ " + delta + " ]", delta <= expectedAverage); assertTrue("Worst case per method overhead cannot exceed " + expectedMax + "ns [ " + deltaWorst + " ]", deltaWorst <= expectedMax); }
From source file:disko.flow.analyzers.socket.SocketReceiver.java
@SuppressWarnings("unchecked") public void process(C ctx, Ports ports) throws InterruptedException { log.debug("Listening to port " + port); ServerSocket serverSocket = null; try {//from ww w. j a v a 2 s. c om serverSocket = new ServerSocket(port); serverSocket.setSoTimeout(5000); } catch (Exception e) { throw new RuntimeException(e); } log.debug("Server socket created."); Set<OutputPort> closedPorts = new HashSet<OutputPort>(); try { while (closedPorts.size() < ports.getOutputCount()) { Message message = readMessage(serverSocket); if (message == null) break; OutputPort output = ports.getOutput(message.getChannelId()); if (output == null) { log.error("OutputPort to channel " + message.getChannelId() + " not found!"); } else if (message.getData() == null) { log.debug("Received EOS of " + message.getChannelId()); if (!ignoreEOF) { output.close(); closedPorts.add(output); } } else if (output.put(message.getData())) { log.debug("Accepted " + message); } else { closedPorts.add(output); log.debug("Ignoring " + message); } } } catch (Throwable t) { log.error("Exception at SocketReceiver.", t); } log.debug("All SocketREceiver outputs closed, exiting normally."); try { serverSocket.close(); } catch (Exception ioe) { log.error(ioe); } }
From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java
@Test public void testNetSingleUseNoInbound() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();/* w ww .j a va 2s . c om*/ for (int i = 0; i < 2; i++) { Socket socket = server.accept(); semaphore.release(); byte[] b = new byte[6]; readFully(socket.getInputStream(), b); semaphore.release(); socket.close(); } server.close(); } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(10000); ccf.start(); ccf.setSingleUse(true); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); assertTrue(semaphore.tryAcquire(4, 10000, TimeUnit.MILLISECONDS)); done.set(true); ccf.stop(); }
From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java
@Test public void testNioSingleUseNoInbound() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();//from ww w . j a v a 2 s . co m for (int i = 0; i < 2; i++) { Socket socket = server.accept(); semaphore.release(); byte[] b = new byte[8]; readFully(socket.getInputStream(), b); semaphore.release(); socket.close(); } server.close(); } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(5000); ccf.start(); ccf.setSingleUse(true); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test.1").build()); handler.handleMessage(MessageBuilder.withPayload("Test.2").build()); assertTrue(semaphore.tryAcquire(4, 10000, TimeUnit.MILLISECONDS)); done.set(true); ccf.stop(); }
From source file:org.globus.gsi.gssapi.test.GlobusGSSContextTest.java
public void testStreamInitAcceptContext() throws Exception { assertTrue("client ctx already established.", !clientContext.isEstablished()); assertTrue("server ctx already established.", !serverContext.isEstablished()); clientContext.requestCredDeleg(true); assertTrue(clientContext.getCredDelegState()); clientContext.requestConf(false);/*from ww w. jav a 2 s . c om*/ serverContext.requestConf(true); ServerSocket serverSocket = new ServerSocket(0); Server serverThread = new Server(serverSocket, serverContext); serverThread.start(); Socket client = new Socket(InetAddress.getLocalHost(), serverSocket.getLocalPort()); OutputStream out = client.getOutputStream(); InputStream in = client.getInputStream(); while (!clientContext.isEstablished()) { clientContext.initSecContext(in, out); out.flush(); } // make sure the thread is complete serverThread.join(); client.close(); serverSocket.close(); if (serverThread.getException() != null) { throw serverThread.getException(); } assertTrue("client ctx not established.", clientContext.isEstablished()); assertTrue("server ctx not established.", serverContext.isEstablished()); // just run some wrap/unwrap tests runWrapTests(true, false, 0); }
From source file:org.nuxeo.launcher.config.ConfigurationGenerator.java
/** * Checks if port is available on given address. * * @param port port to check for availability * @throws ConfigurationException Throws an exception if address is unavailable. * @since 5.5/*from w ww .j a va 2 s . c o m*/ */ public static void checkPortAvailable(InetAddress address, int port) throws ConfigurationException { if ((port == 0) || (port == -1)) { log.warn("Port is set to " + Integer.toString(port) + " - assuming it is disabled - skipping availability check"); return; } if (port < MIN_PORT || port > MAX_PORT) { throw new IllegalArgumentException("Invalid port: " + port); } ServerSocket socketTCP = null; // DatagramSocket socketUDP = null; try { log.debug("Checking availability of port " + port + " on address " + address); socketTCP = new ServerSocket(port, 0, address); socketTCP.setReuseAddress(true); // socketUDP = new DatagramSocket(port, address); // socketUDP.setReuseAddress(true); // return true; } catch (IOException e) { throw new ConfigurationException(e.getMessage() + ": " + address + ":" + port, e); } finally { // if (socketUDP != null) { // socketUDP.close(); // } if (socketTCP != null) { try { socketTCP.close(); } catch (IOException e) { // Do not throw } } } }
From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java
@Test public void testNetSingleUseWithInbound() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();/* w ww . j av a 2s. com*/ for (int i = 1; i < 3; i++) { Socket socket = server.accept(); semaphore.release(); byte[] b = new byte[6]; readFully(socket.getInputStream(), b); b = ("Reply" + i + "\r\n").getBytes(); socket.getOutputStream().write(b); socket.close(); } server.close(); } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(10000); ccf.start(); ccf.setSingleUse(true); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(ccf); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS)); Set<String> replies = new HashSet<String>(); for (int i = 0; i < 2; i++) { Message<?> mOut = channel.receive(10000); assertNotNull(mOut); replies.add(new String((byte[]) mOut.getPayload())); } assertTrue(replies.remove("Reply1")); assertTrue(replies.remove("Reply2")); done.set(true); ccf.stop(); }
From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java
@Test public void testNioSingleUseWithInbound() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); final AtomicBoolean done = new AtomicBoolean(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();//w w w. j a v a 2 s . c om for (int i = 1; i < 3; i++) { Socket socket = server.accept(); semaphore.release(); byte[] b = new byte[6]; readFully(socket.getInputStream(), b); b = ("Reply" + i + "\r\n").getBytes(); socket.getOutputStream().write(b); socket.close(); } server.close(); } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port); ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); ccf.setSerializer(serializer); ccf.setDeserializer(serializer); ccf.setSoTimeout(10000); ccf.start(); ccf.setSingleUse(true); TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); handler.setConnectionFactory(ccf); TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter(); adapter.setConnectionFactory(ccf); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); assertTrue(latch.await(10, TimeUnit.SECONDS)); handler.handleMessage(MessageBuilder.withPayload("Test").build()); handler.handleMessage(MessageBuilder.withPayload("Test").build()); assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS)); Set<String> replies = new HashSet<String>(); for (int i = 0; i < 2; i++) { Message<?> mOut = channel.receive(10000); assertNotNull(mOut); replies.add(new String((byte[]) mOut.getPayload())); } assertTrue(replies.remove("Reply1")); assertTrue(replies.remove("Reply2")); done.set(true); ccf.stop(); }
From source file:org.rhq.storage.installer.StorageInstaller.java
private void isPortBound(String address, int port, String portName, int potentialErrorCode) throws StorageInstallerException { ServerSocket serverSocket = null; try {/* w w w. j a v a 2 s. co m*/ serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress(address, port)); } catch (BindException e) { throw new StorageInstallerException("The " + portName + " (" + address + ":" + port + ") is already in use. " + "Installation cannot proceed.", potentialErrorCode); } catch (IOException e) { // We only log a warning here and let the installation proceed in case the // exception is something that can be ignored. log.warn("An unexpected error occurred while checking the " + portName + " port", e); } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { log.error("An error occurred trying to close the connection to the " + portName, e); } } } }
From source file:com.tomagoyaky.jdwp.IOUtils.java
/** * Closes a <code>ServerSocket</code> unconditionally. * <p/>/*from w w w. j a v a 2s. c om*/ * Equivalent to {@link ServerSocket#close()}, except any exceptions will be ignored. * This is typically used in finally blocks. * <p/> * Example code: * <pre> * ServerSocket socket = null; * try { * socket = new ServerSocket(); * // process socket * socket.close(); * } catch (Exception e) { * // error handling * } finally { * IOUtils.closeQuietly(socket); * } * </pre> * * @param sock the ServerSocket to close, may be null or already closed * @since 2.2 */ public static void closeQuietly(final ServerSocket sock) { if (sock != null) { try { sock.close(); } catch (final IOException ioe) { // ignored } } }