Search in sources :

Example 36 with BindException

use of java.net.BindException in project spring-framework by spring-projects.

the class AnnotationExceptionHandlerMethodResolverTests method resolveMethodExceptionSubType.

@Test
public void resolveMethodExceptionSubType() {
    AnnotationExceptionHandlerMethodResolver resolver = new AnnotationExceptionHandlerMethodResolver(ExceptionController.class);
    IOException ioException = new FileNotFoundException();
    assertEquals("handleIOException", resolver.resolveMethod(ioException).getName());
    SocketException bindException = new BindException();
    assertEquals("handleSocketException", resolver.resolveMethod(bindException).getName());
}
Also used : SocketException(java.net.SocketException) FileNotFoundException(java.io.FileNotFoundException) BindException(java.net.BindException) IOException(java.io.IOException) Test(org.junit.Test)

Example 37 with BindException

use of java.net.BindException in project spring-framework by spring-projects.

the class MBeanClientInterceptorTests method testTestLazyConnectionToRemote.

@Test
public void testTestLazyConnectionToRemote() throws Exception {
    assumeTrue(runTests);
    Assume.group(TestGroup.JMXMP);
    final int port = SocketUtils.findAvailableTcpPort();
    JMXServiceURL url = new JMXServiceURL("service:jmx:jmxmp://localhost:" + port);
    JMXConnectorServer connector = JMXConnectorServerFactory.newJMXConnectorServer(url, null, getServer());
    MBeanProxyFactoryBean factory = new MBeanProxyFactoryBean();
    factory.setServiceUrl(url.toString());
    factory.setProxyInterface(IJmxTestBean.class);
    factory.setObjectName(OBJECT_NAME);
    factory.setConnectOnStartup(false);
    factory.setRefreshOnConnectFailure(true);
    // should skip connection to the server
    factory.afterPropertiesSet();
    IJmxTestBean bean = (IJmxTestBean) factory.getObject();
    // now start the connector
    try {
        connector.start();
    } catch (BindException ex) {
        System.out.println("Skipping remainder of JMX LazyConnectionToRemote test because binding to local port [" + port + "] failed: " + ex.getMessage());
        return;
    }
    // should now be able to access data via the lazy proxy
    try {
        assertEquals("Rob Harrop", bean.getName());
        assertEquals(100, bean.getAge());
    } finally {
        connector.stop();
    }
    try {
        bean.getName();
    } catch (JmxException ex) {
    // expected
    }
    connector = JMXConnectorServerFactory.newJMXConnectorServer(url, null, getServer());
    connector.start();
    // should now be able to access data via the lazy proxy
    try {
        assertEquals("Rob Harrop", bean.getName());
        assertEquals(100, bean.getAge());
    } finally {
        connector.stop();
    }
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) JmxException(org.springframework.jmx.JmxException) BindException(java.net.BindException) IJmxTestBean(org.springframework.jmx.IJmxTestBean) JMXConnectorServer(javax.management.remote.JMXConnectorServer) Test(org.junit.Test)

Example 38 with BindException

use of java.net.BindException in project cdap by caskdata.

the class ExternalAuthenticationServer method startUp.

