use of io.undertow.servlet.spec.HttpServletRequestImpl in project undertow by undertow-io.
the class RewriteHandler method handleRequest.
public void handleRequest(HttpServerExchange exchange) throws Exception {
RewriteRule[] rules = config.getRules();
if (rules == null || rules.length == 0) {
next.handleRequest(exchange);
return;
}
if (Boolean.TRUE.equals(invoked.get())) {
next.handleRequest(exchange);
invoked.set(null);
return;
}
ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
HttpServletRequestImpl request = src.getOriginalRequest();
HttpServletResponseImpl response = src.getOriginalResponse();
UndertowResolver resolver = new UndertowResolver(src, src.getOriginalRequest());
invoked.set(Boolean.TRUE);
// As long as MB isn't a char sequence or affiliated, this has to be
// converted to a string
CharSequence url = exchange.getRelativePath();
CharSequence host = request.getServerName();
boolean rewritten = false;
boolean done = false;
for (int i = 0; i < rules.length; i++) {
CharSequence test = (rules[i].isHost()) ? host : url;
CharSequence newtest = rules[i].evaluate(test, resolver);
if (newtest != null && !test.equals(newtest.toString())) {
if (UndertowServletLogger.REQUEST_LOGGER.isDebugEnabled()) {
UndertowServletLogger.REQUEST_LOGGER.debug("Rewrote " + test + " as " + newtest + " with rule pattern " + rules[i].getPatternString());
}
if (rules[i].isHost()) {
host = newtest;
} else {
url = newtest;
}
rewritten = true;
}
// - forbidden
if (rules[i].isForbidden() && newtest != null) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
done = true;
break;
}
// - gone
if (rules[i].isGone() && newtest != null) {
response.sendError(HttpServletResponse.SC_GONE);
done = true;
break;
}
// - redirect (code)
if (rules[i].isRedirect() && newtest != null) {
// append the query string to the url if there is one and it hasn't been rewritten
String queryString = request.getQueryString();
StringBuffer urlString = new StringBuffer(url);
if (queryString != null && queryString.length() > 0) {
int index = urlString.indexOf("?");
if (index != -1) {
// if qsa is specified append the query
if (rules[i].isQsappend()) {
urlString.append('&');
urlString.append(queryString);
} else // prevent the rewrite module from appending the query string
if (index == urlString.length() - 1) {
urlString.deleteCharAt(index);
}
} else {
urlString.append('?');
urlString.append(queryString);
}
}
// 3. the url isn't absolute
if (urlString.charAt(0) == '/' && !hasScheme(urlString)) {
urlString.insert(0, request.getContextPath());
}
response.sendRedirect(urlString.toString());
response.setStatus(rules[i].getRedirectCode());
done = true;
break;
}
// - cookie
if (rules[i].isCookie() && newtest != null) {
Cookie cookie = new Cookie(rules[i].getCookieName(), rules[i].getCookieResult());
cookie.setDomain(rules[i].getCookieDomain());
cookie.setMaxAge(rules[i].getCookieLifetime());
cookie.setPath(rules[i].getCookiePath());
cookie.setSecure(rules[i].isCookieSecure());
cookie.setHttpOnly(rules[i].isCookieHttpOnly());
response.addCookie(cookie);
}
// - env (note: this sets a request attribute)
if (rules[i].isEnv() && newtest != null) {
for (int j = 0; j < rules[i].getEnvSize(); j++) {
request.setAttribute(rules[i].getEnvName(j), rules[i].getEnvResult(j));
}
}
// to do that)
if (rules[i].isType() && newtest != null) {
exchange.getRequestHeaders().put(Headers.CONTENT_TYPE, rules[i].getTypeValue());
}
// - qsappend
if (rules[i].isQsappend() && newtest != null) {
String queryString = request.getQueryString();
String urlString = url.toString();
if (urlString.indexOf('?') != -1 && queryString != null) {
url = urlString + "&" + queryString;
}
}
// - chain (skip remaining chained rules if this one does not match)
if (rules[i].isChain() && newtest == null) {
for (int j = i; j < rules.length; j++) {
if (!rules[j].isChain()) {
i = j;
break;
}
}
continue;
}
// - last (stop rewriting here)
if (rules[i].isLast() && newtest != null) {
break;
}
// - next (redo again)
if (rules[i].isNext() && newtest != null) {
i = 0;
continue;
}
// - skip (n rules)
if (newtest != null) {
i += rules[i].getSkip();
}
}
if (rewritten) {
if (!done) {
// See if we need to replace the query string
String urlString = url.toString();
String queryString = null;
int queryIndex = urlString.indexOf('?');
if (queryIndex != -1) {
queryString = urlString.substring(queryIndex + 1);
urlString = urlString.substring(0, queryIndex);
}
// Set the new URL
StringBuilder chunk = new StringBuilder();
chunk.append(request.getContextPath());
chunk.append(urlString);
String requestPath = chunk.toString();
exchange.setRequestPath(requestPath);
exchange.setRelativePath(urlString);
// Set the new Query if there is one
if (queryString != null) {
exchange.setQueryString(queryString);
exchange.getQueryParameters().clear();
exchange.getQueryParameters().putAll(QueryParameterUtils.parseQueryString(queryString, exchange.getConnection().getUndertowOptions().get(UndertowOptions.URL_CHARSET, StandardCharsets.UTF_8.name())));
}
// Set the new host if it changed
if (!host.equals(request.getServerName())) {
exchange.getRequestHeaders().put(Headers.HOST, host + ":" + exchange.getHostPort());
}
// Reinvoke the whole request recursively
src.getDeployment().getHandler().handleRequest(exchange);
}
} else {
next.handleRequest(exchange);
}
invoked.set(null);
}
use of io.undertow.servlet.spec.HttpServletRequestImpl in project undertow by undertow-io.
the class ServletInitialHandler method handleRequest.
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final String path = exchange.getRelativePath();
if (isForbiddenPath(path)) {
exchange.setStatusCode(StatusCodes.NOT_FOUND);
return;
}
final ServletPathMatch info = paths.getServletHandlerByPath(path);
//https://issues.jboss.org/browse/WFLY-3439
//if the request is an upgrade request then we don't want to redirect
//as there is a good chance the web socket client won't understand the redirect
//we make an exception for HTTP2 upgrade requests, as this would have already be handled at
//the connector level if it was going to be handled.
String upgradeString = exchange.getRequestHeaders().getFirst(Headers.UPGRADE);
boolean isUpgradeRequest = upgradeString != null && !upgradeString.startsWith(HTTP2_UPGRADE_PREFIX);
if (info.getType() == ServletPathMatch.Type.REDIRECT && !isUpgradeRequest) {
//we redirect on GET requests to the root context to add an / to the end
if (exchange.getRequestMethod().equals(Methods.GET) || exchange.getRequestMethod().equals(Methods.HEAD)) {
exchange.setStatusCode(StatusCodes.FOUND);
} else {
exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
}
exchange.getResponseHeaders().put(Headers.LOCATION, RedirectBuilder.redirect(exchange, exchange.getRelativePath() + "/", true));
return;
} else if (info.getType() == ServletPathMatch.Type.REWRITE) {
//this can only happen if the path ends with a /
//otherwise there would be a redirect instead
exchange.setRelativePath(info.getRewriteLocation());
exchange.setRequestPath(exchange.getResolvedPath() + info.getRewriteLocation());
}
final HttpServletResponseImpl response = new HttpServletResponseImpl(exchange, servletContext);
final HttpServletRequestImpl request = new HttpServletRequestImpl(exchange, servletContext);
final ServletRequestContext servletRequestContext = new ServletRequestContext(servletContext.getDeployment(), request, response, info);
//set the max request size if applicable
if (info.getServletChain().getManagedServlet().getMaxRequestSize() > 0) {
exchange.setMaxEntitySize(info.getServletChain().getManagedServlet().getMaxRequestSize());
}
exchange.putAttachment(ServletRequestContext.ATTACHMENT_KEY, servletRequestContext);
exchange.startBlocking(new ServletBlockingHttpExchange(exchange));
servletRequestContext.setServletPathMatch(info);
Executor executor = info.getServletChain().getExecutor();
if (executor == null) {
executor = servletContext.getDeployment().getExecutor();
}
if (exchange.isInIoThread() || executor != null) {
//either the exchange has not been dispatched yet, or we need to use a special executor
exchange.dispatch(executor, dispatchHandler);
} else {
dispatchRequest(exchange, servletRequestContext, info.getServletChain(), DispatcherType.REQUEST);
}
}
use of io.undertow.servlet.spec.HttpServletRequestImpl in project undertow by undertow-io.
the class ServletDebugPageHandler method handleRequest.
public static void handleRequest(HttpServerExchange exchange, final ServletRequestContext servletRequestContext, final Throwable exception) throws IOException {
HttpServletRequestImpl req = servletRequestContext.getOriginalRequest();
StringBuilder sb = new StringBuilder();
//todo: make this good
sb.append("<html><head><title>ERROR</title>");
sb.append(ERROR_CSS);
sb.append("</head><body><div class=\"header\"><div class=\"error-div\"></div><div class=\"error-text-div\">Error processing request</div></div>");
writeLabel(sb, "Context Path", req.getContextPath());
writeLabel(sb, "Servlet Path", req.getServletPath());
writeLabel(sb, "Path Info", req.getPathInfo());
writeLabel(sb, "Query String", req.getQueryString());
sb.append("<b>Stack Trace</b><br/>");
sb.append(escapeBodyText(exception.toString()));
sb.append("<br/>");
for (StackTraceElement element : exception.getStackTrace()) {
sb.append(escapeBodyText(element.toString()));
sb.append("<br/>");
}
sb.append("</body></html>");
servletRequestContext.getOriginalResponse().setContentType("text/html");
servletRequestContext.getOriginalResponse().setCharacterEncoding("UTF-8");
try {
ServletOutputStream out = servletRequestContext.getOriginalResponse().getOutputStream();
out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
out.close();
} catch (IllegalStateException e) {
PrintWriter writer = servletRequestContext.getOriginalResponse().getWriter();
writer.write(sb.toString());
writer.close();
}
}
use of io.undertow.servlet.spec.HttpServletRequestImpl in project undertow by undertow-io.
the class ServletBlockingHttpExchange method close.
@Override
public void close() throws IOException {
ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
if (!exchange.isComplete()) {
try {
HttpServletRequestImpl request = servletRequestContext.getOriginalRequest();
request.closeAndDrainRequest();
} finally {
HttpServletResponseImpl response = servletRequestContext.getOriginalResponse();
response.closeStreamAndWriter();
}
} else {
try {
HttpServletRequestImpl request = servletRequestContext.getOriginalRequest();
request.freeResources();
} finally {
HttpServletResponseImpl response = servletRequestContext.getOriginalResponse();
response.freeResources();
}
}
}
use of io.undertow.servlet.spec.HttpServletRequestImpl in project undertow by undertow-io.
the class ServletInitialHandler method dispatchMockRequest.
@Override
public void dispatchMockRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
final DefaultByteBufferPool bufferPool = new DefaultByteBufferPool(false, 1024, 0, 0);
MockServerConnection connection = new MockServerConnection(bufferPool);
HttpServerExchange exchange = new HttpServerExchange(connection);
exchange.setRequestScheme(request.getScheme());
exchange.setRequestMethod(new HttpString(request.getMethod()));
exchange.setProtocol(Protocols.HTTP_1_0);
exchange.setResolvedPath(request.getContextPath());
String relative;
if (request.getPathInfo() == null) {
relative = request.getServletPath();
} else {
relative = request.getServletPath() + request.getPathInfo();
}
exchange.setRelativePath(relative);
final ServletPathMatch info = paths.getServletHandlerByPath(request.getServletPath());
final HttpServletResponseImpl oResponse = new HttpServletResponseImpl(exchange, servletContext);
final HttpServletRequestImpl oRequest = new HttpServletRequestImpl(exchange, servletContext);
final ServletRequestContext servletRequestContext = new ServletRequestContext(servletContext.getDeployment(), oRequest, oResponse, info);
servletRequestContext.setServletRequest(request);
servletRequestContext.setServletResponse(response);
//set the max request size if applicable
if (info.getServletChain().getManagedServlet().getMaxRequestSize() > 0) {
exchange.setMaxEntitySize(info.getServletChain().getManagedServlet().getMaxRequestSize());
}
exchange.putAttachment(ServletRequestContext.ATTACHMENT_KEY, servletRequestContext);
exchange.startBlocking(new ServletBlockingHttpExchange(exchange));
servletRequestContext.setServletPathMatch(info);
try {
dispatchRequest(exchange, servletRequestContext, info.getServletChain(), DispatcherType.REQUEST);
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new ServletException(e);
}
}
Aggregations