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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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");
    }
}
 
Example 41
Project: hadoop-oss   File: HttpServer2.java   Source Code and License 5 votes vote down vote up
/**
 * Open the main listener for the server
 * @throws Exception
 */
void openListeners() throws Exception {
  for (Connector listener : listeners) {
    if (listener.getLocalPort() != -1) {
      // This listener is either started externally or has been bound
      continue;
    }
    int port = listener.getPort();
    while (true) {
      // jetty has a bug where you can't reopen a listener that previously
      // failed to open w/o issuing a close first, even if the port is changed
      try {
        listener.close();
        listener.open();
        LOG.info("Jetty bound to port " + listener.getLocalPort());
        break;
      } catch (BindException ex) {
        if (port == 0 || !findPort) {
          BindException be = new BindException("Port in use: "
              + listener.getHost() + ":" + listener.getPort());
          be.initCause(ex);
          throw be;
        }
      }
      // try the next port number
      listener.setPort(++port);
      Thread.sleep(100);
    }
  }
}
 
Example 42
Project: hadoop-oss   File: TestChildReaper.java   Source Code and License 5 votes vote down vote up
@Before
public void setup() throws Exception {
  while(this.server == null) {
    try {
      this.server = new TestingServer();
    } catch (BindException var2) {
      System.err.println("Getting bind exception - retrying to allocate server");
      this.server = null;
    }
  }
}
 
Example 43
Project: hadoop-oss   File: TestNetUtils.java   Source Code and License 5 votes vote down vote up
@Test
public void testWrapBindException() throws Throwable {
  IOException e = new BindException("failed");
  IOException wrapped = verifyExceptionClass(e, BindException.class);
  assertInException(wrapped, "failed");
  assertLocalDetailsIncluded(wrapped);
  assertNotInException(wrapped, DEST_PORT_NAME);
  assertInException(wrapped, "/BindException");
}
 
Example 44
Project: state-channels   File: NodeServer.java   Source Code and License 5 votes vote down vote up
@EventListener(ContextStartedEvent.class)
public void start() throws Exception {
    int port = properties.getPort();
    NettyServerBuilder builder = NettyServerBuilder.forPort(port);
    bindableServices.forEach(builder::addService);
    if (properties.isSecure()) {
        configureSsl(builder);
    }
    grpcServer = builder.build();

    try {
        grpcServer.start();
    } catch (IOException e) {
        if (e.getCause() instanceof BindException) {
            throw new BindException("Address already in use: " + port);
        }
        throw new RuntimeException(e);
    }
    
    if (properties.getHealthCheckPort() > 0) {
        log.info("Starting health check at port {}", properties.getHealthCheckPort());
        healthCheckSocket = new ServerSocket(properties.getHealthCheckPort());
        healthChecker = new Thread(this::healthCheck, "Health Checker");
        healthChecker.setDaemon(true);
        healthChecker.start();
    }

    log.info("Server started, GRPC API listening on {}", grpcServer.getPort());

    String endpointUrl = properties.getEndpointUrl();
    if (endpointUrl == null) {
        log.warn("No endpoint url provided");
    } else {
        for (Address address : ethereumConfig.getAddresses()) {
            ContractsManager contractManager = factory.getContractManager(address);
            EndpointRegistry registry = new EndpointRegistry(contractManager.endpointRegistry());
            registry.registerEndpoint(address, endpointUrl);
        }
    }
}
 
Example 45
Project: NSS   File: FSServer.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	try {
		FSServer fs = new FSServer();
	} catch (Exception e) {
		e.printStackTrace();
		if(e instanceof BindException){
			MLog.println("Udp port already in use.");
		}
		MLog.println("Start failed.");
		System.exit(0);
	}
}
 
Example 46
Project: CGL   File: ServerThread.java   Source Code and License 5 votes vote down vote up
public ServerThread(int port, ServerListener s){
	try {
		this.listener = s;
		server = new ServerSocket(port);
		this.port = port;
		this.start();
	} catch (IOException e) {
		if(e instanceof BindException){
			StatusPrinter.print("ERROR", "Server already running? [port:"+port+"]", ServerThread.class);
			if(listener!=null){listener.onBindException();}
		}else{
			e.printStackTrace();
		}
	}
}
 
