Java Code Examples for java.net.BindException

The following are top voted examples for showing how to use java.net.BindException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: hadoop-oss   File: TestServer.java   View source code 6 votes vote down vote up
@Test
public void testBindError() throws Exception {
  Configuration conf = new Configuration();
  ServerSocket socket = new ServerSocket();
  InetSocketAddress address = new InetSocketAddress("0.0.0.0",0);
  socket.bind(address);
  try {
    int min = socket.getLocalPort();
    conf.set("TestRange", min+"-"+min);
    

    ServerSocket socket2 = new ServerSocket();
    InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0);
    boolean caught = false;
    try {
      Server.bind(socket2, address2, 10, conf, "TestRange");
    } catch (BindException e) {
      caught = true;
    } finally {
      socket2.close();
    }
    assertTrue("Failed to catch the expected bind exception",caught);
  } finally {
    socket.close();
  }
}
 
Example 2
Project: owa-notifier   File: InternalWebServer.java   View source code 6 votes vote down vote up
/**
    * Build a new instance of InternalWebServer
    * @param nonce 
    * 	A string to verify in responses
    * @throws IOException
    * 	In case of Exception when starting webserver
    */
public InternalWebServer(UUID nonce) throws IOException {
	this.listenPort = Integer.parseInt(OwaNotifier.getInstance().getProps().getProperty("listenPort", "8080"));
	this.nonce = nonce;
	// Search an available port
	while(this.socket == null) {
		try {
			InetAddress[] IP=InetAddress.getAllByName("localhost");
			if(IP.length < 1) {
				throw new IOException("Unable to find localhost ip");
			}
			this.socket = new ServerSocket(this.listenPort, 10, IP[0]); // Start, listen on port 8080
			logger.info("Use listen " + this.socket.getInetAddress().toString() + ":" + this.listenPort);
			
		} catch (BindException e){
			this.listenPort = this.listenPort +1;
			OwaNotifier.getInstance().setProps("listenPort", this.listenPort + "");
		}
	}

	// detach thread
	serverThread = new Thread(this);
	serverThread.start();
}
 
Example 3
Project: JInsight   File: TestWebServer.java   View source code 6 votes vote down vote up
public TestWebServer() throws IOException {

    int port = 9000;
    boolean bound = false;
    do {
      try {
        httpServer.bind(new InetSocketAddress(port), 0);
        bound = true;
      } catch (BindException e) {
        port++;
      }
    } while (!bound && port < 12000);

    httpServer.createContext(ECHO_ENDPOINT, new EchoHandler());

    httpServer.start();
  }
 
Example 4
Project: monarch   File: SocketCreator.java   View source code 6 votes vote down vote up
public ServerSocket createServerSocket(int nport, int backlog, InetAddress bindAddr,
    List<GatewayTransportFilter> transportFilters, int socketBufferSize) throws IOException {
  if (transportFilters.isEmpty()) {
    return createServerSocket(nport, backlog, bindAddr, socketBufferSize);
  } else {
    printConfig();
    ServerSocket result = new TransportFilterServerSocket(transportFilters);
    result.setReuseAddress(true);
    // Set the receive buffer size before binding the socket so
    // that large buffers will be allocated on accepted sockets (see
    // java.net.ServerSocket.setReceiverBufferSize javadocs)
    result.setReceiveBufferSize(socketBufferSize);
    try {
      result.bind(new InetSocketAddress(bindAddr, nport), backlog);
    } catch (BindException e) {
      BindException throwMe =
          new BindException(LocalizedStrings.SocketCreator_FAILED_TO_CREATE_SERVER_SOCKET_ON_0_1
              .toLocalizedString(new Object[] {bindAddr, Integer.valueOf(nport)}));
      throwMe.initCause(e);
      throw throwMe;
    }
    return result;
  }
}
 
Example 5
Project: hadoop   File: TestValidateConfigurationSettings.java   View source code 6 votes vote down vote up
/**
 * Tests setting the rpc port to the same as the web port to test that 
 * an exception
 * is thrown when trying to re-use the same port
 */
