java.net.BindException Java Examples
The following examples show how to use
java.net.BindException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RmiBootstrapTest.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** * 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 #2
Source File: SiphonServer.java From sdl_java_suite with BSD 3-Clause "New" or "Revised" License | 6 votes |
private boolean findOpenSocket(short port) { // Accept incoming sihpon connection from trace utility. Boolean foundOpenPort = false; listenPort = port; // Listen to accept incoming connection from SDL while (!foundOpenPort) { try { m_listeningSocket = new ServerSocket(listenPort); foundOpenPort = true; m_listenPort = listenPort; } catch (BindException ex) { listenPort++; if(listenPort > port + MAX_NUMBER_OF_PORT_ATTEMPTS) { return false; } } catch (IOException e) { return false; } } return foundOpenPort; }
Example #3
Source File: UpdateStatementConstraintCheckTest.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** 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 #4
Source File: RmiBootstrapTest.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * 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 #5
Source File: PortHelper.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: Setup.java From rdf-delta with Apache License 2.0 | 6 votes |
@Override public void restart() { server.stop(); //testPort = LibX.choosePort(); LocalServerConfig config = localServer.getConfig() ; LocalServer.release(localServer); localServer = LocalServer.create(config); resetDefaultHttpClient(); DeltaLink localLink = DeltaLinkLocal.connect(localServer); server = DeltaServer.create(testPort, localLink); try { server.start(); } catch (BindException e) { e.printStackTrace(); } relink(); }
Example #7
Source File: UDPConnector.java From gama with GNU General Public License v3.0 | 6 votes |
public void openServerSocket(final IAgent agent) { final Integer port = Cast.asInt(agent.getScope(), this.getConfigurationParameter(SERVER_PORT)); if (agent.getScope().getSimulation().getAttribute(_UDP_SERVER + port) == null) { try { final DatagramSocket sersock = new DatagramSocket(port); final MultiThreadedUDPSocketServer ssThread = new MultiThreadedUDPSocketServer(agent, sersock, this.getConfigurationParameter(PACKET_SIZE)); ssThread.start(); agent.getScope().getSimulation().setAttribute(_UDP_SERVER + port, ssThread); } catch (final BindException be) { throw GamaRuntimeException.create(be, agent.getScope()); } catch (final Exception e) { throw GamaRuntimeException.create(e, agent.getScope()); } } }
Example #8
Source File: NetworkBridge.java From j2objc with Apache License 2.0 | 6 votes |
public static void bind(FileDescriptor fd, InetAddress address, int port) throws SocketException { if (address instanceof Inet6Address) { Inet6Address inet6Address = (Inet6Address) address; if (inet6Address.getScopeId() == 0 && inet6Address.isLinkLocalAddress()) { // Linux won't let you bind a link-local address without a scope id. // Find one. NetworkInterface nif = NetworkInterface.getByInetAddress(address); if (nif == null) { throw new SocketException("Can't bind to a link-local address without a scope id: " + address); } try { address = Inet6Address.getByAddress(address.getHostName(), address.getAddress(), nif.getIndex()); } catch (UnknownHostException ex) { throw new AssertionError(ex); // Can't happen. } } } try { NetworkOs.bind(fd, address, port); } catch (ErrnoException errnoException) { throw new BindException(errnoException.getMessage(), errnoException); } }
Example #9
Source File: SiphonServer.java From sdl_java_suite with BSD 3-Clause "New" or "Revised" License | 6 votes |
private boolean findOpenSocket(short port) { // Accept incoming sihpon connection from trace utility. Boolean foundOpenPort = false; listenPort = port; // Listen to accept incoming connection from SDL while (!foundOpenPort) { try { m_listeningSocket = new ServerSocket(listenPort); foundOpenPort = true; m_listenPort = listenPort; } catch (BindException ex) { listenPort++; if(listenPort > port + MAX_NUMBER_OF_PORT_ATTEMPTS) { return false; } } catch (IOException e) { return false; } } return foundOpenPort; }
Example #10
Source File: SinkChannelTest.java From j2objc with Apache License 2.0 | 6 votes |
public void test_socketChannel_read_write() throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); try { ssc.socket() .bind(new InetSocketAddress(InetAddress.getLocalHost(), 0 /* any free port */)); } catch (BindException e) { // Continuous build environment doesn't support localhost sockets. return; } int localPort = ssc.socket().getLocalPort(); SocketChannel sc = SocketChannel.open(); sc.connect(new InetSocketAddress(InetAddress.getLocalHost(), localPort)); SocketChannel sock = ssc.accept(); ByteBuffer[] buf = {ByteBuffer.allocate(10),null}; try { sc.write(buf,0,2); fail("should throw NPE"); } catch (NullPointerException expected) { } ssc.close(); sc.close(); ByteBuffer target = ByteBuffer.allocate(10); assertEquals(-1, sock.read(target)); }
Example #11
Source File: LocalSocketServer.java From weex with Apache License 2.0 | 6 votes |
@Nonnull private static LocalServerSocket bindToSocket(String address) throws IOException { int retries = MAX_BIND_RETRIES; IOException firstException = null; do { try { if (LogUtil.isLoggable(Log.DEBUG)) { LogUtil.d("Trying to bind to @" + address); } return new LocalServerSocket(address); } catch (BindException be) { LogUtil.w(be, "Binding error, sleep " + TIME_BETWEEN_BIND_RETRIES_MS + " ms..."); if (firstException == null) { firstException = be; } Util.sleepUninterruptibly(TIME_BETWEEN_BIND_RETRIES_MS); } } while (retries-- > 0); throw firstException; }
Example #12
Source File: NettyThreadManager.java From fastjgame with Apache License 2.0 | 6 votes |
/** * 在某个端口范围内选择一个端口监听. * * @param host 地址 * @param portRange 端口范围 * @param sndBuffer socket发送缓冲区 * @param rcvBuffer socket接收缓冲区 * @param initializer channel初始化类 * @return 监听成功的端口号,失败返回null */ public DefaultSocketPort bindRange(String host, PortRange portRange, int sndBuffer, int rcvBuffer, ChannelInitializer<SocketChannel> initializer) throws BindException { if (portRange.startPort <= 0) { throw new IllegalArgumentException("fromPort " + portRange.startPort); } if (portRange.startPort > portRange.endPort) { throw new IllegalArgumentException("fromPort " + portRange.startPort + " toPort " + portRange.endPort); } for (int port = portRange.startPort; port <= portRange.endPort; port++) { try { return bind(host, port, sndBuffer, rcvBuffer, initializer); } catch (BindException e) { // ignore } } throw new BindException("can't bind port from " + portRange.startPort + " to " + portRange.endPort); }
Example #13
Source File: MasterRpcServices.java From hbase with Apache License 2.0 | 6 votes |
@Override protected RpcServerInterface createRpcServer(final Server server, final RpcSchedulerFactory rpcSchedulerFactory, final InetSocketAddress bindAddress, final String name) throws IOException { final Configuration conf = regionServer.getConfiguration(); // RpcServer at HM by default enable ByteBufferPool iff HM having user table region in it boolean reservoirEnabled = conf.getBoolean(ByteBuffAllocator.ALLOCATOR_POOL_ENABLED_KEY, LoadBalancer.isMasterCanHostUserRegions(conf)); try { return RpcServerFactory.createRpcServer(server, name, getServices(), bindAddress, // use final bindAddress for this server. conf, rpcSchedulerFactory.create(conf, this, server), reservoirEnabled); } catch (BindException be) { throw new IOException(be.getMessage() + ". To switch ports use the '" + HConstants.MASTER_PORT + "' configuration property.", be.getCause() != null ? be.getCause() : be); } }
Example #14
Source File: HttpServerImpl.java From reef with Apache License 2.0 | 6 votes |
private Server tryPort(final int portNumber) throws Exception { Server srv = new Server(); final Connector connector = new SocketConnector(); connector.setHost(this.hostAddress); connector.setPort(portNumber); srv.addConnector(connector); try { srv.start(); LOG.log(Level.INFO, "Jetty Server started with port: {0}", portNumber); } catch (final BindException ex) { srv = null; LOG.log(Level.FINEST, "Cannot use host: {0},port: {1}. Will try another", new Object[] {this.hostAddress, portNumber}); } return srv; }
Example #15
Source File: LongClientSession.java From Tatala-RPC with Apache License 2.0 | 5 votes |
public Object start(TransferObject to) { Object resultObject = null; String calleeClass = to.getCalleeClass(); String calleeMethod = to.getCalleeMethod(); //set default server call proxy if(to.getServerCallProxy() != null){ serverCallProxy = to.getServerCallProxy(); } try { if(socketChannel == null || !socketChannel.isOpen() || closed){ connect(); } send(to); resultObject = receive(to); if(resultObject instanceof TatalaReturnException){ throw (TatalaReturnException)resultObject; } } catch (TatalaReturnException tre) { log.error("Tatala Return Exception: Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]"); throw tre; } catch (BindException be) { log.error("Connection error: " + be.getMessage()); log.error("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]"); close(); } catch (TimeoutException te) { log.error("Socekt timed out, return null. [" + timeout + "ms]"); log.error("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]"); close(); } catch (Exception e) { log.error("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]"); e.printStackTrace(); close(); } return resultObject; }
Example #16
Source File: Server.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
public static String start() throws Exception { int serverPort = 12345; ObjectName name = new ObjectName("test", "foo", "bar"); MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer(); SteMBean bean = new Ste(); jmxServer.registerMBean(bean, name); boolean exported = false; Random rnd = new Random(System.currentTimeMillis()); do { try { LocateRegistry.createRegistry(serverPort); exported = true; } catch (ExportException ee) { if (ee.getCause() instanceof BindException) { serverPort = rnd.nextInt(10000) + 4096; } else { throw ee; } } } while (!exported); JMXServiceURL serverUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + serverPort + "/test"); JMXConnectorServer jmxConnector = JMXConnectorServerFactory.newJMXConnectorServer(serverUrl, null, jmxServer); jmxConnector.start(); return serverUrl.toString(); }
Example #17
Source File: BadKdc.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
public static void go(String... expected) throws Exception { try { go0(expected); } catch (BindException be) { System.out.println("The random port is used by another process"); } catch (LoginException le) { Throwable cause = le.getCause(); if (cause instanceof Asn1Exception) { System.out.println("Bad packet possibly from another process"); return; } throw le; } }
Example #18
Source File: RMIHydraSocketFactory.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
public Socket createSocket(String host, int port) throws IOException { int retryCount = INITIAL_RETRY_COUNT; do { retryCount--; try { return new Socket(host, port); } catch (SocketException se) { //IBM J9 sometimes reports "listen failed" instead of BindException //see bug #40589 final String msg = se.getMessage(); boolean reattempt = se instanceof BindException || se instanceof ConnectException || (msg != null && msg.contains("Invalid argument: listen failed")); if (!reattempt || retryCount <= 0) { throw se; } else { try {Thread.sleep(THROTTLE_PERIOD);} catch (InterruptedException ie) { retryCount = 0; Thread.currentThread().interrupt(); } } } } while (true); }
Example #19
Source File: Gossip.java From gossip with MIT License | 5 votes |
private void start() throws BindException { if (server == null) { server = new GossipServer(configPath, configFile); server.setPort(port); server.setRootResourcePath(rootResourcePath); server.start(); shutdownHook(); } else { throw new GossipInitializeException("The gossip server is already started, check the author's shit logic code"); } }
Example #20
Source File: Main.java From ict with Apache License 2.0 | 5 votes |
public static void main(String[] args) { Main.args = args; Constants.RUN_MODUS = Constants.RunModus.MAIN; Properties ictProperties = processCmdLineArgs(args); logger.info("Starting new Ict '" + ictProperties.name() + "' (version: " + Constants.ICT_VERSION + ")"); IctInterface ict; try { ict = new Ict(ictProperties.toFinal()); } catch (Throwable t) { if (t.getCause() instanceof BindException) { logger.error("Could not start Ict on " + ictProperties.host() + ":" + ictProperties.port(), t); logger.info("Make sure that the address is correct and you are not already running an Ict instance or any other service on that port. You can change the port in your properties file."); } else logger.error("Could not start Ict.", t); return; } ict.getModuleHolder().initAllModules(); ict.getModuleHolder().startAllModules(); final IctInterface finalRefToIct = ict; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { finalRefToIct.terminate(); } }); }
Example #21
Source File: GridNioSelfTest.java From ignite with Apache License 2.0 | 5 votes |
/** * Starts server with specified arguments. * * @param parser Parser to use. * @param lsnr Listener. * @param queueLimit Optional send queue limit. * @return Started server. * @throws Exception If failed. */ protected final GridNioServer<?> startServer(GridNioParser parser, GridNioServerListener lsnr, @Nullable Integer queueLimit) throws Exception { for (int i = 0; i < 10; i++) { int srvPort = port++; try { GridNioServer.Builder<?> builder = serverBuilder(srvPort, parser, lsnr); if (queueLimit != null) builder.sendQueueLimit(queueLimit); GridNioServer<?> srvr = builder.build(); srvr.start(); return srvr; } catch (IgniteCheckedException e) { if (i < 9 && e.hasCause(BindException.class)) { log.error("Failed to start server, will try another port [err=" + e + ", port=" + srvPort + ']'); U.sleep(5000); } else throw e; } } fail("Failed to start server."); return null; }
Example #22
Source File: EmbeddedKafkaServer.java From twill with Apache License 2.0 | 5 votes |
@Override protected void startUp() throws Exception { int tries = 0; do { KafkaConfig kafkaConfig = createKafkaConfig(properties); KafkaServer kafkaServer = createKafkaServer(kafkaConfig); try { kafkaServer.startup(); server = kafkaServer; } catch (Exception e) { kafkaServer.shutdown(); kafkaServer.awaitShutdown(); Throwable rootCause = Throwables.getRootCause(e); if (rootCause instanceof ZkTimeoutException) { // Potentially caused by race condition bug described in TWILL-139. LOG.warn("Timeout when connecting to ZooKeeper from KafkaServer. Attempt number {}.", tries, rootCause); } else if (rootCause instanceof BindException) { LOG.warn("Kafka failed to bind to port {}. Attempt number {}.", kafkaConfig.port(), tries, rootCause); } else { throw e; } // Do a random sleep of < 200ms TimeUnit.MILLISECONDS.sleep(new Random().nextInt(200) + 1L); } } while (server == null && ++tries < startTimeoutRetries); if (server == null) { throw new IllegalStateException("Failed to start Kafka server after " + tries + " attempts."); } }
Example #23
Source File: LdapServer.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
private synchronized int configureAndStartServer(String... ldifFiles) throws Exception { Collection<InMemoryListenerConfig> listenerConfigs = getInMemoryListenerConfigs(); Schema schema = Schema.getDefaultStandardSchema(); final String rootObjectDN = "o=TEST"; InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(new DN(rootObjectDN)); config.setSchema(schema); //schema can be set on the rootDN too, per javadoc. config.setListenerConfigs(listenerConfigs); config.setEnforceAttributeSyntaxCompliance(false); config.setEnforceSingleStructuralObjectClass(false); //config.setLDAPDebugLogHandler(DEBUG_HANDLER); //config.setAccessLogHandler(DEBUG_HANDLER); //config.addAdditionalBindCredentials(configuration.getBindDn(), configuration.getPassword()); server = new InMemoryDirectoryServer(config); try { /* Clear entries from server. */ server.clear(); server.startListening(); return loadLdifFiles(ldifFiles); } catch (LDAPException ldape) { if (ldape.getMessage().contains("java.net.BindException")) { throw new BindException(ldape.getMessage()); } throw ldape; } }
Example #24
Source File: TestRedisServer.java From redis-mock with MIT License | 5 votes |
@Test public void testBindUsedPort() throws IOException, InterruptedException { RedisServer server1 = RedisServer.newRedisServer(); server1.start(); RedisServer server2 = RedisServer.newRedisServer(server1.getBindPort()); try { server2.start(); assertTrue(false); } catch (BindException e) { // OK } }
Example #25
Source File: RmiBootstrapTest.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Find all *ok.property files and test them. * (see findConfigurationFilesOk() and testConfiguration()) * @throws RuntimeException if the test fails. **/ public void runok() { final String portStr = System.getProperty("rmi.port",null); final int port = portStr != null ? Integer.parseInt(portStr) : basePort; final File[] conf = findConfigurationFilesOk(); if ((conf == null)||(conf.length == 0)) throw new RuntimeException("No configuration found"); String errStr = null; for (int i=0;i<conf.length;i++) { for (int j = 0; j < PORT_TEST_LEN; i++) { try { errStr = testConfiguration(conf[i],port+testPort++); break; } catch (BindException e) { // port conflict; try another port } } if (errStr != null) { throw new RuntimeException(errStr); } } // FIXME: No jmxremote.password is not installed in JRE by default. // - disable the following test case. // // Test default config // // errStr = testConfiguration(null,port+testPort++); // if (errStr != null) { // throw new RuntimeException(errStr); // } }
Example #26
Source File: TestNetUtils.java From big-c with Apache License 2.0 | 5 votes |
@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 #27
Source File: DefaultAgentFilterTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public synchronized void start() throws Exception { if (started.compareAndSet(false, true)) { try { AtomicBoolean error = new AtomicBoolean(false); AtomicBoolean bindError = new AtomicBoolean(false); p = ProcessTools.startProcess( TEST_APP_NAME + "{" + name + "}", pb, (line) -> { if (line.toLowerCase().contains("exception") || line.toLowerCase().contains("error")) { error.set(true); } bindError.set(line.toLowerCase().contains("bindexception")); return true; }, 10, TimeUnit.SECONDS); if (bindError.get()) { throw new BindException("Process could not be started"); } else if (error.get()) { throw new RuntimeException(); } } catch (Exception ex) { if (p != null) { p.destroy(); p.waitFor(); } throw ex; } } }
Example #28
Source File: BindFailTest.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String args[]) throws Exception { DatagramSocket s = new DatagramSocket(); int port = s.getLocalPort(); for (int i=0; i<32000; i++) { try { DatagramSocket s2 = new DatagramSocket(port); } catch (BindException e) { } } }
Example #29
Source File: ServerTCPListener.java From phoebus with Eclipse Public License 1.0 | 5 votes |
/** @return Socket bound to EPICS_PVA_SERVER_PORT or unused port */ private static ServerSocketChannel createSocket() throws Exception { ServerSocketChannel socket = ServerSocketChannel.open(); socket.configureBlocking(true); socket.socket().setReuseAddress(true); try { socket.bind(new InetSocketAddress(PVASettings.EPICS_PVA_SERVER_PORT)); return socket; } catch (BindException ex) { logger.log(Level.INFO, "TCP port " + PVASettings.EPICS_PVA_SERVER_PORT + " already in use, switching to automatically assigned port"); final InetSocketAddress any = new InetSocketAddress(0); try { // Must create new socket after bind() failed, cannot re-use socket = ServerSocketChannel.open(); socket.configureBlocking(true); socket.socket().setReuseAddress(true); socket.bind(any); return socket; } catch (Exception e) { throw new Exception("Cannot bind to automatically assigned port " + any, e); } } }
Example #30
Source File: Util.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
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")); }