Example usage for java.net BindException BindException

List of usage examples for java.net BindException BindException

Introduction

In this page you can find the example usage for java.net BindException BindException.

Prototype

public BindException(String msg) 

Source Link

Document

Constructs a new BindException with the specified detail message as to why the bind error occurred.

Usage

From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java

private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception {
    if (tries >= 5) {
        throw new BindException(
                "Unable to bind to several ports, most recently " + relay.getPort() + ". Giving up");
    }/*  w  w w . j a  v a 2  s.  c  om*/
    try {
        if (server.isStarted()) {
            relay.start();
        } else {
            throw new RuntimeException(
                    "Can't start SslRelay: server is not started (perhaps it was just shut down?)");
        }
    } catch (BindException e) {
        // doh - the port is being used up, let's pick a new port
        LOG.info("Unable to bind to port %d, going to try port %d now", relay.getPort(), relay.getPort() + 1);
        relay.setPort(relay.getPort() + 1);
        startRelayWithPortTollerance(server, relay, tries + 1);
    }
}

From source file:voldemort.ServerTestUtils.java

/**
 * Starts a Voldemort server for testing purposes.
 * //  w w w .java 2s .  c  o m
 * Unless the ports passed in via cluster are guaranteed to be available,
 * this method is susceptible to BindExceptions in VoldemortServer.start().
 * (And, there is no good way of guaranteeing that ports will be available,
 * so...)
 * 
 * The method {@link ServerTestUtils#startVoldemortCluster} should be used
 * in preference to this method.}
 * 
 * @param socketStoreFactory
 * @param config
 * @param cluster
 * @return
 */
public static VoldemortServer startVoldemortServer(SocketStoreFactory socketStoreFactory,
        VoldemortConfig config, Cluster cluster) throws BindException {

    // TODO: Some tests that use this method fail intermittently with the
    // following output:
    //
    // A successor version version() to this version() exists for key
    // cluster.xml
    // voldemort.versioning.ObsoleteVersionException: A successor version
    // version() to this version() exists for key cluster.xml"
    //
    // Need to trace through the constructor VoldemortServer(VoldemortConfig
    // config, Cluster cluster) to understand how this error is possible,
    // and why it only happens intermittently.
    VoldemortServer server = new VoldemortServer(config, cluster);
    try {
        server.start();
    } catch (VoldemortException ve) {
        if (ve.getCause() instanceof BindException) {
            ve.printStackTrace();
            throw new BindException(ve.getMessage());
        } else {
            throw ve;
        }
    }

    ServerTestUtils.waitForServerStart(socketStoreFactory, server.getIdentityNode());
    // wait till server starts or throw exception
    return server;
}

From source file:org.apache.flink.runtime.clusterframework.BootstrapTools.java

/**
 * Starts an ActorSystem with the given configuration listening at the address/ports.
 * @param configuration The Flink configuration
 * @param listeningAddress The address to listen at.
 * @param portRangeDefinition The port range to choose a port from.
 * @param logger The logger to output log information.
 * @return The ActorSystem which has been started
 * @throws Exception/*from   ww w .j a  v a  2 s.c om*/
 */
public static ActorSystem startActorSystem(Configuration configuration, String listeningAddress,
        String portRangeDefinition, Logger logger) throws Exception {

    // parse port range definition and create port iterator
    Iterator<Integer> portsIterator;
    try {
        portsIterator = NetUtils.getPortRangeFromString(portRangeDefinition);
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid port range definition: " + portRangeDefinition);
    }

    while (portsIterator.hasNext()) {
        // first, we check if the port is available by opening a socket
        // if the actor system fails to start on the port, we try further
        ServerSocket availableSocket = NetUtils.createSocketFromPorts(portsIterator,
                new NetUtils.SocketFactory() {
                    @Override
                    public ServerSocket createSocket(int port) throws IOException {
                        return new ServerSocket(port);
                    }
                });

        int port;
        if (availableSocket == null) {
            throw new BindException("Unable to allocate further port in port range: " + portRangeDefinition);
        } else {
            port = availableSocket.getLocalPort();
            try {
                availableSocket.close();
            } catch (IOException ignored) {
            }
        }

        try {
            return startActorSystem(configuration, listeningAddress, port, logger);
        } catch (Exception e) {
            // we can continue to try if this contains a netty channel exception
            Throwable cause = e.getCause();
            if (!(cause instanceof org.jboss.netty.channel.ChannelException
                    || cause instanceof java.net.BindException)) {
                throw e;
            } // else fall through the loop and try the next port
        }
    }

    // if we come here, we have exhausted the port range
    throw new BindException("Could not start actor system on any port in port range " + portRangeDefinition);
}