@Test(expected = BindException.class, timeout = 300000)
public void testThatMatchingRPCandHttpPortsThrowException() 
    throws IOException {

  NameNode nameNode = null;
  try {
    Configuration conf = new HdfsConfiguration();
    File nameDir = new File(MiniDFSCluster.getBaseDirectory(), "name");
    conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
        nameDir.getAbsolutePath());

    Random rand = new Random();
    final int port = 30000 + rand.nextInt(30000);

    // set both of these to the same port. It should fail.
    FileSystem.setDefaultUri(conf, "hdfs://localhost:" + port);
    conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "127.0.0.1:" + port);
    DFSTestUtil.formatNameNode(conf);
    nameNode = new NameNode(conf);
  } finally {
    if (nameNode != null) {
      nameNode.stop();
    }
  }
}
 
Example 6
Project: hadoop   File: TestServer.java   View source code 6 votes vote down vote up
@Test
public void testBindError() throws Exception {
  Configuration conf = new Configuration();
  ServerSocket socket = new ServerSocket();
  InetSocketAddress address = new InetSocketAddress("0.0.0.0",0);
  socket.bind(address);
  try {
    int min = socket.getLocalPort();
    conf.set("TestRange", min+"-"+min);
    

    ServerSocket socket2 = new ServerSocket();
    InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0);
    boolean caught = false;
    try {
      Server.bind(socket2, address2, 10, conf, "TestRange");
    } catch (BindException e) {
      caught = true;
    } finally {
      socket2.close();
    }
    assertTrue("Failed to catch the expected bind exception",caught);
  } finally {
    socket.close();
  }
}
 
Example 7
Project: jdk8u-jdk   File: RmiBootstrapTest.java   View source code 6 votes vote down vote up
/**
 * Test a configuration file which should make the bootstrap fail.
 * The test is assumed to have succeeded if the bootstrap fails.
 * @return null if the test succeeds, an error message otherwise.
 **/
private String testConfigurationKo(File conf,int port) {
    String errStr = null;
    for (int i = 0; i < PORT_TEST_LEN; i++) {
        try {
            errStr = testConfiguration(conf,port+testPort++);
            break;
        } catch (BindException e) {
            // port conflict; try another port
        }
    }
    if (errStr == null) {
        return "Configuration " +
            conf + " should have failed!";
    }
    System.out.println("Configuration " +
                       conf + " failed as expected");
    log.debug("runko","Error was: " + errStr);
    return null;
}
 
Example 8
Project: jdk8u-jdk   File: RmiBootstrapTest.java   View source code 6 votes vote down vote up
/**
 * Test a configuration file. Determines whether the bootstrap
 * should succeed or fail depending on the file name:
 *     *ok.properties: bootstrap should succeed.
 *     *ko.properties: bootstrap or connection should fail.
 * @return null if the test succeeds, an error message otherwise.
 **/
private String testConfigurationFile(String fileName) {
    File file = new File(fileName);
    final String portStr = System.getProperty("rmi.port",null);
    final int port       = portStr != null ?
                            Integer.parseInt(portStr) : basePort;

    if (fileName.endsWith("ok.properties")) {
        String errStr = null;
        for (int i = 0; i < PORT_TEST_LEN; i++) {
            try {
                errStr = testConfiguration(file,port+testPort++);
                return errStr;
            } catch (BindException e) {
                // port conflict; try another port
            }
        }
        return "Can not locate available port";
    }
    if (fileName.endsWith("ko.properties")) {
        return testConfigurationKo(file,port+testPort++);
    }
    return fileName +
        ": test file suffix must be one of [ko|ok].properties";
}
 
Example 9
Project: openjdk-jdk10   File: JMXStatusTest.java   View source code 6 votes vote down vote up
@Test
public final void testAgentRemote() throws Exception {
    while (true) {
        try {
            int[] ports = PortAllocator.allocatePorts(1);
            jcmd.start(
                "jmxremote.port=" + ports[0],
                "jmxremote.authenticate=false",
                "jmxremote.ssl=false"
            );
            String status = jcmd.status();

            assertStatusMatches(REMOTE_AGENT_STATUS, status);
            return;
        } catch (BindException e) {
            System.out.println("Failed to allocate ports. Retrying ...");
        }
    }
}
 
Example 10
Project: openjdk-jdk10   File: JMXStatusPerfCountersTest.java   View source code 6 votes vote down vote up
/**
 * After enabling the remote agent the 'sun.management.JMXConnectorServer.remote.enabled'
 * counter will be exported with value of '0' - corresponding to the actual
 * version of the associated remote connector perf counters.
 * @throws Exception
 */
