use of io.undertow.server.HttpHandler in project openremote by openremote.
the class AbstractHttpServerProtocol method undeploy.
protected void undeploy(AssetAttribute protocolConfiguration) {
Pair<DeploymentInfo, HttpHandler> deploymentInfoHttpHandlerPair = deployments.get(protocolConfiguration.getReferenceOrThrow());
if (deploymentInfoHttpHandlerPair == null) {
LOG.info("Deployment doesn't exist for protocol configuration: " + protocolConfiguration);
return;
}
DeploymentInfo deploymentInfo = deploymentInfoHttpHandlerPair.key;
try {
LOG.info("Un-registering HTTP Server Protocol request handler '" + this.getClass().getSimpleName() + "' for request path: " + deploymentInfo.getContextPath());
webService.getRequestPathHandler().removePrefixPath(deploymentInfo.getContextPath());
DeploymentManager manager = Servlets.defaultContainer().getDeployment(deploymentInfo.getDeploymentName());
manager.stop();
manager.undeploy();
Servlets.defaultContainer().removeDeployment(deploymentInfo);
deployments.remove(protocolConfiguration.getReferenceOrThrow());
} catch (Exception ex) {
LOG.log(Level.WARNING, "An exception occurred whilst un-deploying protocolConfiguration: " + protocolConfiguration.getReferenceOrThrow(), ex);
throw new RuntimeException(ex);
}
}
use of io.undertow.server.HttpHandler in project openremote by openremote.
the class WebService method build.
protected Undertow.Builder build(Container container, Undertow.Builder builder) {
LOG.info("Building web routing with custom routes: " + getPrefixRoutes().keySet());
IdentityService identityService = container.hasService(IdentityService.class) ? container.getService(IdentityService.class) : null;
ResteasyDeployment resteasyDeployment = createResteasyDeployment(container);
HttpHandler apiHandler = createApiHandler(identityService, resteasyDeployment);
HttpHandler jsApiHandler = createJsApiHandler(identityService, resteasyDeployment);
requestPathHandler = new PathHandler(apiHandler);
HttpHandler handler = exchange -> {
String requestPath = exchange.getRequestPath();
LOG.fine("Handling request: " + exchange.getRequestMethod() + " " + exchange.getRequestPath());
// Other services can register routes here with a prefix patch match
boolean handled = false;
for (Map.Entry<String, HttpHandler> entry : getPrefixRoutes().entrySet()) {
if (requestPath.startsWith(entry.getKey())) {
LOG.fine("Handling with '" + entry.getValue().getClass().getName() + "' path prefix: " + entry.getKey());
entry.getValue().handleRequest(exchange);
handled = true;
break;
}
}
if (handled)
return;
// Redirect / to default realm
if (requestPath.equals("/")) {
LOG.fine("Handling root request, redirecting client to default realm: " + requestPath);
new RedirectHandler(fromUri(exchange.getRequestURL()).replacePath(getDefaultRealm()).build().toString()).handleRequest(exchange);
return;
}
// Serve JavaScript API with path /jsapi/*
if (jsApiHandler != null && requestPath.startsWith(JSAPI_PATH)) {
LOG.fine("Serving JS API call: " + requestPath);
jsApiHandler.handleRequest(exchange);
return;
}
// Serve /<realm>/index.html
Matcher realmRootMatcher = PATTERN_REALM_ROOT.matcher(requestPath);
if (getRealmIndexHandler() != null && realmRootMatcher.matches()) {
LOG.fine("Serving index document of realm: " + requestPath);
exchange.setRelativePath("/index.html");
getRealmIndexHandler().handleRequest(exchange);
return;
}
Matcher realmSubMatcher = PATTERN_REALM_SUB.matcher(requestPath);
if (!realmSubMatcher.matches()) {
exchange.setStatusCode(NOT_FOUND.getStatusCode());
throw new WebApplicationException(NOT_FOUND);
}
// Extract realm from path and push it into REQUEST_HEADER_REALM header
String realm = realmSubMatcher.group(1);
// Move the realm from path segment to header
exchange.getRequestHeaders().put(HttpString.tryFromString(REQUEST_HEADER_REALM), realm);
// Rewrite path, remove realm segment
URI url = fromUri(exchange.getRequestURL()).replacePath(realmSubMatcher.group(2)).build();
exchange.setRequestURI(url.toString(), true);
exchange.setRequestPath(url.getPath());
exchange.setRelativePath(url.getPath());
// Look for registered path handlers and fallback to API handler
LOG.fine("Serving HTTP call: " + url.getPath());
requestPathHandler.handleRequest(exchange);
};
handler = new WebServiceExceptions.RootUndertowExceptionHandler(devMode, handler);
if (getBoolean(container.getConfig(), WEBSERVER_DUMP_REQUESTS, WEBSERVER_DUMP_REQUESTS_DEFAULT)) {
handler = new RequestDumpingHandler(handler);
}
builder.setHandler(handler);
return builder;
}
use of io.undertow.server.HttpHandler in project openremote by openremote.
the class DefaultWebsocketComponent method deploy.
@Override
protected void deploy() throws Exception {
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
getConsumers().entrySet().forEach(consumerEntry -> {
String endpointPath = MessageBrokerSetupService.WEBSOCKET_PATH + "/" + consumerEntry.getKey();
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(consumerEntry.getValue());
}
@SuppressWarnings("unchecked")
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
Principal principal = request.getUserPrincipal();
if (principal == null) {
throw new WebApplicationException("Request is not authenticated, can't access user principal", FORBIDDEN);
}
AuthContext authContext;
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 {
throw new WebApplicationException("Unsupported user principal type: " + principal, INTERNAL_SERVER_ERROR);
}
config.getUserProperties().put(WebsocketConstants.HANDSHAKE_AUTH, authContext);
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));
deploymentInfo = new DeploymentInfo().setDeploymentName("WebSocket Deployment").setContextPath(MessageBrokerSetupService.WEBSOCKET_PATH).addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo).setClassLoader(WebsocketComponent.class.getClassLoader());
WebResourceCollection resourceCollection = new WebResourceCollection();
resourceCollection.addUrlPattern("/*");
// Require authentication, but authorize specific roles later in Camel
SecurityConstraint constraint = new SecurityConstraint();
constraint.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.AUTHENTICATE);
constraint.addWebResourceCollection(resourceCollection);
deploymentInfo.addSecurityConstraints(constraint);
HttpHandler handler = webService.addServletDeployment(identityService, deploymentInfo, true);
webService.getPrefixRoutes().put(MessageBrokerSetupService.WEBSOCKET_PATH, handler);
}
use of io.undertow.server.HttpHandler in project camel by apache.
the class CamelRootHandler method remove.
public synchronized void remove(String path, String[] methods, boolean prefixMatch) {
String basePath = getBasePath(path);
HttpHandler basePathHandler = pathHandler.getHandler(basePath);
if (basePathHandler == null) {
return;
}
if (path.contains("{")) {
// Removing a handler for the template path
String relativePath = path.substring(basePath.length());
CamelPathTemplateHandler templateHandler = (CamelPathTemplateHandler) basePathHandler;
CamelMethodHandler targetHandler = templateHandler.get(relativePath);
if (methods != null && methods.length != 0) {
targetHandler.remove(methods);
} else {
targetHandler.removeDefault();
}
if (targetHandler.isEmpty()) {
templateHandler.remove(relativePath);
if (templateHandler.isEmpty()) {
pathHandler.removePrefixPath(basePath);
}
}
} else {
// Removing a handler for the static path
if (basePathHandler instanceof CamelPathTemplateHandler) {
String relativePath = path.substring(basePath.length());
CamelPathTemplateHandler templateHandler = (CamelPathTemplateHandler) basePathHandler;
CamelMethodHandler targetHandler = templateHandler.getDefault();
if (methods != null && methods.length != 0) {
targetHandler.remove(methods);
} else {
targetHandler.removeDefault();
}
if (targetHandler.isEmpty()) {
templateHandler.remove(relativePath);
if (templateHandler.isEmpty()) {
pathHandler.removePrefixPath(basePath);
}
}
} else {
CamelMethodHandler targetHandler = (CamelMethodHandler) basePathHandler;
if (methods != null && methods.length != 0) {
targetHandler.remove(methods);
} else {
targetHandler.removeDefault();
}
if (targetHandler.isEmpty()) {
if (prefixMatch) {
pathHandler.removePrefixPath(basePath);
} else {
pathHandler.removeExactPath(basePath);
}
}
}
}
}
use of io.undertow.server.HttpHandler in project undertow by undertow-io.
the class ServerSentEventSCI method onStartup.
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
if (c == null || c.isEmpty()) {
return;
}
try {
final Map<String, ServerSentEventConnectionCallback> callbacks = new HashMap<>();
ServletContextImpl servletContext = (ServletContextImpl) ctx;
final List<InstanceHandle<?>> handles = new ArrayList<>();
for (Class<?> clazz : c) {
final ServerSentEvent annotation = clazz.getAnnotation(ServerSentEvent.class);
if (annotation == null) {
continue;
}
String path = annotation.value();
final InstanceHandle<?> instance = servletContext.getDeployment().getDeploymentInfo().getClassIntrospecter().createInstanceFactory(clazz).createInstance();
handles.add(instance);
callbacks.put(path, (ServerSentEventConnectionCallback) instance.getInstance());
}
if (callbacks.isEmpty()) {
return;
}
servletContext.getDeployment().getDeploymentInfo().addInnerHandlerChainWrapper(new HandlerWrapper() {
@Override
public HttpHandler wrap(HttpHandler handler) {
PathTemplateHandler pathTemplateHandler = new PathTemplateHandler(handler, false);
for (Map.Entry<String, ServerSentEventConnectionCallback> e : callbacks.entrySet()) {
pathTemplateHandler.add(e.getKey(), new ServerSentEventHandler(e.getValue()));
}
return pathTemplateHandler;
}
});
servletContext.addListener(new ServletContextListener() {
@Override
public void contextInitialized(ServletContextEvent sce) {
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
for (InstanceHandle<?> h : handles) {
h.release();
}
}
});
} catch (Exception e) {
throw new ServletException(e);
}
}
Aggregations