From source file:org.apache.geode.distributed.AbstractLauncher.java

/**
 * Asserts that the specified port is available on the specified network interface, indicated by
 * it's assigned IP address, on this local system.
 *
 * @param bindAddress an InetAddress indicating the bounded network interface to determine whether
 *        the service port is available or not.
 * @param port an integer indicating the network port to listen for client network requests.
 * @throws BindException if the network address and port are not available. Address defaults to
 *         localhost (or all network interfaces on the local system) if null.
 * @see org.apache.geode.internal.AvailablePort
 *//*from  w  w w  .jav a2 s.c  om*/
protected static void assertPortAvailable(final InetAddress bindAddress, final int port) throws BindException {
    if (!AvailablePort.isPortAvailable(port, AvailablePort.SOCKET, bindAddress)) {
        throw new BindException(String.format("Network is unreachable; port (%1$d) is not available on %2$s.",
                port, bindAddress != null ? bindAddress.getCanonicalHostName() : "localhost"));
    }
}

From source file:org.apache.geode.internal.net.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 {//  w  w w. j a  va2  s .c om
        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;
    }
}

From source file:org.apache.geode.internal.net.SocketCreator.java

private ServerSocket createServerSocket(int nport, int backlog, InetAddress bindAddr, int socketBufferSize,
        boolean sslConnection) throws IOException {
    printConfig();//from  w ww . j  a  v a  2 s .  co  m
    if (sslConnection) {
        if (this.sslContext == null) {
            throw new GemFireConfigException("SSL not configured correctly, Please look at previous error");
        }
        ServerSocketFactory ssf = this.sslContext.getServerSocketFactory();
        SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket();
        serverSocket.setReuseAddress(true);
        // If necessary, 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)
        if (socketBufferSize != -1) {
            serverSocket.setReceiveBufferSize(socketBufferSize);
        }
        serverSocket.bind(new InetSocketAddress(bindAddr, nport), backlog);
        finishServerSocket(serverSocket);
        return serverSocket;
    } else {
        // log.info("Opening server socket on " + nport, new Exception("SocketCreation"));
        ServerSocket result = new ServerSocket();
        result.setReuseAddress(true);
        // If necessary, 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)
        if (socketBufferSize != -1) {
            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;
    }
}

From source file:org.apache.hadoop.hbase.http.HttpServer.java

/**
 * Open the main listener for the server
 * @throws Exception//from www . j a v  a  2s. c  om
 */
void openListeners() throws Exception {
    for (ListenerInfo li : listeners) {
        Connector listener = li.listener;
        if (!li.isManaged || li.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);
        }
    }
}

From source file:org.apache.hadoop.http.HttpServer2.java

/**
 * Open the main listener for the server
 * @throws Exception/*from  w  w  w.j a va 2 s  . c  o  m*/
 */
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);
        }
    }
}

From source file:org.apache.juddi.v3.client.mapping.UDDIServiceCache.java

public void publishAndRegisterHttpCallbackEndpoint() throws BindException {
    if (clerk != null && listenerEndpoint == null) {
        try {/*from   www  . j  a va  2 s .  c  o  m*/
            listenerServiceUrl = new URL(urlLocalizer.rewrite(new URL(DEFAULT_SUBSCRIPTION_LISTENER_URL)));
            WSDL2UDDI wsdl2UDDI = new WSDL2UDDI(clerk, urlLocalizer, properties);
            Definition wsdlDefinition = new ReadWSDL()
                    .readWSDL("org/apache/juddi/v3/client/mapping/UDDIClientSubscriptionListener.wsdl");

            String bindingKey = wsdl2UDDI
                    .registerBusinessService(SUBSCRIPTION_LISTENER_SERVICE_NAME,
                            SUBSCRIPTION_LISTENER_PORT_NAME, listenerServiceUrl, wsdlDefinition)
                    .getBindingKey();
            UDDISubscriptionListenerPortType subscriptionListener = new UDDIClientSubscriptionListenerImpl(
                    bindingKey, this);
            log.info("Bringing up a UDDIClientSubscriptionListenerImpl on Endpoint "
                    + listenerServiceUrl.toExternalForm());
            listenerEndpoint = Endpoint.create(subscriptionListener);
            listenerEndpoint.publish(listenerServiceUrl.toExternalForm());

            log.info("Registering a CallbackSubscription to this endpoint using bindingKey " + bindingKey);
            registerSubscription(bindingKey);

        } catch (RuntimeException t) {
            listenerEndpoint = null;
            if (t.getCause() instanceof BindException) {
                throw new BindException(t.getCause().getMessage());
            } else {
                throw t;
            }
        } catch (Exception e) {
            log.error("Cannot publish or register the CallbackEndpoint " + e.getMessage(), e);
        }
    }
}