Example 47
Project: Bootstrapper   File: Downloader.java   Source Code and License 5 votes vote down vote up
public void suggestHelp(Throwable t) {
	if ((t instanceof BindException)) {
		log("Recognized exception: the likely cause is a broken ipv4/6 stack. Check your TCP/IP settings.");
	} else if ((t instanceof ConnectException)) {
		log("Recognized exception: the likely cause is that the server is down or unreachable. Please try again later");
	}
}
 
Example 48
Project: lams   File: JIoEndpoint.java   Source Code and License 5 votes vote down vote up
public void init()
    throws Exception {

    if (initialized)
        return;
    
    // Initialize thread count defaults for acceptor
    if (acceptorThreadCount == 0) {
        acceptorThreadCount = 1;
    }
    if (serverSocketFactory == null) {
        serverSocketFactory = ServerSocketFactory.getDefault();
    }
    if (serverSocket == null) {
        try {
            if (address == null) {
                serverSocket = serverSocketFactory.createSocket(port, backlog);
            } else {
                serverSocket = serverSocketFactory.createSocket(port, backlog, address);
            }
        } catch (BindException be) {
            if (address == null) {
                throw new BindException(be.getMessage() + "<null>:" + port);
            } else {
                throw new BindException(be.getMessage() + " " +
                        address.toString() + ":" + port);
            }
        }
    }
    //if( serverTimeout >= 0 )
    //    serverSocket.setSoTimeout( serverTimeout );
    
    initialized = true;
    
}
 
Example 49
Project: Gather-Platform   File: CommonSpider.java   Source Code and License 5 votes vote down vote up
@Autowired
public CommonSpider(TaskManager taskManager, StaticValue staticValue) throws InterruptedException, BindException {
    this.taskManager = taskManager;
    this.staticValue = staticValue;
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            deleteAll();
            LOG.debug("定时删除全部完成的普通网页抓取任务");
        }
    }, staticValue.getTaskDeleteDelay() * 3600000, staticValue.getTaskDeletePeriod() * 3600000);
    LOG.debug("定时删除普通网页抓取任务记录线程已启动,延时:{}小时,每{}小时删除一次", staticValue.getTaskDeleteDelay(), staticValue.getTaskDeletePeriod());
}
 
Example 50
Project: siddhi-io-http   File: HttpConnectorPortBindingListener.java   Source Code and License 5 votes vote down vote up
@Override
public void onError(Throwable throwable) {
    log.error("Error in http server connector", throwable);

    if (throwable instanceof BindException) {
        connectorStartupSynchronizer.addException(serverConnectorId, (BindException) throwable);
        connectorStartupSynchronizer.getCountDownLatch().countDown();
    }
}
 
Example 51
Project: QDrill   File: BasicServer.java   Source Code and License 5 votes vote down vote up
public int bind(final int initialPort, boolean allowPortHunting) throws DrillbitStartupException {
  int port = initialPort - 1;
  while (true) {
    try {
      b.bind(++port).sync();
      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;
      }
      final UserException bindException =
          UserException
            .resourceError( e )
            .addContext( "Server type", getClass().getSimpleName() )
            .message( "Drillbit could not bind to port %s.", port )
            .build(logger);
      throw bindException;
    }
  }

  connect = !connect;
  logger.debug("Server of type {} started on port {}.", getClass().getSimpleName(), port);
  return port;
}
 