@Test
public void testRemoteEnabled() throws Exception {
    while (true) {
        try {
            int[] ports = PortAllocator.allocatePorts(1);
            jcmd.start(
                "jmxremote.port=" + ports[0],
                "jmxremote.authenticate=false",
                "jmxremote.ssl=false"
            );
            String v = getCounters().getProperty(REMOTE_STATUS_KEY);
            assertNotNull(v);
            assertEquals("0", v);
            return;
        } catch (BindException e) {
            System.out.println("Failed to allocate ports. Retrying ...");
        }
    }
}
 
Example 11
Project: openjdk-jdk10   File: JMXStatusPerfCountersTest.java   View source code 6 votes vote down vote up
/**
 * After disabling the remote agent the value of 'sun.management.JMXConnectorServer.remote.enabled'
 * counter will become '-1'.
 * @throws Exception
 */
@Test
public void testRemoteDisabled() throws Exception {
    while (true) {
        try {
            int[] ports = PortAllocator.allocatePorts(1);
            jcmd.start(
                "jmxremote.port=" + ports[0],
                "jmxremote.authenticate=false",
                "jmxremote.ssl=false"
            );
            jcmd.stop();
            String v = getCounters().getProperty(REMOTE_STATUS_KEY);
            assertNotNull(v);
            assertEquals("-1", v);
            return;
        } catch (BindException e) {
            System.out.println("Failed to allocate ports. Retrying ...");
        }
    }
}
 
Example 12
Project: dremio-oss   File: BasicServer.java   View source code 6 votes vote down vote up
public int bind(final int initialPort, boolean allowPortHunting) {
  int port = initialPort - 1;
  while (true) {
    try {
      allChannels.add(b.bind(++port).sync().channel());
      break;
    } catch (Exception e) {
      // TODO(DRILL-3026):  Revisit:  Exception is not (always) BindException.
      // One case is "java.io.IOException: bind() failed: Address already in
      // use".
      if (e instanceof BindException && allowPortHunting) {
        continue;
      }
      throw UserException.resourceError( e )
            .addContext( "Server", rpcConfig.getName())
            .message( "Could not bind to port %s.", port )
            .build(logger);
    }
  }

  connect = !connect;
  logger.info("[{}]: Server started on port {}.", rpcConfig.getName(), port);
  return port;
}
 
Example 13
Project: yaacc-code   File: YaaccUpnpServerService.java   View source code 6 votes vote down vote up
public RequestListenerThread(Context context) throws IOException, BindException {
	serversocket = new ServerSocket(PORT);
	params = new BasicHttpParams();
	params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
			.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
			.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true).setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

	// Set up the HTTP protocol processor
	BasicHttpProcessor httpProcessor = new BasicHttpProcessor();
	httpProcessor.addInterceptor(new ResponseDate());
	httpProcessor.addInterceptor(new ResponseServer());
	httpProcessor.addInterceptor(new ResponseContent());
	httpProcessor.addInterceptor(new ResponseConnControl());

	// Set up the HTTP service
	this.httpService = new YaaccHttpService(httpProcessor, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), context);

}
 
Example 14
Project: ditb   File: TestIPv6NIOServerSocketChannel.java   View source code 6 votes vote down vote up
/**
 * Creates a NIO ServerSocketChannel, and gets the ServerSocket from
 * there. Then binds the obtained socket.
 * This fails on Windows with Oracle JDK1.6.0u33, if the passed InetAddress is a
 * IPv6 address. Works on Oracle JDK 1.7.
 */
private void bindNIOServerSocket(InetAddress inetAddr) throws IOException {
  while (true) {
    int port = HBaseTestingUtility.randomFreePort();
    InetSocketAddress addr = new InetSocketAddress(inetAddr, port);
    ServerSocketChannel channel = null;
    ServerSocket serverSocket = null;
    try {
      channel = ServerSocketChannel.open();
      serverSocket = channel.socket();
      serverSocket.bind(addr); // This does not work
      break;
    } catch (BindException ex) {
      //continue
    } finally {
      if (serverSocket != null) {
        serverSocket.close();
      }
      if (channel != null) {
        channel.close();
      }
    }  
  }
}
 
Example 15
Project: ditb   File: TestIPv6NIOServerSocketChannel.java   View source code 6 votes vote down vote up
/**
 * Checks whether we are effected by the JDK issue on windows, and if so
 * ensures that we are running with preferIPv4Stack=true.
 */
