use of javax.websocket.server.ServerEndpointConfig in project undertow by undertow-io.
the class BinaryEndpointServlet method init.
@Override
public void init(ServletConfig c) throws ServletException {
String websocketPath = "/partial";
ServerEndpointConfig config = ServerEndpointConfig.Builder.create(BinaryPartialEndpoint.class, websocketPath).build();
ServerContainer serverContainer = (ServerContainer) c.getServletContext().getAttribute("javax.websocket.server.ServerContainer");
try {
serverContainer.addEndpoint(config);
} catch (DeploymentException ex) {
throw new ServletException("Error deploying websocket endpoint:", ex);
}
}
use of javax.websocket.server.ServerEndpointConfig in project undertow by undertow-io.
the class Bootstrap method handleDeployment.
@Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
WebSocketDeploymentInfo info = (WebSocketDeploymentInfo) deploymentInfo.getServletContextAttributes().get(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
if (info == null) {
return;
}
Supplier<XnioWorker> worker = info.getWorker();
ByteBufferPool buffers = info.getBuffers();
if (buffers == null) {
ServerWebSocketContainer defaultContainer = UndertowContainerProvider.getDefaultContainer();
if (defaultContainer == null) {
throw JsrWebSocketLogger.ROOT_LOGGER.bufferPoolWasNullAndNoDefault();
}
JsrWebSocketLogger.ROOT_LOGGER.bufferPoolWasNull();
buffers = defaultContainer.getBufferPool();
}
final List<ThreadSetupHandler> setup = new ArrayList<>();
setup.add(new ContextClassLoaderSetupAction(deploymentInfo.getClassLoader()));
setup.addAll(deploymentInfo.getThreadSetupActions());
InetSocketAddress bind = null;
if (info.getClientBindAddress() != null) {
bind = new InetSocketAddress(info.getClientBindAddress(), 0);
}
List<Extension> extensions = new ArrayList<>();
for (ExtensionHandshake e : info.getExtensions()) {
extensions.add(new ExtensionImpl(e.getName(), Collections.emptyList()));
}
ServerWebSocketContainer container = new ServerWebSocketContainer(deploymentInfo.getClassIntrospecter(), servletContext.getClassLoader(), worker, buffers, setup, info.isDispatchToWorkerThread(), bind, info.getReconnectHandler(), extensions);
try {
for (Class<?> annotation : info.getAnnotatedEndpoints()) {
container.addEndpoint(annotation);
}
for (ServerEndpointConfig programatic : info.getProgramaticEndpoints()) {
container.addEndpoint(programatic);
}
} catch (DeploymentException e) {
throw new RuntimeException(e);
}
servletContext.setAttribute(ServerContainer.class.getName(), container);
info.containerReady(container);
SecurityActions.addContainer(deploymentInfo.getClassLoader(), container);
deploymentInfo.addListener(Servlets.listener(WebSocketListener.class));
deploymentInfo.addDeploymentCompleteListener(new ServletContextListener() {
@Override
public void contextInitialized(ServletContextEvent sce) {
container.validateDeployment();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
});
}
use of javax.websocket.server.ServerEndpointConfig in project quickstart by wildfly.
the class Frontend method init.
public void init(@Observes @Initialized(ApplicationScoped.class) ServletContext servletContext) {
if (servletContext == null) {
log.severe(format("Failed to deploy frontend endpoint %s: %s", WEBSOCKET_PATH, "ServletContext not available"));
return;
}
ServerContainer serverContainer = (ServerContainer) servletContext.getAttribute("javax.websocket.server.ServerContainer");
if (serverContainer == null) {
log.severe(format("Failed to deploy frontend endpoint %s: %s", WEBSOCKET_PATH, "javax.websocket.server.ServerContainer ServerContainer not available"));
return;
}
// WebSocket does not honor CDI contexts in the default configuration; by default a new object is created for each new
// websocket.
// We can work around this by supplying a custom ServerEndpointConfig.Configurator that returns the same instance of the
// endpoint for each new websocket. Unfortunately this precludes us from using annotations, and forces us to extend the
// abstract class Endpoint, and forces us to add the server endpoint programmatically upon startup of the servlet
// context.
ServerEndpointConfig config = ServerEndpointConfig.Builder.create(Frontend.class, WEBSOCKET_PATH).configurator(new ServerEndpointConfig.Configurator() {
@SuppressWarnings("unchecked")
@Override
public <T> T getEndpointInstance(final Class<T> endpointClass) throws InstantiationException {
if (endpointClass.isAssignableFrom(Frontend.class)) {
return (T) Frontend.this;
}
return super.getEndpointInstance(endpointClass);
}
}).build();
try {
serverContainer.addEndpoint(config);
} catch (DeploymentException e) {
log.log(Level.SEVERE, format("Failed to deploy frontend endpoint %s: %s", WEBSOCKET_PATH, e.getMessage()), e);
}
}
use of javax.websocket.server.ServerEndpointConfig in project openremote by openremote.
the class DefaultWebsocketComponent method deploy.
@Override
protected void deploy() throws Exception {
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
getConsumers().forEach((key, value) -> {
String endpointPath = WEBSOCKET_PATH + "/" + key;
LOG.info("Deploying websocket endpoint: " + endpointPath);
webSocketDeploymentInfo.addEndpoint(ServerEndpointConfig.Builder.create(WebsocketAdapter.class, endpointPath).configurator(new DefaultContainerConfigurator() {
@SuppressWarnings("unchecked")
@Override
public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
return (T) new WebsocketAdapter(value);
}
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
String realm = Optional.ofNullable(request.getHeaders().get(Constants.REALM_PARAM_NAME)).map(realms -> realms.isEmpty() ? null : realms.get(0)).orElse(null);
Principal principal = request.getUserPrincipal();
AuthContext authContext = null;
if (principal instanceof KeycloakPrincipal) {
KeycloakPrincipal<?> keycloakPrincipal = (KeycloakPrincipal<?>) principal;
authContext = new AccessTokenAuthContext(keycloakPrincipal.getKeycloakSecurityContext().getRealm(), keycloakPrincipal.getKeycloakSecurityContext().getToken());
} else if (principal instanceof BasicAuthContext) {
authContext = (BasicAuthContext) principal;
} else if (principal != null) {
LOG.info("Unsupported user principal type: " + principal);
}
config.getUserProperties().put(ConnectionConstants.HANDSHAKE_AUTH, authContext);
config.getUserProperties().put(ConnectionConstants.HANDSHAKE_REALM, realm);
super.modifyHandshake(config, request, response);
}
}).build());
});
// We use the I/O thread to handle received websocket frames, as we expect to quickly hand them over to
// an internal asynchronous message queue for processing, so we don't need a separate worker thread
// pool for websocket frame processing
webSocketDeploymentInfo.setDispatchToWorkerThread(false);
// Make the shit Undertow/Websocket JSR client bootstrap happy - this is the pool that would be used
// when Undertow acts as a WebSocket client, which we don't do... and I'm not even sure it can do that...
webSocketDeploymentInfo.setWorker(Xnio.getInstance().createWorker(OptionMap.builder().set(Options.WORKER_TASK_MAX_THREADS, 1).set(Options.WORKER_NAME, "WebsocketInternalClient").set(Options.THREAD_DAEMON, true).getMap()));
boolean directBuffers = Boolean.getBoolean("io.undertow.websockets.direct-buffers");
webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(directBuffers, 1024, 100, 12));
String deploymentName = "WebSocket Deployment";
deploymentInfo = new DeploymentInfo().setDeploymentName(deploymentName).setContextPath(WEBSOCKET_PATH).addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo).setClassLoader(WebsocketComponent.class.getClassLoader());
// Require authentication, but authorize specific roles later in Camel
WebResourceCollection resourceCollection = new WebResourceCollection();
resourceCollection.addUrlPattern("/*");
SecurityConstraint constraint = new SecurityConstraint();
constraint.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT);
constraint.addWebResourceCollection(resourceCollection);
deploymentInfo.addSecurityConstraints(constraint);
HttpHandler handler = WebService.addServletDeployment(container, deploymentInfo, true);
websocketHttpHandler = pathStartsWithHandler(deploymentName, WEBSOCKET_PATH, handler);
// Give web socket handler higher priority than any other handlers already added
webService.getRequestHandlers().add(0, websocketHttpHandler);
}
use of javax.websocket.server.ServerEndpointConfig in project tomcat by apache.
the class TestWsServerContainer method testDuplicatePaths_04.
@Test
public void testDuplicatePaths_04() throws Exception {
WsServerContainer sc = new WsServerContainer(new TesterServletContext());
ServerEndpointConfig configA = ServerEndpointConfig.Builder.create(Object.class, "/a/{var1}/{var2}").build();
ServerEndpointConfig configB = ServerEndpointConfig.Builder.create(Object.class, "/a/b/{var2}").build();
sc.addEndpoint(configA);
sc.addEndpoint(configB);
Assert.assertEquals(configA, sc.findMapping("/a/x/y").getConfig());
Assert.assertEquals(configB, sc.findMapping("/a/b/y").getConfig());
}
Aggregations