@Override
protected void startUp() throws Exception {
    try {
        server = new Server();
        try {
            bindAddress = InetAddress.getByName(cConfiguration.get(Constants.Security.AUTH_SERVER_BIND_ADDRESS));
        } catch (UnknownHostException e) {
            LOG.error("Error finding host to connect to.", e);
            throw e;
        }
        QueuedThreadPool threadPool = new QueuedThreadPool();
        threadPool.setMaxThreads(maxThreads);
        server.setThreadPool(threadPool);
        initHandlers();
        ServletContextHandler context = new ServletContextHandler();
        context.setServer(server);
        context.addServlet(HttpServletDispatcher.class, "/");
        context.addEventListener(new AuthenticationGuiceServletContextListener(handlers));
        context.setSecurityHandler(authenticationHandler);
        // Status endpoint should be handled without the authentication
        ContextHandler statusContext = new ContextHandler();
        statusContext.setContextPath(Constants.EndPoints.STATUS);
        statusContext.setServer(server);
        statusContext.setHandler(new StatusRequestHandler());
        if (cConfiguration.getBoolean(Constants.Security.SSL.EXTERNAL_ENABLED, false)) {
            SslContextFactory sslContextFactory = new SslContextFactory();
            String keyStorePath = sConfiguration.get(Constants.Security.AuthenticationServer.SSL_KEYSTORE_PATH);
            String keyStorePassword = sConfiguration.get(Constants.Security.AuthenticationServer.SSL_KEYSTORE_PASSWORD);
            String keyStoreType = sConfiguration.get(Constants.Security.AuthenticationServer.SSL_KEYSTORE_TYPE, Constants.Security.AuthenticationServer.DEFAULT_SSL_KEYSTORE_TYPE);
            String keyPassword = sConfiguration.get(Constants.Security.AuthenticationServer.SSL_KEYPASSWORD);
            Preconditions.checkArgument(keyStorePath != null, "Key Store Path Not Configured");
            Preconditions.checkArgument(keyStorePassword != null, "KeyStore Password Not Configured");
            sslContextFactory.setKeyStorePath(keyStorePath);
            sslContextFactory.setKeyStorePassword(keyStorePassword);
            sslContextFactory.setKeyStoreType(keyStoreType);
            if (keyPassword != null && keyPassword.length() != 0) {
                sslContextFactory.setKeyManagerPassword(keyPassword);
            }
            String trustStorePath = cConfiguration.get(Constants.Security.AuthenticationServer.SSL_TRUSTSTORE_PATH);
            if (StringUtils.isNotEmpty(trustStorePath)) {
                String trustStorePassword = cConfiguration.get(Constants.Security.AuthenticationServer.SSL_TRUSTSTORE_PASSWORD);
                String trustStoreType = cConfiguration.get(Constants.Security.AuthenticationServer.SSL_TRUSTSTORE_TYPE, Constants.Security.AuthenticationServer.DEFAULT_SSL_KEYSTORE_TYPE);
                // SSL handshaking will involve requesting for a client certificate, if cert is not provided
                // server continues with the connection but the client is considered to be unauthenticated
                sslContextFactory.setWantClientAuth(true);
                sslContextFactory.setTrustStore(trustStorePath);
                sslContextFactory.setTrustStorePassword(trustStorePassword);
                sslContextFactory.setTrustStoreType(trustStoreType);
                sslContextFactory.setValidateCerts(true);
            }
            // TODO Figure out how to pick a certificate from key store
            SslSelectChannelConnector sslConnector = new SslSelectChannelConnector(sslContextFactory);
            sslConnector.setHost(bindAddress.getCanonicalHostName());
            sslConnector.setPort(port);
            server.setConnectors(new Connector[] { sslConnector });
        } else {
            SelectChannelConnector connector = new SelectChannelConnector();
            connector.setHost(bindAddress.getCanonicalHostName());
            connector.setPort(port);
            server.setConnectors(new Connector[] { connector });
        }
        HandlerCollection handlers = new HandlerCollection();
        handlers.addHandler(statusContext);
        handlers.addHandler(context);
        // AuditLogHandler must be last, since it needs the response that was sent to the client
        handlers.addHandler(auditLogHandler);
        server.setHandler(handlers);
    } catch (Exception e) {
        LOG.error("Error while starting Authentication Server.", e);
    }
    try {
        server.start();
    } catch (Exception e) {
        if ((Throwables.getRootCause(e) instanceof BindException)) {
            throw new ServiceBindException("Authentication Server", bindAddress.getCanonicalHostName(), port, e);
        }
        throw e;
    }
    // assumes we only have one connector
    Connector connector = server.getConnectors()[0];
    InetSocketAddress inetSocketAddress = new InetSocketAddress(connector.getHost(), connector.getLocalPort());
    serviceCancellable = discoveryService.register(ResolvingDiscoverable.of(new Discoverable(Constants.Service.EXTERNAL_AUTHENTICATION, inetSocketAddress)));
}
Also used : SslSelectChannelConnector(org.eclipse.jetty.server.ssl.SslSelectChannelConnector) SelectChannelConnector(org.eclipse.jetty.server.nio.SelectChannelConnector) Connector(org.eclipse.jetty.server.Connector) Discoverable(org.apache.twill.discovery.Discoverable) ResolvingDiscoverable(co.cask.cdap.common.discovery.ResolvingDiscoverable) ServiceBindException(co.cask.cdap.common.ServiceBindException) Server(org.eclipse.jetty.server.Server) UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) BindException(java.net.BindException) ServiceBindException(co.cask.cdap.common.ServiceBindException) BindException(java.net.BindException) ServiceBindException(co.cask.cdap.common.ServiceBindException) UnknownHostException(java.net.UnknownHostException) SslSelectChannelConnector(org.eclipse.jetty.server.ssl.SslSelectChannelConnector) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SslSelectChannelConnector(org.eclipse.jetty.server.ssl.SslSelectChannelConnector) SelectChannelConnector(org.eclipse.jetty.server.nio.SelectChannelConnector) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 39 with BindException