@Test
public void testServerSocket() throws IOException {
  byte[] addr = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
  InetAddress inetAddr = InetAddress.getByAddress(addr);

  try {
    bindServerSocket(inetAddr);
    bindNIOServerSocket(inetAddr);
    //if on *nix or windows JDK7, both will pass
  } catch(java.net.SocketException ex) {
    //On Windows JDK6, we will get expected exception:
    //java.net.SocketException: Address family not supported by protocol family
    //or java.net.SocketException: Protocol family not supported
    Assert.assertFalse(ex.getClass().isInstance(BindException.class));
    Assert.assertTrue(ex.getMessage().toLowerCase().contains("protocol family"));
    LOG.info("Received expected exception:");
    LOG.info(ex);

    //if this is the case, ensure that we are running on preferIPv4=true
    ensurePreferIPv4();
  }
}
 
Example 16
Project: silvertunnel-ng   File: HiddenServiceInstance.java   View source code 6 votes vote down vote up
/**
 * Assign a HiddenServicePortInstance to a port.
 * 
 * @param instance
 *            instance inclusive port number
 * @throws BindException
 *             if the port is already in use
 */
public synchronized void putHiddenServicePortInstance(
		HiddenServicePortInstance instance) throws BindException
{
	// check that port is still available
	final int port = instance.getPort();
	final HiddenServicePortInstance old = getHiddenServicePortInstance(port);
	if (old != null && old.isOpen())
	{
		// port is already occupied
		throw new BindException("port=" + port
				+ " is already in use - instance=" + instance
				+ " cannot be bound to");
	}

	// reserve the port
	listenPortsOfThisHiddenService.put(port, instance);
	instance.setHiddenServiceInstance(this);
}
 
Example 17
Project: openjdk9   File: Security.java   View source code 6 votes vote down vote up
private static void directProxyTest(int proxyPort, boolean samePort) throws IOException, InterruptedException {
    Object proxy = null;
    try {
        proxy = getProxy(proxyPort, true);
    } catch (BindException e) {
        System.out.println("Bind failed");
        throw e;
    } catch (Throwable ee) {
        throw new RuntimeException(ee);
    }
    System.out.println("Proxy port = " + proxyPort);
    if (!samePort)
        proxyPort++;

    HttpClient cl = HttpClient.create()
            .proxy(ProxySelector.of(
                            new InetSocketAddress("127.0.0.1", proxyPort)))
            .build();
    clients.add(cl);

    URI u = URI.create("http://127.0.0.1:" + port + "/files/foo.txt");
    HttpRequest request = cl.request(u)
            .headers("X-Foo", "bar", "X-Bar", "foo")
            .GET();
    HttpResponse response = request.response();
}
 
Example 18
Project: openjdk9   File: JMXStatusTest.java   View source code 6 votes vote down vote up
@Test
public final void testAgentRemote() throws Exception {
    while (true) {
        try {
            int[] ports = PortAllocator.allocatePorts(1);
            jcmd.start(
                "jmxremote.port=" + ports[0],
                "jmxremote.authenticate=false",
                "jmxremote.ssl=false"
            );
            String status = jcmd.status();

            assertStatusMatches(REMOTE_AGENT_STATUS, status);
            return;
        } catch (BindException e) {
            System.out.println("Failed to allocate ports. Retrying ...");
        }
    }
}
 
Example 19
Project: vespa   File: Application.java   View source code 6 votes vote down vote up
private Application build() throws Exception {
    Application app = null;
    Exception exception = null;

    // if we get a bind exception, then retry a few times (may conflict with parallel test runs)
    for (int i = 0; i < 5; i++) {
        try {
            generateXml();
            app = new Application(path, networking, true);
            break;
        } catch (Error e) { // the container thinks this is really serious, in this case is it not in the cause is a BindException
            // catch bind error and reset container
            if (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause() instanceof BindException) {
                exception = (Exception) e.getCause().getCause();
                com.yahoo.container.Container.resetInstance(); // this is needed to be able to recreate the container from config again
            } else {
                throw new Exception(e.getCause());
            }
        }
    }

    if (app == null) {
        throw exception;
    }
    return app;
}
 
Example 20
Project: openjdk9   File: JMXStatusPerfCountersTest.java   View source code 6 votes vote down vote up
/**
 * After enabling the remote agent the 'sun.management.JMXConnectorServer.remote.enabled'
 * counter will be exported with value of '0' - corresponding to the actual
 * version of the associated remote connector perf counters.
 * @throws Exception
 */