Example 52
Project: xmall   File: RestCtrlExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(BindException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public Result<Object> bindExceptionHandler(BindException e){
    String errorMsg="请求数据校验不合法: ";
    if(e!=null){
        errorMsg=e.getMessage();
        log.warn(errorMsg);
    }
    return new ResultUtil<>().setErrorMsg(errorMsg);
}
 
Example 53
Project: xmall   File: RestCtrlExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(BindException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public Result<Object> bindExceptionHandler(BindException e){
    String errorMsg="请求数据校验不合法: ";
    if(e!=null){
        errorMsg=e.getMessage();
        log.warn(errorMsg);
    }
    return new ResultUtil<>().setErrorMsg(errorMsg);
}
 
Example 54
Project: CloudDB   File: KVServer.java   Source Code and License 5 votes vote down vote up
/**
	 * Starts the KVServer, all client requests and all ECS requests are
	 * processed.
	 */

	public void start() {

		try {
			serverSocket = new ServerSocket(port);
			logger.info("Server listening on port: " + serverSocket.getLocalPort());
		} catch (IOException e) {
			logger.error("Error! Cannot open server socket:");
			if (e instanceof BindException) {
				logger.error("Port " + port + " is already bound!");
			}
		}

		replicationManager.update(this.metadata);

		synchronized (state) {
			state.setState(State.RUNNING);
			state.notifyAll();
		}

		// replicationManager.start();
		// replicationManager.start3();

		if (!failureDetector.isAlive())
			failureDetector.start();

//		try {
//			logger.info("Message Broker: start to initialize, IP: " + metadata.getBrokerIP() + ", Port: " + metadata.getBrokerPort());
//			brokerSocket = new Socket(metadata.getBrokerIP(), metadata.getBrokerPort());
//			logger.info("Message Broker: IP: " + metadata.getBrokerIP() + ", Port: " + metadata.getBrokerPort());
//			brokerMsgHandler = new MessageHandler(brokerSocket, logger);
//			logger.info("Message Broker: is started");
//		} catch (Exception e) {
//			logger.error(e.getMessage());
//		}

		logger.info("The server is started");
	}
 
Example 55
Project: monarch   File: AcceptorImpl.java   Source Code and License 5 votes vote down vote up
public static boolean treatAsBindException(SocketException se) {
  if (se instanceof BindException) {
    return true;
  }
  final String msg = se.getMessage();
  return (msg != null && msg.contains("Invalid argument: listen failed"));
}
 
Example 56
Project: monarch   File: SocketCreator.java   Source Code and License 5 votes vote down vote up
public static boolean treatAsBindException(SocketException se) {
  if (se instanceof BindException) {
    return true;
  }
  final String msg = se.getMessage();
  return (msg != null && msg.contains("Invalid argument: listen failed"));
}
 
Example 57
Project: hadoop   File: TestRefreshCallQueue.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  // We want to count additional events, so we reset here
  mockQueueConstructions = 0;
  mockQueuePuts = 0;
  int portRetries = 5;
  int nnPort;

  for (; portRetries > 0; --portRetries) {
    // Pick a random port in the range [30000,60000).
    nnPort = 30000 + rand.nextInt(30000);  
    config = new Configuration();
    callQueueConfigKey = "ipc." + nnPort + ".callqueue.impl";
    config.setClass(callQueueConfigKey,
        MockCallQueue.class, BlockingQueue.class);
    config.set("hadoop.security.authorization", "true");

    FileSystem.setDefaultUri(config, "hdfs://localhost:" + nnPort);
    fs = FileSystem.get(config);
    
    try {
      cluster = new MiniDFSCluster.Builder(config).nameNodePort(nnPort).build();
      cluster.waitActive();
      break;
    } catch (BindException be) {
      // Retry with a different port number.
    }
  }
  
  if (portRetries == 0) {
    // Bail if we get very unlucky with our choice of ports.
    fail("Failed to pick an ephemeral port for the NameNode RPC server.");
  }
}
 
Example 58
Project: hadoop   File: TestStandbyCheckpoints.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Before
public void setupCluster() throws Exception {
  Configuration conf = setupCommonConfig();

  // Dial down the retention of extra edits and checkpoints. This is to
  // help catch regressions of HDFS-4238 (SBN should not purge shared edits)
  conf.setInt(DFSConfigKeys.DFS_NAMENODE_NUM_CHECKPOINTS_RETAINED_KEY, 1);
  conf.setInt(DFSConfigKeys.DFS_NAMENODE_NUM_EXTRA_EDITS_RETAINED_KEY, 0);

  int retryCount = 0;
  while (true) {
    try {
      int basePort = 10060 + random.nextInt(100) * 2;
      MiniDFSNNTopology topology = new MiniDFSNNTopology()
          .addNameservice(new MiniDFSNNTopology.NSConf("ns1")
              .addNN(new MiniDFSNNTopology.NNConf("nn1").setHttpPort(basePort))
              .addNN(new MiniDFSNNTopology.NNConf("nn2").setHttpPort(basePort + 1)));

      cluster = new MiniDFSCluster.Builder(conf)
          .nnTopology(topology)
          .numDataNodes(1)
          .build();
      cluster.waitActive();

      nn0 = cluster.getNameNode(0);
      nn1 = cluster.getNameNode(1);
      fs = HATestUtil.configureFailoverFs(cluster, conf);

      cluster.transitionToActive(0);
      ++retryCount;
      break;
    } catch (BindException e) {
      LOG.info("Set up MiniDFSCluster failed due to port conflicts, retry "
          + retryCount + " times");
    }
  }
}
 
Example 59
Project: hadoop   File: TestEditLogAutoroll.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  conf = new Configuration();
  // Stall the standby checkpointer in two ways
  conf.setLong(DFS_NAMENODE_CHECKPOINT_PERIOD_KEY, Long.MAX_VALUE);
  conf.setLong(DFS_NAMENODE_CHECKPOINT_TXNS_KEY, 20);
  // Make it autoroll after 10 edits
  conf.setFloat(DFS_NAMENODE_EDIT_LOG_AUTOROLL_MULTIPLIER_THRESHOLD, 0.5f);
  conf.setInt(DFS_NAMENODE_EDIT_LOG_AUTOROLL_CHECK_INTERVAL_MS, 100);

  int retryCount = 0;
  while (true) {
    try {
      int basePort = 10060 + random.nextInt(100) * 2;
      MiniDFSNNTopology topology = new MiniDFSNNTopology()
          .addNameservice(new MiniDFSNNTopology.NSConf("ns1")
              .addNN(new MiniDFSNNTopology.NNConf("nn1").setHttpPort(basePort))
              .addNN(new MiniDFSNNTopology.NNConf("nn2").setHttpPort(basePort + 1)));

      cluster = new MiniDFSCluster.Builder(conf)
          .nnTopology(topology)
          .numDataNodes(0)
          .build();
      cluster.waitActive();

      nn0 = cluster.getNameNode(0);
      fs = HATestUtil.configureFailoverFs(cluster, conf);

      cluster.transitionToActive(0);

      fs = cluster.getFileSystem(0);
      editLog = nn0.getNamesystem().getEditLog();
      ++retryCount;
      break;
    } catch (BindException e) {
      LOG.info("Set up MiniDFSCluster failed due to port conflicts, retry "
          + retryCount + " times");
    }
  }
}
 
Example 60
Project: hadoop   File: TestValidateConfigurationSettings.java   Source Code and License 5 votes vote down vote up
/**
 * Tests setting the rpc port to a different as the web port that an 
 * exception is NOT thrown 
 */
@Test(timeout = 300000)
public void testThatDifferentRPCandHttpPortsAreOK() 
    throws IOException {

  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();

  // A few retries in case the ports we choose are in use.
  for (int i = 0; i < 5; ++i) {
    final int port1 = 30000 + rand.nextInt(10000);
    final int port2 = port1 + 1 + rand.nextInt(10000);

    FileSystem.setDefaultUri(conf, "hdfs://localhost:" + port1);
    conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "127.0.0.1:" + port2);
    DFSTestUtil.formatNameNode(conf);
    NameNode nameNode = null;

    try {
      nameNode = new NameNode(conf); // should be OK!
      break;
    } catch(BindException be) {
      continue;     // Port in use? Try another.
    } finally {
      if (nameNode != null) {
        nameNode.stop();
      }
    }
  }
}