use of java.net.BindException in project cdap by caskdata.

the class NettyRouter method bootstrapServer.

private void bootstrapServer(final ChannelUpstreamHandler connectionTracker) throws ServiceBindException {
    ExecutorService serverBossExecutor = createExecutorService(serverBossThreadPoolSize, "router-server-boss-thread-%d");
    ExecutorService serverWorkerExecutor = createExecutorService(serverWorkerThreadPoolSize, "router-server-worker-thread-%d");
    serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(serverBossExecutor, serverWorkerExecutor));
    serverBootstrap.setOption("backlog", serverConnectionBacklog);
    serverBootstrap.setOption("child.bufferFactory", new DirectChannelBufferFactory());
    // Setup the pipeline factory
    serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = Channels.pipeline();
            if (isSSLEnabled()) {
                // Add SSLHandler is SSL is enabled
                pipeline.addLast("ssl", sslHandlerFactory.create());
            }
            pipeline.addLast("tracker", connectionTracker);
            pipeline.addLast("http-response-encoder", new HttpResponseEncoder());
            pipeline.addLast("http-decoder", new HttpRequestDecoder());
            pipeline.addLast("http-status-request-handler", new HttpStatusRequestHandler());
            if (securityEnabled) {
                pipeline.addLast("access-token-authenticator", new SecurityAuthenticationHttpHandler(realm, tokenValidator, configuration, accessTokenTransformer, discoveryServiceClient));
            }
            // for now there's only one hardcoded rule, but if there will be more, we may want it generic and configurable
            pipeline.addLast("http-request-handler", new HttpRequestHandler(clientBootstrap, serviceLookup, ImmutableList.<ProxyRule>of()));
            return pipeline;
        }
    });
    // Start listening on ports.
    ImmutableMap.Builder<Integer, String> serviceMapBuilder = ImmutableMap.builder();
    for (Map.Entry<String, Integer> forward : serviceToPortMap.entrySet()) {
        int port = forward.getValue();
        String service = forward.getKey();
        String boundService = serviceLookup.getService(port);
        if (boundService != null) {
            LOG.warn("Port {} is already configured to service {}, ignoring forward for service {}", port, boundService, service);
            continue;
        }
        InetSocketAddress bindAddress = new InetSocketAddress(hostname, port);
        LOG.info("Starting Netty Router for service {} on address {}...", service, bindAddress);
        try {
            Channel channel = serverBootstrap.bind(bindAddress);
            InetSocketAddress boundAddress = (InetSocketAddress) channel.getLocalAddress();
            serviceMapBuilder.put(boundAddress.getPort(), service);
            channelGroup.add(channel);
            // Update service map
            serviceLookup.updateServiceMap(serviceMapBuilder.build());
            LOG.info("Started Netty Router for service {} on address {}.", service, boundAddress);
        } catch (ChannelException e) {
            if ((Throwables.getRootCause(e) instanceof BindException)) {
                throw new ServiceBindException("Router", hostname.getCanonicalHostName(), port, e);
            }
            throw e;
        }
    }
}
Also used : ServiceBindException(co.cask.cdap.common.ServiceBindException) HttpRequestHandler(co.cask.cdap.gateway.router.handlers.HttpRequestHandler) InetSocketAddress(java.net.InetSocketAddress) SecurityAuthenticationHttpHandler(co.cask.cdap.gateway.router.handlers.SecurityAuthenticationHttpHandler) HttpStatusRequestHandler(co.cask.cdap.gateway.router.handlers.HttpStatusRequestHandler) HttpRequestDecoder(org.jboss.netty.handler.codec.http.HttpRequestDecoder) ChannelException(org.jboss.netty.channel.ChannelException) NioServerSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory) Channel(org.jboss.netty.channel.Channel) BindException(java.net.BindException) ServiceBindException(co.cask.cdap.common.ServiceBindException) DirectChannelBufferFactory(org.jboss.netty.buffer.DirectChannelBufferFactory) ServerBootstrap(org.jboss.netty.bootstrap.ServerBootstrap) ChannelException(org.jboss.netty.channel.ChannelException) BindException(java.net.BindException) ServiceBindException(co.cask.cdap.common.ServiceBindException) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) ImmutableMap(com.google.common.collect.ImmutableMap) HttpResponseEncoder(org.jboss.netty.handler.codec.http.HttpResponseEncoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) ChannelPipelineFactory(org.jboss.netty.channel.ChannelPipelineFactory) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 40 with BindException