@Test
public void testRemoteEnabled() throws Exception {
    while (true) {
        try {
            int[] ports = PortAllocator.allocatePorts(1);
            jcmd.start(
                "jmxremote.port=" + ports[0],
                "jmxremote.authenticate=false",
                "jmxremote.ssl=false"
            );
            String v = getCounters().getProperty(REMOTE_STATUS_KEY);
            assertNotNull(v);
            assertEquals("0", v);
            return;
        } catch (BindException e) {
            System.out.println("Failed to allocate ports. Retrying ...");
        }
    }
}
 
Example 21
Project: openjdk9   File: JMXStatusPerfCountersTest.java   View source code 6 votes vote down vote up
/**
 * After disabling the remote agent the value of 'sun.management.JMXConnectorServer.remote.enabled'
 * counter will become '-1'.
 * @throws Exception
 */
@Test
public void testRemoteDisabled() throws Exception {
    while (true) {
        try {
            int[] ports = PortAllocator.allocatePorts(1);
            jcmd.start(
                "jmxremote.port=" + ports[0],
                "jmxremote.authenticate=false",
                "jmxremote.ssl=false"
            );
            jcmd.stop();
            String v = getCounters().getProperty(REMOTE_STATUS_KEY);
            assertNotNull(v);
            assertEquals("-1", v);
            return;
        } catch (BindException e) {
            System.out.println("Failed to allocate ports. Retrying ...");
        }
    }
}
 
Example 22
Project: ThriftyPaxos   File: NetUtils.java   View source code 6 votes vote down vote up
private static ServerSocket createServerSocketTry(int port, boolean ssl) {
    try {
        InetAddress bindAddress = getBindAddress();
        if (ssl) {
            return CipherFactory.createServerSocket(port, bindAddress);
        }
        if (bindAddress == null) {
            return new ServerSocket(port);
        }
        return new ServerSocket(port, 0, bindAddress);
    } catch (BindException be) {
        throw DbException.get(ErrorCode.EXCEPTION_OPENING_PORT_2,
                be, "" + port, be.toString());
    } catch (IOException e) {
        throw DbException.convertIOException(e, "port: " + port + " ssl: " + ssl);
    }
}
 
Example 23
Project: aliyun-oss-hadoop-fs   File: TestValidateConfigurationSettings.java   View source code 6 votes vote down vote up
/**
 * Tests setting the rpc port to the same as the web port to test that 
 * an exception
 * is thrown when trying to re-use the same port
 */
@Test(expected = BindException.class, timeout = 300000)
public void testThatMatchingRPCandHttpPortsThrowException() 
    throws IOException {

  NameNode nameNode = null;
  try {
    Configuration conf = new HdfsConfiguration();
    File nameDir = new File(MiniDFSCluster.getBaseDirectory(), "name");
    conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
        nameDir.getAbsolutePath());

    Random rand = new Random();
    final int port = 30000 + rand.nextInt(30000);

    // set both of these to the same port. It should fail.
    FileSystem.setDefaultUri(conf, "hdfs://localhost:" + port);
    conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "127.0.0.1:" + port);
    DFSTestUtil.formatNameNode(conf);
    nameNode = new NameNode(conf);
  } finally {
    if (nameNode != null) {
      nameNode.stop();
    }
  }
}
 
Example 24
Project: LunaticSMTP   File: EmailServer.java   View source code 6 votes vote down vote up
public static StartResult start(int port) {
    try {
        smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(listener), new SMTPAuthHandlerFactory());
        smtpServer.setPort(port);
        smtpServer.start();

        return new StartResult(true, null);
    } catch (Throwable e) {
        log.error("Failed to start SMTP server", e);

        if (e.getCause() instanceof BindException) {
            return new StartResult(false, String.format(Messages.get("%s, port: %s"), e.getCause().getMessage(), port));
        } else if (e.getCause() instanceof IllegalArgumentException && e.getMessage().contains("out of range")) {
            return new StartResult(false, String.format(Messages.get("server.error.outofrange"), port));
        } else {
            return new StartResult(false, e.getLocalizedMessage());
        }
    }
}
 
Example 25
Project: StreamProcessingInfrastructure   File: Leader.java   View source code 6 votes vote down vote up
Leader(QuorumPeer self,LeaderZooKeeperServer zk) throws IOException {
    this.self = self;
    try {
        if (self.getQuorumListenOnAllIPs()) {
            ss = new ServerSocket(self.getQuorumAddress().getPort());
        } else {
            ss = new ServerSocket();
        }
        ss.setReuseAddress(true);
        if (!self.getQuorumListenOnAllIPs()) {
            ss.bind(self.getQuorumAddress());
        }
    } catch (BindException e) {
        if (self.getQuorumListenOnAllIPs()) {
            LOG.error("Couldn't bind to port " + self.getQuorumAddress().getPort(), e);
        } else {
            LOG.error("Couldn't bind to " + self.getQuorumAddress(), e);
        }
        throw e;
    }
    this.zk=zk;
}
 
