下面列出了javax.servlet.http.HttpUpgradeHandler#io.undertow.servlet.api.Deployment 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public ServletInitialHandler(final ServletPathMatches paths, final HttpHandler next, final Deployment deployment, final ServletContextImpl servletContext) {
this.next = next;
this.servletContext = servletContext;
this.paths = paths;
this.listeners = servletContext.getDeployment().getApplicationListeners();
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
//handle request can use doPrivilidged
//we need to make sure this is not abused
sm.checkPermission(PERMISSION);
}
ExceptionHandler handler = servletContext.getDeployment().getDeploymentInfo().getExceptionHandler();
if (handler != null) {
this.exceptionHandler = handler;
} else {
this.exceptionHandler = LoggingExceptionHandler.DEFAULT;
}
this.firstRequestHandler = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Object, ServletRequestContext>() {
@Override
public Object call(HttpServerExchange exchange, ServletRequestContext context) throws Exception {
handleFirstRequest(exchange, context);
return null;
}
});
}
@Override
public boolean isUserInRole(String role, Account account, ServletInfo servletInfo, HttpServletRequest request, Deployment deployment) {
final Map<String, Set<String>> principalVersusRolesMap = deployment.getDeploymentInfo().getPrincipalVersusRolesMap();
final Set<String> roles = principalVersusRolesMap.get(account.getPrincipal().getName());
//TODO: a more efficient imple
for (SecurityRoleRef ref : servletInfo.getSecurityRoleRefs()) {
if (ref.getRole().equals(role)) {
if (roles != null && roles.contains(ref.getLinkedRole())) {
return true;
}
return account.getRoles().contains(ref.getLinkedRole());
}
}
if (roles != null && roles.contains(role)) {
return true;
}
return account.getRoles().contains(role);
}
/**
* Sets up a simple servlet deployment with the provided servlets.
*
* This is just a convenience method for simple deployments
*
* @param servlets The servlets to add
*/
public static Deployment setupServlet(final ServletExtension servletExtension, final ServletInfo... servlets) {
final PathHandler pathHandler = new PathHandler();
final ServletContainer container = ServletContainer.Factory.newInstance();
DeploymentInfo builder = new DeploymentInfo()
.setClassLoader(SimpleServletTestCase.class.getClassLoader())
.setContextPath("/servletContext")
.setClassIntrospecter(TestClassIntrospector.INSTANCE)
.setDeploymentName("servletContext.war")
.addServlets(servlets);
if(servletExtension != null) {
builder.addServletExtension(servletExtension);
}
DeploymentManager manager = container.addDeployment(builder);
manager.deploy();
try {
pathHandler.addPrefixPath(builder.getContextPath(), manager.start());
} catch (ServletException e) {
throw new RuntimeException(e);
}
DefaultServer.setRootHandler(pathHandler);
return manager.getDeployment();
}
public ServletInitialHandler(final ServletPathMatches paths, final HttpHandler next, final Deployment deployment, final ServletContextImpl servletContext) {
this.next = next;
this.servletContext = servletContext;
this.paths = paths;
this.listeners = servletContext.getDeployment().getApplicationListeners();
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
//handle request can use doPrivilidged
//we need to make sure this is not abused
sm.checkPermission(PERMISSION);
}
ExceptionHandler handler = servletContext.getDeployment().getDeploymentInfo().getExceptionHandler();
if(handler != null) {
this.exceptionHandler = handler;
} else {
this.exceptionHandler = LoggingExceptionHandler.DEFAULT;
}
this.firstRequestHandler = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Object, ServletRequestContext>() {
@Override
public Object call(HttpServerExchange exchange, ServletRequestContext context) throws Exception {
handleFirstRequest(exchange, context);
return null;
}
});
}
@Override
public boolean isUserInRole(String role, Account account, ServletInfo servletInfo, HttpServletRequest request, Deployment deployment) {
final Map<String, Set<String>> principalVersusRolesMap = deployment.getDeploymentInfo().getPrincipalVersusRolesMap();
final Set<String> roles = principalVersusRolesMap.get(account.getPrincipal().getName());
//TODO: a more efficient imple
for (SecurityRoleRef ref : servletInfo.getSecurityRoleRefs()) {
if (ref.getRole().equals(role)) {
if (roles != null && roles.contains(ref.getLinkedRole())) {
return true;
}
return account.getRoles().contains(ref.getLinkedRole());
}
}
if (roles != null && roles.contains(role)) {
return true;
}
return account.getRoles().contains(role);
}
private void validateEndpointContextPath(URI httpURI) {
String undertowEndpointPath = getContextPath(httpURI);
Set<Deployment> deployments = defaultHost.getDeployments();
for (Deployment deployment : deployments) {
DeploymentInfo depInfo = deployment.getDeploymentInfo();
String contextPath = depInfo.getContextPath();
if (contextPath.equals(undertowEndpointPath)) {
final HttpHandler handler = deployment.getHandler();
if (handler instanceof CamelEndpointDeployerHandler && ((CamelEndpointDeployerHandler)handler).getRoutingHandler() instanceof DelegatingRoutingHandler) {
final ModuleClassLoader oldCl = ((DelegatingRoutingHandler)((CamelEndpointDeployerHandler)handler).getRoutingHandler()).classLoader;
final ModuleClassLoader tccl = checkTccl();
if (tccl != oldCl) {
// Avoid allowing handlers from distinct apps to handle the same path
throw new IllegalStateException("Cannot add "+ HttpHandler.class.getName() +" for path " + contextPath + " defined in " + tccl.getName() + " because that path is already served by "+ oldCl.getName());
}
} else {
// Another application already serves this path
throw new IllegalStateException("Cannot overwrite context path " + contextPath + " owned by " + depInfo.getDeploymentName());
}
}
}
}
/**
* Exposes an HTTP endpoint that will be served by the given {@link HttpHandler} under the given {@link URI}'s path.
*
* @param uri determines the path and protocol under which the HTTP endpoint should be exposed
* @param routingHandler an {@link HttpHandler} to use for handling HTTP requests sent to the given
* {@link URI}'s path
*/
public void deploy(URI uri, final HttpHandler routingHandler) {
final Set<Deployment> availableDeployments = hostSupplier.getValue().getDeployments();
if (!availableDeployments.stream().anyMatch(
deployment -> deployment.getHandler() instanceof CamelEndpointDeployerHandler
&& ((CamelEndpointDeployerHandler) deployment.getHandler()).getRoutingHandler() == routingHandler)) {
/* deploy only if the routing handler is not there already */
doDeploy(
uri,
servletInstance -> servletInstance.setEndpointHttpHandler(new DelegatingEndpointHttpHandler(routingHandler)), // plug the endpointHttpHandler into the servlet
deploymentInfo -> deploymentInfo.addInnerHandlerChainWrapper(exchangeStoringHandlerWrapper), // add the handler to the chain
deployment -> { // wrap the initial handler with our custom class so that we can recognize it at other places
final HttpHandler servletHandler = new CamelEndpointDeployerHandler(deployment.getHandler(), routingHandler);
deployment.setInitialHandler(servletHandler);
});
}
}
private void undeploy(DeploymentManager deploymentManager) {
final Deployment deployment = deploymentManager.getDeployment();
CamelLogger.LOGGER.debug("Undeploying endpoint {}", deployment.getDeploymentInfo().getDeploymentName());
final ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(deployment.getDeploymentInfo().getClassLoader());
try {
try {
hostSupplier.getValue().unregisterDeployment(deployment);
deploymentManager.stop();
} catch (ServletException e) {
throw new RuntimeException(e);
}
deploymentManager.undeploy();
servletContainerServiceSupplier.getValue().getServletContainer().removeDeployment(deployment.getDeploymentInfo());
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
public ServletContextImpl(final ServletContainer servletContainer, final Deployment deployment) {
this.servletContainer = servletContainer;
this.deployment = deployment;
this.deploymentInfo = deployment.getDeploymentInfo();
sessionCookieConfig = new SessionCookieConfigImpl(this);
sessionCookieConfig.setPath(deploymentInfo.getContextPath());
if (deploymentInfo.getServletContextAttributeBackingMap() == null) {
this.attributes = new ConcurrentHashMap<>();
} else {
this.attributes = deploymentInfo.getServletContextAttributeBackingMap();
}
attributes.putAll(deployment.getDeploymentInfo().getServletContextAttributes());
this.contentTypeCache = new LRUCache<>(deployment.getDeploymentInfo().getContentTypeCacheSize(), -1, true);
this.defaultSessionTimeout = deploymentInfo.getDefaultSessionTimeout() / 60;
}
@Override
public boolean isUserInRole(final String role) {
if (role == null) {
return false;
}
//according to the servlet spec this aways returns false
if (role.equals("*")) {
return false;
}
SecurityContext sc = exchange.getSecurityContext();
Account account = sc.getAuthenticatedAccount();
if (account == null) {
return false;
}
ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (role.equals("**")) {
Set<String> roles = servletRequestContext.getDeployment().getDeploymentInfo().getSecurityRoles();
if (!roles.contains("**")) {
return true;
}
}
final ServletChain servlet = servletRequestContext.getCurrentServlet();
final Deployment deployment = servletContext.getDeployment();
final AuthorizationManager authorizationManager = deployment.getDeploymentInfo().getAuthorizationManager();
return authorizationManager.isUserInRole(role, account, servlet.getManagedServlet().getServletInfo(), this, deployment);
}
public ServletRequestContext(final Deployment deployment, final HttpServletRequestImpl originalRequest, final HttpServletResponseImpl originalResponse, final ServletPathMatch originalServletPathMatch) {
this.deployment = deployment;
this.originalRequest = originalRequest;
this.originalResponse = originalResponse;
this.servletRequest = originalRequest;
this.servletResponse = originalResponse;
this.originalServletPathMatch = originalServletPathMatch;
this.currentServletContext = deployment.getServletContext();
}
MetricsChainHandler(HttpHandler next, MetricsCollector collector, Deployment deployment) {
this.next = next;
final Map<String, MetricsHandler> servletHandlers = new HashMap<>();
for(Map.Entry<String, ServletHandler> entry : deployment.getServlets().getServletHandlers().entrySet()) {
MetricsHandler handler = new MetricsHandler(next);
servletHandlers.put(entry.getKey(), handler);
collector.registerMetric(entry.getKey(), handler);
}
this.servletHandlers = Collections.unmodifiableMap(servletHandlers);
}
public SessionListenerBridge(final Deployment deployment, final ApplicationListeners applicationListeners, final ServletContext servletContext) {
this.applicationListeners = applicationListeners;
this.servletContext = servletContext;
this.destroyedAction = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Session>() {
@Override
public Void call(HttpServerExchange exchange, Session session) throws ServletException {
doDestroy(session);
return null;
}
});
}
static ServletInitialHandler createServletInitialHandler(final ServletPathMatches paths, final HttpHandler next, final Deployment deployment, final ServletContextImpl servletContext) {
if (System.getSecurityManager() == null) {
return new ServletInitialHandler(paths, next, deployment, servletContext);
} else {
return AccessController.doPrivileged(new PrivilegedAction<ServletInitialHandler>() {
@Override
public ServletInitialHandler run() {
return new ServletInitialHandler(paths, next, deployment, servletContext);
}
});
}
}
public ServletHttpSecurityPolicy setDeployment(Deployment deployment) {
this.deployment = deployment;
contextPath = deployment.getDeploymentInfo().getContextPath();
if (!contextPath.endsWith("/")) {
contextPath = contextPath + "/";
}
return this;
}
public ServletContextImpl(final ServletContainer servletContainer, final Deployment deployment) {
this.servletContainer = servletContainer;
this.deployment = deployment;
this.deploymentInfo = deployment.getDeploymentInfo();
sessionCookieConfig = new SessionCookieConfigImpl(this);
sessionCookieConfig.setPath(deploymentInfo.getContextPath());
if (deploymentInfo.getServletContextAttributeBackingMap() == null) {
this.attributes = new ConcurrentHashMap<>();
} else {
this.attributes = deploymentInfo.getServletContextAttributeBackingMap();
}
attributes.putAll(deployment.getDeploymentInfo().getServletContextAttributes());
this.contentTypeCache = new LRUCache<>(deployment.getDeploymentInfo().getContentTypeCacheSize(), -1, true);
this.defaultSessionTimeout = deploymentInfo.getDefaultSessionTimeout() / 60;
}
@Override
public boolean isUserInRole(final String role) {
if (role == null) {
return false;
}
//according to the servlet spec this aways returns false
if (role.equals("*")) {
return false;
}
SecurityContext sc = exchange.getSecurityContext();
Account account = sc.getAuthenticatedAccount();
if (account == null) {
return false;
}
ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (role.equals("**")) {
Set<String> roles = servletRequestContext.getDeployment().getDeploymentInfo().getSecurityRoles();
if (!roles.contains("**")) {
return true;
}
}
final ServletChain servlet = servletRequestContext.getCurrentServlet();
final Deployment deployment = servletContext.getDeployment();
final AuthorizationManager authorizationManager = deployment.getDeploymentInfo().getAuthorizationManager();
return authorizationManager.isUserInRole(role, account, servlet.getManagedServlet().getServletInfo(), this, deployment);
}
public ServletRequestContext(final Deployment deployment, final HttpServletRequestImpl originalRequest, final HttpServletResponseImpl originalResponse, final ServletPathMatch originalServletPathMatch) {
this.deployment = deployment;
this.originalRequest = originalRequest;
this.originalResponse = originalResponse;
this.servletRequest = originalRequest;
this.servletResponse = originalResponse;
this.originalServletPathMatch = originalServletPathMatch;
this.currentServletContext = deployment.getServletContext();
}
MetricsChainHandler(HttpHandler next, MetricsCollector collector, Deployment deployment) {
this.next = next;
final Map<String, MetricsHandler> servletHandlers = new HashMap<>();
for(Map.Entry<String, ServletHandler> entry : deployment.getServlets().getServletHandlers().entrySet()) {
MetricsHandler handler = new MetricsHandler(next);
servletHandlers.put(entry.getKey(), handler);
collector.registerMetric(entry.getKey(), handler);
}
this.servletHandlers = Collections.unmodifiableMap(servletHandlers);
}
public SessionListenerBridge(final Deployment deployment, final ApplicationListeners applicationListeners, final ServletContext servletContext) {
this.applicationListeners = applicationListeners;
this.servletContext = servletContext;
this.destroyedAction = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Session>() {
@Override
public Void call(HttpServerExchange exchange, Session session) throws ServletException {
doDestroy(session);
return null;
}
});
}
static ServletInitialHandler createServletInitialHandler(final ServletPathMatches paths, final HttpHandler next, final Deployment deployment, final ServletContextImpl servletContext) {
if (System.getSecurityManager() == null) {
return new ServletInitialHandler(paths, next, deployment, servletContext);
} else {
return AccessController.doPrivileged(new PrivilegedAction<ServletInitialHandler>() {
@Override
public ServletInitialHandler run() {
return new ServletInitialHandler(paths, next, deployment, servletContext);
}
});
}
}
@Override
public void onDeploymentStart(Deployment dep, Host host) {
// Ensure that a deployment HttpHandler cannot overwrite handlers created by camel-undertow
checkForOverlappingContextPath(dep);
runtimeState.addHttpContext(dep.getServletContext().getContextPath());
}
@Override
public void onDeploymentStop(Deployment dep, Host host) {
runtimeState.removeHttpContext(dep.getServletContext().getContextPath());
final DeploymentInfo depInfo = dep.getDeploymentInfo();
if (dep.getHandler() != null) {
final String contextPath = depInfo.getContextPath();
existingContextPaths.remove(contextPath);
}
}
private void checkForOverlappingContextPath(Deployment dep) {
final DeploymentInfo depInfo = dep.getDeploymentInfo();
if (dep.getHandler() != null) {
final String contextPath = depInfo.getContextPath();
final Boolean exists = existingContextPaths.putIfAbsent(contextPath, Boolean.TRUE);
IllegalStateAssertion.assertFalse(Boolean.TRUE == exists,
"Cannot overwrite context path " + contextPath + " owned by camel-undertow" + contextPath);
}
}
/**
* The stuff common for {@link #deploy(URI, EndpointHttpHandler)} and {@link #deploy(URI, HttpHandler)}.
*
* @param uri
* @param endpointServletConsumer customize the {@link EndpointServlet}
* @param deploymentInfoConsumer customize the {@link DeploymentInfo}
* @param deploymentConsumer customize the {@link DeploymentImpl}
*/
void doDeploy(URI uri, Consumer<EndpointServlet> endpointServletConsumer, Consumer<DeploymentInfo> deploymentInfoConsumer, Consumer<DeploymentImpl> deploymentConsumer) {
final ServletInfo servletInfo = Servlets.servlet(EndpointServlet.NAME, EndpointServlet.class).addMapping("/*")
.setAsyncSupported(true);
final DeploymentInfo mainDeploymentInfo = deploymentInfoSupplier.getValue();
DeploymentInfo endPointDeplyomentInfo = adaptDeploymentInfo(mainDeploymentInfo, uri, servletInfo);
deploymentInfoConsumer.accept(endPointDeplyomentInfo);
CamelLogger.LOGGER.debug("Deploying endpoint {}", endPointDeplyomentInfo.getDeploymentName());
final ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(endPointDeplyomentInfo.getClassLoader());
try {
final DeploymentManager manager = servletContainerServiceSupplier.getValue().getServletContainer()
.addDeployment(endPointDeplyomentInfo);
manager.deploy();
final Deployment deployment = manager.getDeployment();
try {
deploymentConsumer.accept((DeploymentImpl) deployment);
manager.start();
hostSupplier.getValue().registerDeployment(deployment, deployment.getHandler());
ManagedServlet managedServlet = deployment.getServlets().getManagedServlet(EndpointServlet.NAME);
EndpointServlet servletInstance = (EndpointServlet) managedServlet.getServlet().getInstance();
endpointServletConsumer.accept(servletInstance);
} catch (ServletException ex) {
throw new IllegalStateException(ex);
}
synchronized (deployments) {
deployments.put(uri, manager);
}
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
public Deployment getDeployment() {
return deployment;
}
public ServletRegistrationImpl(final ServletInfo servletInfo, ManagedServlet managedServlet, final Deployment deployment) {
this.servletInfo = servletInfo;
this.managedServlet = managedServlet;
this.deployment = deployment;
}
public FilterRegistrationImpl(final FilterInfo filterInfo, final Deployment deployment, ServletContextImpl servletContext) {
this.filterInfo = filterInfo;
this.deployment = deployment;
this.servletContext = servletContext;
}
@Override
public void dispatch(final ServletContext context, final String path) {
if (dispatched) {
throw UndertowServletMessages.MESSAGES.asyncRequestAlreadyDispatched();
}
HttpServletRequestImpl requestImpl = servletRequestContext.getOriginalRequest();
HttpServletResponseImpl responseImpl = servletRequestContext.getOriginalResponse();
final HttpServerExchange exchange = requestImpl.getExchange();
exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).setDispatcherType(DispatcherType.ASYNC);
requestImpl.setAttribute(ASYNC_REQUEST_URI, requestImpl.getOriginalRequestURI());
requestImpl.setAttribute(ASYNC_CONTEXT_PATH, requestImpl.getOriginalContextPath());
requestImpl.setAttribute(ASYNC_SERVLET_PATH, requestImpl.getOriginalServletPath());
requestImpl.setAttribute(ASYNC_QUERY_STRING, requestImpl.getOriginalQueryString());
String newQueryString = "";
int qsPos = path.indexOf("?");
String newServletPath = path;
if (qsPos != -1) {
newQueryString = newServletPath.substring(qsPos + 1);
newServletPath = newServletPath.substring(0, qsPos);
}
String newRequestUri = context.getContextPath() + newServletPath;
//todo: a more efficient impl
Map<String, Deque<String>> newQueryParameters = new HashMap<>();
for (String part : newQueryString.split("&")) {
String name = part;
String value = "";
int equals = part.indexOf('=');
if (equals != -1) {
name = part.substring(0, equals);
value = part.substring(equals + 1);
}
Deque<String> queue = newQueryParameters.get(name);
if (queue == null) {
newQueryParameters.put(name, queue = new ArrayDeque<>(1));
}
queue.add(value);
}
requestImpl.setQueryParameters(newQueryParameters);
requestImpl.getExchange().setRelativePath(newServletPath);
requestImpl.getExchange().setQueryString(newQueryString);
requestImpl.getExchange().setRequestPath(newRequestUri);
requestImpl.getExchange().setRequestURI(newRequestUri);
requestImpl.setServletContext((ServletContextImpl) context);
responseImpl.setServletContext((ServletContextImpl) context);
Deployment deployment = requestImpl.getServletContext().getDeployment();
ServletPathMatch info = deployment.getServletPaths().getServletHandlerByPath(newServletPath);
requestImpl.getExchange().getAttachment(ServletRequestContext.ATTACHMENT_KEY).setServletPathMatch(info);
dispatchAsyncRequest(deployment.getServletDispatcher(), info, exchange);
}
public ServletPathMatches(final Deployment deployment) {
this.deployment = deployment;
this.welcomePages = deployment.getDeploymentInfo().getWelcomePages().toArray(new String[deployment.getDeploymentInfo().getWelcomePages().size()]);
this.resourceManager = deployment.getDeploymentInfo().getResourceManager();
}