下面列出了javax.servlet.ServletResponseWrapper#io.undertow.servlet.handlers.ServletRequestContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public boolean resolve(final HttpServerExchange value) {
String location = this.location.readAttribute(value);
ServletRequestContext src = value.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if(src == null) {
return false;
}
ResourceManager manager = src.getDeployment().getDeploymentInfo().getResourceManager();
if(manager == null) {
return false;
}
try {
Resource resource = manager.getResource(location);
if(resource == null) {
return false;
}
return resource.isDirectory();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void logout() {
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
req.removeAttribute(KeycloakUndertowAccount.class.getName());
req.removeAttribute(KeycloakSecurityContext.class.getName());
HttpSession session = req.getSession(false);
if (session == null) return;
try {
KeycloakUndertowAccount account = (KeycloakUndertowAccount) session.getAttribute(KeycloakUndertowAccount.class.getName());
if (account == null) return;
session.removeAttribute(KeycloakSecurityContext.class.getName());
session.removeAttribute(KeycloakUndertowAccount.class.getName());
} catch (IllegalStateException ise) {
// Session may be already logged-out in case that app has adminUrl
log.debugf("Session %s logged-out already", session.getId());
}
}
@Override
public String readAttribute(final HttpServerExchange exchange) {
ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if(src == null) {
return RelativePathAttribute.INSTANCE.readAttribute(exchange);
}
String path = (String) src.getServletRequest().getAttribute(RequestDispatcher.FORWARD_PATH_INFO);
String sp = (String) src.getServletRequest().getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH);
if(path == null && sp == null) {
return RelativePathAttribute.INSTANCE.readAttribute(exchange);
}
if(sp == null) {
return path;
} else if(path == null) {
return sp;
} else {
return sp + path;
}
}
@Override
public String readAttribute(final HttpServerExchange exchange) {
ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (src == null) {
return RequestURLAttribute.INSTANCE.readAttribute(exchange);
}
String uri = (String) src.getServletRequest().getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
if (uri != null) {
return uri;
}
uri = (String) src.getServletRequest().getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
if (uri != null) {
return uri;
}
return RequestURLAttribute.INSTANCE.readAttribute(exchange);
}
@Override
public String findSessionId(HttpServerExchange exchange) {
String invalidated = exchange.getAttachment(INVALIDATED);
ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
final String current;
if(src.getOverridenSessionId() == null) {
current = delegate.findSessionId(exchange);
} else {
current = src.getOverridenSessionId();
}
if(invalidated == null) {
return current;
}
if(invalidated.equals(current)) {
return null;
}
return current;
}
/**
* This method doesn't save content of request but instead uses data from parameter.
* This should be used in case that data from request was already read and therefore it is not possible to save them.
*
* @param exchange
* @param bytes
* @param contentLength
*/
protected void storeInitialLocation(final HttpServerExchange exchange, byte[] bytes, int contentLength) {
if(!saveOriginalRequest) {
return;
}
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, true);
Session session;
if (System.getSecurityManager() == null) {
session = httpSession.getSession();
} else {
session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
}
SessionManager manager = session.getSessionManager();
if (seenSessionManagers.add(manager)) {
manager.registerSessionListener(LISTENER);
}
session.setAttribute(SESSION_KEY, RedirectBuilder.redirect(exchange, exchange.getRelativePath()));
if(bytes == null) {
SavedRequest.trySaveRequest(exchange);
} else {
SavedRequest.trySaveRequest(exchange, bytes, contentLength);
}
}
@Override
public <T, C> Action<T, C> create(final Action<T, C> action) {
return new Action<T, C>() {
@Override
public T call(HttpServerExchange exchange, C context) throws Exception {
if (exchange == null) {
return action.call(null, context);
} else {
ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
final ServletRequestContext old = ServletRequestContext.current();
SecurityActions.setCurrentRequestContext(servletRequestContext);
try {
return action.call(exchange, context);
} finally {
ServletRequestContext.setCurrentRequestContext(old);
}
}
}
};
}
@Override
public AsyncContext startAsync(final ServletRequest servletRequest, final ServletResponse servletResponse) throws IllegalStateException {
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (!servletContext.getDeployment().getDeploymentInfo().isAllowNonStandardWrappers()) {
if (servletRequestContext.getOriginalRequest() != servletRequest) {
if (!(servletRequest instanceof ServletRequestWrapper)) {
throw UndertowServletMessages.MESSAGES.requestWasNotOriginalOrWrapper(servletRequest);
}
}
if (servletRequestContext.getOriginalResponse() != servletResponse) {
if (!(servletResponse instanceof ServletResponseWrapper)) {
throw UndertowServletMessages.MESSAGES.responseWasNotOriginalOrWrapper(servletResponse);
}
}
}
if (!isAsyncSupported()) {
throw UndertowServletMessages.MESSAGES.startAsyncNotAllowed();
} else if (asyncStarted) {
throw UndertowServletMessages.MESSAGES.asyncAlreadyStarted();
}
asyncStarted = true;
servletRequestContext.setServletRequest(servletRequest);
servletRequestContext.setServletResponse(servletResponse);
return asyncContext = new AsyncContextImpl(exchange, servletRequest, servletResponse, servletRequestContext, true, asyncContext);
}
@Override
public void setCharacterEncoding(final String env) throws UnsupportedEncodingException {
if (readStarted) {
return;
}
try {
characterEncoding = Charset.forName(env);
final ManagedServlet originalServlet = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getOriginalServletPathMatch().getServletChain().getManagedServlet();
// final FormDataParser parser = originalServlet.getFormParserFactory().createParser(exchange);
// if (parser != null) {
// parser.setCharacterEncoding(env);
// }
} catch (UnsupportedCharsetException e) {
throw new UnsupportedEncodingException();
}
}
@Override
public String readAttribute(final HttpServerExchange exchange) {
ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (src == null) {
return RequestURLAttribute.INSTANCE.readAttribute(exchange);
}
String uri = (String) src.getServletRequest().getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
if (uri != null) {
return uri;
}
uri = (String) src.getServletRequest().getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
if (uri != null) {
return uri;
}
return RequestURLAttribute.INSTANCE.readAttribute(exchange);
}
public AsyncContextImpl(final HttpServerExchange exchange, final ServletRequest servletRequest, final ServletResponse servletResponse, final ServletRequestContext servletRequestContext, boolean requestSupplied, final AsyncContextImpl previousAsyncContext) {
this.exchange = exchange;
this.servletRequest = servletRequest;
this.servletResponse = servletResponse;
this.servletRequestContext = servletRequestContext;
this.requestSupplied = requestSupplied;
this.previousAsyncContext = previousAsyncContext;
initiatingThread = Thread.currentThread();
exchange.dispatch(SameThreadExecutor.INSTANCE, new Runnable() {
@Override
public void run() {
exchange.setDispatchExecutor(null);
initialRequestDone();
}
});
}
public static HttpSessionImpl forSession(final Session session, final ServletContext servletContext, final boolean newSession) {
// forSession is called by privileged actions only so no need to do it again
ServletRequestContext current = ServletRequestContext.current();
if (current == null) {
return new HttpSessionImpl(session, servletContext, newSession, null);
} else {
HttpSessionImpl httpSession = current.getSession();
if (httpSession == null) {
httpSession = new HttpSessionImpl(session, servletContext, newSession, current);
current.setSession(httpSession);
} else {
if(httpSession.session != session) {
//in some rare cases it may be that there are two different service contexts involved in the one request
//in this case we just return a new session rather than using the thread local version
httpSession = new HttpSessionImpl(session, servletContext, newSession, current);
}
}
return httpSession;
}
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
ServletRequest request = servletRequestContext.getServletRequest();
if (request.getDispatcherType() == DispatcherType.REQUEST) {
List<SingleConstraintMatch> constraints = servletRequestContext.getRequiredConstrains();
SecurityContext sc = exchange.getSecurityContext();
if (!authorizationManager.canAccessResource(constraints, sc.getAuthenticatedAccount(), servletRequestContext.getCurrentServlet().getManagedServlet().getServletInfo(), servletRequestContext.getOriginalRequest(), servletRequestContext.getDeployment())) {
HttpServletResponse response = (HttpServletResponse) servletRequestContext.getServletResponse();
response.sendError(StatusCodes.FORBIDDEN);
return;
}
}
next.handleRequest(exchange);
}
public void handleNormalRequest(HttpServerExchange undertowExchange) throws Exception {
HttpServletResponseImpl response = new HttpServletResponseImpl(undertowExchange,
(ServletContextImpl)servletContext);
HttpServletRequestImpl request = new HttpServletRequestImpl(undertowExchange,
(ServletContextImpl)servletContext);
ServletRequestContext servletRequestContext = new ServletRequestContext(((ServletContextImpl)servletContext)
.getDeployment(), request, response, null);
undertowExchange.putAttachment(ServletRequestContext.ATTACHMENT_KEY, servletRequestContext);
try {
framework.doCometSupport(AtmosphereRequestImpl.wrap(request),
AtmosphereResponseImpl.wrap(response));
} catch (ServletException e) {
throw new IOException(e);
}
}
public AsyncContextImpl(final HttpServerExchange exchange, final ServletRequest servletRequest, final ServletResponse servletResponse, final ServletRequestContext servletRequestContext, boolean requestSupplied, final AsyncContextImpl previousAsyncContext) {
this.exchange = exchange;
this.servletRequest = servletRequest;
this.servletResponse = servletResponse;
this.servletRequestContext = servletRequestContext;
this.requestSupplied = requestSupplied;
this.previousAsyncContext = previousAsyncContext;
initiatingThread = Thread.currentThread();
exchange.dispatch(SameThreadExecutor.INSTANCE, new Runnable() {
@Override
public void run() {
exchange.setDispatchExecutor(null);
initialRequestDone();
}
});
}
public void doErrorDispatch(int sc, String error) throws IOException {
writer = null;
responseState = ResponseState.NONE;
resetBuffer();
treatAsCommitted = false;
final String location = servletContext.getDeployment().getErrorPages().getErrorLocation(sc);
if (location != null) {
RequestDispatcherImpl requestDispatcher = new RequestDispatcherImpl(location, servletContext);
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
try {
requestDispatcher.error(servletRequestContext, servletRequestContext.getServletRequest(), servletRequestContext.getServletResponse(), exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getCurrentServlet().getManagedServlet().getServletInfo().getName(), error);
} catch (ServletException e) {
throw new RuntimeException(e);
}
} else if (error != null) {
setContentType("text/html");
setCharacterEncoding("UTF-8");
if(servletContext.getDeployment().getDeploymentInfo().isEscapeErrorMessage()) {
getWriter().write("<html><head><title>Error</title></head><body>" + escapeHtml(error) + "</body></html>");
} else {
getWriter().write("<html><head><title>Error</title></head><body>" + error + "</body></html>");
}
getWriter().close();
}
responseDone();
}
/**
* This method doesn't save content of request but instead uses data from parameter.
* This should be used in case that data from request was already read and therefore it is not possible to save them.
*
* @param exchange
* @param bytes
* @param contentLength
*/
protected void storeInitialLocation(final HttpServerExchange exchange, byte[] bytes, int contentLength) {
if(!saveOriginalRequest) {
return;
}
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, true);
Session session;
if (System.getSecurityManager() == null) {
session = httpSession.getSession();
} else {
session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
}
SessionManager manager = session.getSessionManager();
if (seenSessionManagers.add(manager)) {
manager.registerSessionListener(LISTENER);
}
session.setAttribute(SESSION_KEY, RedirectBuilder.redirect(exchange, exchange.getRelativePath()));
if(bytes == null) {
SavedRequest.trySaveRequest(exchange);
} else {
SavedRequest.trySaveRequest(exchange, bytes, contentLength);
}
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final String path = exchange.getRelativePath();
SecurityPathMatch securityMatch = securityPathMatches.getSecurityInfo(path, exchange.getRequestMethod());
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
List<SingleConstraintMatch> list = servletRequestContext.getRequiredConstrains();
if (list == null) {
servletRequestContext.setRequiredConstrains(list = new ArrayList<>());
}
list.add(securityMatch.getMergedConstraint());
TransportGuaranteeType type = servletRequestContext.getTransportGuarenteeType();
if (type == null || type.ordinal() < securityMatch.getTransportGuaranteeType().ordinal()) {
servletRequestContext.setTransportGuarenteeType(securityMatch.getTransportGuaranteeType());
}
UndertowLogger.SECURITY_LOGGER.debugf("Security constraints for request %s are %s", exchange.getRequestURI(), list);
next.handleRequest(exchange);
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
ServletRequest request = servletRequestContext.getServletRequest();
if (request.getDispatcherType() == DispatcherType.REQUEST) {
List<SingleConstraintMatch> constraints = servletRequestContext.getRequiredConstrains();
SecurityContext sc = exchange.getSecurityContext();
if (!authorizationManager.canAccessResource(constraints, sc.getAuthenticatedAccount(), servletRequestContext.getCurrentServlet().getManagedServlet().getServletInfo(), servletRequestContext.getOriginalRequest(), servletRequestContext.getDeployment())) {
HttpServletResponse response = (HttpServletResponse) servletRequestContext.getServletResponse();
response.sendError(StatusCodes.FORBIDDEN);
return;
}
}
next.handleRequest(exchange);
}
@Override
public <T, C> Action<T, C> create(final Action<T, C> action) {
return new Action<T, C>() {
@Override
public T call(HttpServerExchange exchange, C context) throws Exception {
if (exchange == null) {
return action.call(null, context);
} else {
ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
final ServletRequestContext old = ServletRequestContext.current();
SecurityActions.setCurrentRequestContext(servletRequestContext);
try {
return action.call(exchange, context);
} finally {
ServletRequestContext.setCurrentRequestContext(old);
}
}
}
};
}
@Override
public void setCharacterEncoding(final String env) throws UnsupportedEncodingException {
if (readStarted) {
return;
}
try {
characterEncoding = Charset.forName(env);
final ManagedServlet originalServlet = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getOriginalServletPathMatch().getServletChain().getManagedServlet();
final FormDataParser parser = originalServlet.getFormParserFactory().createParser(exchange);
if (parser != null) {
parser.setCharacterEncoding(env);
}
} catch (UnsupportedCharsetException e) {
throw new UnsupportedEncodingException();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.startAsync();
resp.getOutputStream().print("hi");
resp.getOutputStream().setWriteListener(new WriteListener() {
@Override
public void onWritePossible() throws IOException {
}
@Override
public void onError(Throwable t) {
}
});
HttpServerExchange exchange = ServletRequestContext.current().getExchange();
try {
exchange.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final String path = exchange.getRelativePath();
SecurityPathMatch securityMatch = securityPathMatches.getSecurityInfo(path, exchange.getRequestMethod().toString());
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
List<SingleConstraintMatch> list = servletRequestContext.getRequiredConstrains();
if (list == null) {
servletRequestContext.setRequiredConstrains(list = new ArrayList<>());
}
list.add(securityMatch.getMergedConstraint());
TransportGuaranteeType type = servletRequestContext.getTransportGuarenteeType();
if (type == null || type.ordinal() < securityMatch.getTransportGuaranteeType().ordinal()) {
servletRequestContext.setTransportGuarenteeType(securityMatch.getTransportGuaranteeType());
}
UndertowLogger.SECURITY_LOGGER.debugf("Security constraints for request %s are %s", exchange.getRequestURI(), list);
next.handleRequest(exchange);
}
@Override
public String readAttribute(final HttpServerExchange exchange) {
ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (context != null) {
ServletRequest req = context.getServletRequest();
return req.getCharacterEncoding();
}
return null;
}
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (context != null) {
context.getServletRequest().setAttribute(attributeName, newValue);
} else {
Map<String, String> attrs = exchange.getAttachment(HttpServerExchange.REQUEST_ATTRIBUTES);
if(attrs == null) {
exchange.putAttachment(HttpServerExchange.REQUEST_ATTRIBUTES, attrs = new HashMap<>());
}
attrs.put(attributeName, newValue);
}
}
@Override
public String readAttribute(final HttpServerExchange exchange) {
ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (context != null) {
Object result = context.getServletRequest().getParameter(attributeName);
if (result != null) {
return result.toString();
}
}
return null;
}
@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);
}
@Override
public String readAttribute(final HttpServerExchange exchange) {
ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (context != null) {
Object result = context.getCurrentServletContext().getAttribute(attributeName);
if (result != null) {
return result.toString();
}
}
return null;
}
static ServletRequestContext requireCurrentServletRequestContext() {
if (System.getSecurityManager() == null) {
return ServletRequestContext.requireCurrent();
} else {
return AccessController.doPrivileged(new PrivilegedAction<ServletRequestContext>() {
@Override
public ServletRequestContext run() {
return ServletRequestContext.requireCurrent();
}
});
}
}
@Override
public String readAttribute(final HttpServerExchange exchange) {
ServletRequestContext context = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (context != null) {
ServletRequest req = context.getServletRequest();
return req.getLocale().toString();
}
return null;
}