Example 26
Project: SecureKeeper   File: Leader.java   View source code 6 votes vote down vote up
Leader(QuorumPeer self,LeaderZooKeeperServer zk) throws IOException {
    this.self = self;
    try {
        if (self.getQuorumListenOnAllIPs()) {
            ss = new ServerSocket(self.getQuorumAddress().getPort());
        } else {
            ss = new ServerSocket();
        }
        ss.setReuseAddress(true);
        if (!self.getQuorumListenOnAllIPs()) {
            ss.bind(self.getQuorumAddress());
        }
    } catch (BindException e) {
        if (self.getQuorumListenOnAllIPs()) {
            LOG.error("Couldn't bind to port " + self.getQuorumAddress().getPort(), e);
        } else {
            LOG.error("Couldn't bind to " + self.getQuorumAddress(), e);
        }
        throw e;
    }
    this.zk = zk;
}
 
Example 27
Project: leopard   File: AbstractWebServer.java   View source code 6 votes vote down vote up
/**
 * 智能选择port.
 * 
 * @param port
 * @return
 * @throws BindException
 */
protected int getAutoPort(int port) throws BindException {
	if (System.getProperty("os.name").startsWith("Mac")) {
		if (port == 80) {
			port = 8080;
		}
		return port;
	}
	try {
		checkOpened(port);
	}
	catch (BindException e) {
		if (port == 80) {
			checkOpened(8080);
			port = 8080;
		}
		else {
			throw e;
		}
	}
	return port;
}
 
Example 28
Project: rxjava2-extras   File: FlowableServerSocketTest.java   View source code 6 votes vote down vote up
@Test
public void errorEmittedIfServerSocketBusy() throws IOException {
    reset();
    TestSubscriber<Object> ts = TestSubscriber.create();
    ServerSocket socket = null;
    int port = 12345;
    try {
        socket = new ServerSocket(port);
        IO.serverSocket(port).readTimeoutMs(10000).bufferSize(5).create().subscribe(ts);
        ts.assertNoValues();
        ts.assertNotComplete();
        ts.assertTerminated();
        ts.assertError(new Predicate<Throwable>() {
            @Override
            public boolean test(Throwable e) throws Exception {
                return e instanceof BindException;
            }
        });
    } finally {
        socket.close();
    }
}
 
Example 29
Project: gemfirexd-oss   File: UpdateStatementConstraintCheckTest.java   View source code 6 votes vote down vote up
/** keeping a few tests with mcast-port */
private static Connection getConnectionWithRandomMcastPort()
    throws SQLException {
  Properties props = new Properties();
  RETRY: while (true) {
    final int mcastPort = AvailablePort
        .getRandomAvailablePort(AvailablePort.JGROUPS);
    props.setProperty("mcast-port", String.valueOf(mcastPort));
    try {
      return getConnection(props);
    } catch (SQLException ex) {
      if ("XJ040".equals(ex.getSQLState())) {
        // check if a BindException then retry
        Throwable t = ex;
        while ((t = t.getCause()) != null) {
          if (t instanceof BindException) {
            continue RETRY;
          }
        }
      }
      throw ex;
    }
  }
}
 
Example 30
Project: gemfirexd-oss   File: PortHelper.java   View source code 6 votes vote down vote up
/**
 * Returns true if a cause of the given (non-null) exception is a
 * BindException with message containing {@link #ADDRESS_ALREADY_IN_USE}.
 * or a SocketException with message containing {@link #UNRECOGNIZED_SOCKET}.
 */
public static boolean addressAlreadyInUse(Throwable t) {
  if (t == null) {
    throw new IllegalArgumentException("Exception cannot be null");
  }
  Throwable root = t;
  while (root != null) {
    if (root instanceof BindException &&
        root.getMessage() != null &&
        root.getMessage().contains(ADDRESS_ALREADY_IN_USE)) {
      Log.getLogWriter().warning("Got BindException: " + ADDRESS_ALREADY_IN_USE);
      return true;
    }
    if (root instanceof SocketException &&
        root.getMessage() != null &&
        root.getMessage().contains(UNRECOGNIZED_SOCKET)) {
      Log.getLogWriter().warning("Got SocketException: " + UNRECOGNIZED_SOCKET);
      return true;
    }
    root = root.getCause();
  }
  return false;
}
 