use of java.net.BindException in project midpoint by Evolveum.

the class SqlRepositoryFactory method checkPort.

private void checkPort(int port) throws RepositoryServiceFactoryException {
    if (port >= 65635 || port < 0) {
        throw new RepositoryServiceFactoryException("Port must be in range 0-65634, not '" + port + "'.");
    }
    ServerSocket ss = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
    } catch (BindException e) {
        throw new RepositoryServiceFactoryException("Configured port (" + port + ") for H2 already in use.", e);
    } catch (IOException e) {
        LOGGER.error("Reported IO error, while binding ServerSocket to port " + port + " used to test availability " + "of port for H2 Server", e);
    } finally {
        try {
            if (ss != null) {
                ss.close();
            }
        } catch (IOException ex) {
            LOGGER.error("Reported IO error, while closing ServerSocket used to test availability " + "of port for H2 Server", ex);
        }
    }
}
Also used : BindException(java.net.BindException) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) RepositoryServiceFactoryException(com.evolveum.midpoint.repo.api.RepositoryServiceFactoryException)

Aggregations

BindException (java.net.BindException)103 IOException (java.io.IOException)34 InetSocketAddress (java.net.InetSocketAddress)25 ServerSocket (java.net.ServerSocket)22 Test (org.junit.Test)22 File (java.io.File)12 SocketException (java.net.SocketException)10 Configuration (org.apache.hadoop.conf.Configuration)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 InterruptedIOException (java.io.InterruptedIOException)5 MiniDFSNNTopology (org.apache.hadoop.hdfs.MiniDFSNNTopology)5 InetAddress (java.net.InetAddress)4 UnknownHostException (java.net.UnknownHostException)4 RemoteException (java.rmi.RemoteException)4 NIOServerCnxnFactory (org.apache.zookeeper.server.NIOServerCnxnFactory)4 ZooKeeperServer (org.apache.zookeeper.server.ZooKeeperServer)4 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)3 Socket (java.net.Socket)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3