Java 类java.net.BindException 实例源码

项目:hadoop-oss    文件:TestServer.java   
@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();
  }
}
项目:owa-notifier    文件:InternalWebServer.java   
/**
    * 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();
}
项目:JInsight    文件:TestWebServer.java   
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();
  }
项目:monarch    文件:SocketCreator.java   
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;
  }
}
项目:hadoop    文件:TestValidateConfigurationSettings.java   
/**
 * 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();
    }
  }
}
项目:hadoop    文件:TestServer.java   
@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();
  }
}
项目:jdk8u-jdk    文件:RmiBootstrapTest.java   
/**
 * 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;
}
项目:jdk8u-jdk    文件:RmiBootstrapTest.java   
/**
 * 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";
}
项目:openjdk-jdk10    文件:JMXStatusTest.java   
@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 ...");
        }
    }
}
项目:openjdk-jdk10    文件:JMXStatusPerfCountersTest.java   
/**
 * 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 ...");
        }
    }
}
项目:openjdk-jdk10    文件:JMXStatusPerfCountersTest.java   
/**
 * 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 ...");
        }
    }
}
项目:dremio-oss    文件:BasicServer.java   
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;
}
项目:yaacc-code    文件:YaaccUpnpServerService.java   
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);

}
项目:ditb    文件:TestIPv6NIOServerSocketChannel.java   
/**
 * 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();
      }
    }  
  }
}
项目:ditb    文件:TestIPv6NIOServerSocketChannel.java   
/**
 * 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();
  }
}
项目:silvertunnel-ng    文件:HiddenServiceInstance.java   
/**
 * 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);
}
项目:openjdk9    文件:Security.java   
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();
}
项目:openjdk9    文件:JMXStatusTest.java   
@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 ...");
        }
    }
}
项目:vespa    文件:Application.java   
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;
}
项目:openjdk9    文件:JMXStatusPerfCountersTest.java   
/**
 * 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 ...");
        }
    }
}
项目:openjdk9    文件:JMXStatusPerfCountersTest.java   
/**
 * 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 ...");
        }
    }
}
项目:ThriftyPaxos    文件:NetUtils.java   
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);
    }
}
项目:aliyun-oss-hadoop-fs    文件:TestValidateConfigurationSettings.java   
/**
 * 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();
    }
  }
}
项目:LunaticSMTP    文件:EmailServer.java   
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());
        }
    }
}
项目:StreamProcessingInfrastructure    文件:Leader.java   
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;
}
项目:SecureKeeper    文件:Leader.java   
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;
}
项目:leopard    文件:AbstractWebServer.java   
/**
 * 智能选择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;
}
项目:rxjava2-extras    文件:FlowableServerSocketTest.java   
@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();
    }
}
项目:gemfirexd-oss    文件:UpdateStatementConstraintCheckTest.java   
/** 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;
    }
  }
}
项目:gemfirexd-oss    文件:PortHelper.java   
/**
 * 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;
}
项目:big-c    文件:TestValidateConfigurationSettings.java   
/**
 * 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();
    }
  }
}
项目:big-c    文件:TestServer.java   
@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();
  }
}
项目:zookeeper    文件:Leader.java   
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;
}
项目:jdk8u_jdk    文件:RmiBootstrapTest.java   
/**
 * 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;
}
项目:jdk8u_jdk    文件:RmiBootstrapTest.java   
/**
 * 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";
}
项目:lookaside_java-1.8.0-openjdk    文件:RmiBootstrapTest.java   
/**
 * 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;
}
项目:lookaside_java-1.8.0-openjdk    文件:RmiBootstrapTest.java   
/**
 * 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";
}
项目:wildfly-swarm    文件:DaemonService.java   
@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);
    }
}
项目:rdf-delta    文件:LogRun.java   
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;
    }
}
项目:Mindustry    文件:KryoServer.java   
@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");
    }
}