Example 31
Project: big-c   File: TestValidateConfigurationSettings.java   View source code 6 votes vote down vote up
/**
 * Tests setting the rpc port to the same as the web port to test that 
 * an exception
 * is thrown when trying to re-use the same port
 */
@Test(expected = BindException.class, timeout = 300000)
public void testThatMatchingRPCandHttpPortsThrowException() 
    throws IOException {

  NameNode nameNode = null;
  try {
    Configuration conf = new HdfsConfiguration();
    File nameDir = new File(MiniDFSCluster.getBaseDirectory(), "name");
    conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
        nameDir.getAbsolutePath());

    Random rand = new Random();
    final int port = 30000 + rand.nextInt(30000);

    // set both of these to the same port. It should fail.
    FileSystem.setDefaultUri(conf, "hdfs://localhost:" + port);
    conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "127.0.0.1:" + port);
    DFSTestUtil.formatNameNode(conf);
    nameNode = new NameNode(conf);
  } finally {
    if (nameNode != null) {
      nameNode.stop();
    }
  }
}
 
Example 32
Project: big-c   File: TestServer.java   View source code 6 votes vote down vote up
@Test
public void testBindError() throws Exception {
  Configuration conf = new Configuration();
  ServerSocket socket = new ServerSocket();
  InetSocketAddress address = new InetSocketAddress("0.0.0.0",0);
  socket.bind(address);
  try {
    int min = socket.getLocalPort();
    conf.set("TestRange", min+"-"+min);
    

    ServerSocket socket2 = new ServerSocket();
    InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0);
    boolean caught = false;
    try {
      Server.bind(socket2, address2, 10, conf, "TestRange");
    } catch (BindException e) {
      caught = true;
    } finally {
      socket2.close();
    }
    assertTrue("Failed to catch the expected bind exception",caught);
  } finally {
    socket.close();
  }
}
 
Example 33
Project: zookeeper   File: Leader.java   View source code 6 votes vote down vote up
Leader(QuorumPeer self,LeaderZooKeeperServer zk) throws IOException {
    this.self = self;
    try {
        if (self.getQuorumListenOnAllIPs()) {
            ss = new ServerSocket(self.getQuorumAddress().getPort());
        } else {
            ss = new ServerSocket();
        }
        ss.setReuseAddress(true);
        if (!self.getQuorumListenOnAllIPs()) {
            ss.bind(self.getQuorumAddress());
        }
    } catch (BindException e) {
        if (self.getQuorumListenOnAllIPs()) {
            LOG.error("Couldn't bind to port " + self.getQuorumAddress().getPort(), e);
        } else {
            LOG.error("Couldn't bind to " + self.getQuorumAddress(), e);
        }
        throw e;
    }
    this.zk=zk;
}
 
Example 34
Project: jdk8u_jdk   File: RmiBootstrapTest.java   View source code 6 votes vote down vote up
/**
 * Test a configuration file which should make the bootstrap fail.
 * The test is assumed to have succeeded if the bootstrap fails.
 * @return null if the test succeeds, an error message otherwise.
 **/
private String testConfigurationKo(File conf,int port) {
    String errStr = null;
    for (int i = 0; i < PORT_TEST_LEN; i++) {
        try {
            errStr = testConfiguration(conf,port+testPort++);
            break;
        } catch (BindException e) {
            // port conflict; try another port
        }
    }
    if (errStr == null) {
        return "Configuration " +
            conf + " should have failed!";
    }
    System.out.println("Configuration " +
                       conf + " failed as expected");
    log.debug("runko","Error was: " + errStr);
    return null;
}
 
Example 35
Project: jdk8u_jdk   File: RmiBootstrapTest.java   View source code 6 votes vote down vote up
/**
 * Test a configuration file. Determines whether the bootstrap
 * should succeed or fail depending on the file name:
 *     *ok.properties: bootstrap should succeed.
 *     *ko.properties: bootstrap or connection should fail.
 * @return null if the test succeeds, an error message otherwise.
 **/