From source file:org.apache.tajo.webapp.HttpServer.java

/**
 * Start the server. Does not wait for the server to start.
 *//*from  w ww . j a v a  2  s  .  c om*/
public void start() throws IOException {
    try {
        if (listenerStartedExternally) { // Expect that listener was started
                                         // securely
            if (listener.getLocalPort() == -1) // ... and verify
                throw new Exception("Exepected webserver's listener to be started " + "previously but wasn't");
            // And skip all the port rolling issues.
            webServer.start();
        } else {
            int port;
            int oriPort = listener.getPort(); // The original requested port
            while (true) {
                try {
                    port = webServer.getConnectors()[0].getLocalPort();
                    LOG.debug("Port returned by webServer.getConnectors()[0]."
                            + "getLocalPort() before open() is " + port + ". Opening the listener on "
                            + oriPort);
                    listener.open();
                    port = listener.getLocalPort();
                    LOG.debug("listener.getLocalPort() returned " + listener.getLocalPort()
                            + " webServer.getConnectors()[0].getLocalPort() returned "
                            + webServer.getConnectors()[0].getLocalPort());
                    // Workaround to handle the problem reported in HADOOP-4744
                    if (port < 0) {
                        Thread.sleep(100);
                        int numRetries = 1;
                        while (port < 0) {
                            LOG.warn("listener.getLocalPort returned " + port);
                            if (numRetries++ > MAX_RETRIES) {
                                throw new Exception(" listener.getLocalPort is returning "
                                        + "less than 0 even after " + numRetries + " resets");
                            }
                            for (int i = 0; i < 2; i++) {
                                LOG.info("Retrying listener.getLocalPort()");
                                port = listener.getLocalPort();
                                if (port > 0) {
                                    break;
                                }
                                Thread.sleep(200);
                            }
                            if (port > 0) {
                                break;
                            }
                            LOG.info("Bouncing the listener");
                            listener.close();
                            Thread.sleep(1000);
                            listener.setPort(oriPort == 0 ? 0 : (oriPort += 1));
                            listener.open();
                            Thread.sleep(100);
                            port = listener.getLocalPort();
                        }
                    } // Workaround end
                    LOG.info("Jetty bound to port " + port);
                    webServer.start();
                    break;
                } catch (IOException ex) {
                    // if this is a bind exception,
                    // then try the next port number.
                    if (ex instanceof BindException) {
                        if (!findPort) {
                            BindException be = new BindException(
                                    "Port in use: " + listener.getHost() + ":" + listener.getPort());
                            be.initCause(ex);
                            throw be;
                        }
                    } else {
                        LOG.info("HttpServer.start() threw a non Bind IOException");
                        throw ex;
                    }
                } catch (MultiException ex) {
                    LOG.info("HttpServer.start() threw a MultiException");
                    throw ex;
                }
                listener.setPort((oriPort += 1));
            }
        }
        // Make sure there is no handler failures.
        Handler[] handlers = webServer.getHandlers();
        for (Handler handler : handlers) {
            if (handler.isFailed()) {
                throw new IOException("Problem in starting http server. Server handlers failed");
            }
        }
    } catch (IOException e) {
        throw e;
    } catch (InterruptedException e) {
        throw (IOException) new InterruptedIOException("Interrupted while starting HTTP server").initCause(e);
    } catch (Exception e) {
        throw new IOException("Problem starting http server", e);
    }
}