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