private String testConfigurationFile(String fileName) {
    File file = new File(fileName);
    final String portStr = System.getProperty("rmi.port",null);
    final int port       = portStr != null ?
                            Integer.parseInt(portStr) : basePort;

    if (fileName.endsWith("ok.properties")) {
        String errStr = null;
        for (int i = 0; i < PORT_TEST_LEN; i++) {
            try {
                errStr = testConfiguration(file,port+testPort++);
                return errStr;
            } catch (BindException e) {
                // port conflict; try another port
            }
        }
        return "Can not locate available port";
    }
    if (fileName.endsWith("ko.properties")) {
        return testConfigurationKo(file,port+testPort++);
    }
    return fileName +
        ": test file suffix must be one of [ko|ok].properties";
}
 
Example 36
Project: lookaside_java-1.8.0-openjdk   File: RmiBootstrapTest.java   View source code 6 votes vote down vote up
/**
 * Test a configuration file which should make the bootstrap fail.
 * The test is assumed to have succeeded if the bootstrap fails.
 * @return null if the test succeeds, an error message otherwise.
 **/
private String testConfigurationKo(File conf,int port) {
    String errStr = null;
    for (int i = 0; i < PORT_TEST_LEN; i++) {
        try {
            errStr = testConfiguration(conf,port+testPort++);
            break;
        } catch (BindException e) {
            // port conflict; try another port
        }
    }
    if (errStr == null) {
        return "Configuration " +
            conf + " should have failed!";
    }
    System.out.println("Configuration " +
                       conf + " failed as expected");
    log.debug("runko","Error was: " + errStr);
    return null;
}
 
Example 37
Project: lookaside_java-1.8.0-openjdk   File: RmiBootstrapTest.java   View source code 6 votes vote down vote up
/**
 * Test a configuration file. Determines whether the bootstrap
 * should succeed or fail depending on the file name:
 *     *ok.properties: bootstrap should succeed.
 *     *ko.properties: bootstrap or connection should fail.
 * @return null if the test succeeds, an error message otherwise.
 **/
private String testConfigurationFile(String fileName) {
    File file = new File(fileName);
    final String portStr = System.getProperty("rmi.port",null);
    final int port       = portStr != null ?
                            Integer.parseInt(portStr) : basePort;

    if (fileName.endsWith("ok.properties")) {
        String errStr = null;
        for (int i = 0; i < PORT_TEST_LEN; i++) {
            try {
                errStr = testConfiguration(file,port+testPort++);
                return errStr;
            } catch (BindException e) {
                // port conflict; try another port
            }
        }
        return "Can not locate available port";
    }
    if (fileName.endsWith("ko.properties")) {
        return testConfigurationKo(file,port+testPort++);
    }
    return fileName +
        ": test file suffix must be one of [ko|ok].properties";
}
 
Example 38
Project: wildfly-swarm   File: DaemonService.java   View source code 6 votes vote down vote up
@Override
public void start(StartContext context) throws StartException {
    int port = Integer.getInteger(SwarmProperties.ARQUILLIAN_DAEMON_PORT, 12345);

    try {
        this.server = Server.create("localhost", port);
        this.server.start();
    } catch (Exception e) {
        // this shouldn't be possible per Java control flow rules, but there is a "sneaky throw" somewhere
        //noinspection ConstantConditions
        if (e instanceof BindException) {
            log.log(Level.SEVERE, "Couldn't bind Arquillian Daemon on localhost:" + port
                    + "; you can change the port using system property '"
                    + SwarmProperties.ARQUILLIAN_DAEMON_PORT + "'", e);
        }

        throw new StartException(e);
    }
}
 
Example 39
Project: rdf-delta   File: LogRun.java   View source code 6 votes vote down vote up
private static PatchLogServer server(int port, String base) {
    // --- Reset state.
    FileOps.ensureDir(base);
    FileOps.clearAll("DeltaServer/ABC");
    FileOps.delete("DeltaServer/ABC");
    FileOps.clearAll(base);
    PatchLogServer dps = PatchLogServer.server(port, base);
    try { 
        dps.start();
        return dps; 
    } catch(BindException ex) {
        Delta.DELTA_LOG.error("Address in use: port="+port);
        System.exit(0);
        return null;
    }
}
 
Example 40
Project: Mindustry   File: KryoServer.java   View source code 5 votes vote down vote up
@Override
public void onError(WebSocket conn, Exception ex) {
    UCore.log("WS error:");
    ex.printStackTrace();
    if(ex instanceof BindException){
        Net.closeServer();
        Vars.ui.showError("$text.server.addressinuse");
    }
}