use of org.eclipse.jetty.server.Request in project httpx by EricEdens.
the class JettyPathTest method testParameterDecoding.
@Test
public void testParameterDecoding() throws Exception {
Server server = run(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print(request.getParameter("hi"));
baseRequest.setHandled(true);
}
});
try {
for (char c = 0; c < 1024; c++) {
String queryParam = String.valueOf(c);
String url = Url.httpBuilder("localhost", "/").port(8080).addQueryParam("hi", queryParam).toString();
try (InputStream stream = new URL(url).openStream()) {
byte[] bytes = ByteStreams.toByteArray(stream);
assertEquals("char c = " + c, queryParam, new String(bytes));
}
}
} finally {
server.stop();
}
}
use of org.eclipse.jetty.server.Request in project jersey by jersey.
the class JettyHttpContainer method handle.
@Override
public void handle(final String target, final Request request, final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException, ServletException {
final Response response = Response.getResponse(httpServletResponse);
final ResponseWriter responseWriter = new ResponseWriter(request, response, configSetStatusOverSendError);
final URI baseUri = getBaseUri(request);
final URI requestUri = getRequestUri(request, baseUri);
try {
final ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri, request.getMethod(), getSecurityContext(request), new MapPropertiesDelegate());
requestContext.setEntityStream(request.getInputStream());
final Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
final String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
requestContext.headers(headerName, headerValue == null ? "" : headerValue);
}
requestContext.setWriter(responseWriter);
requestContext.setRequestScopedInitializer(injectionManager -> {
injectionManager.<Ref<Request>>getInstance(REQUEST_TYPE).set(request);
injectionManager.<Ref<Response>>getInstance(RESPONSE_TYPE).set(response);
});
// Mark the request as handled before generating the body of the response
request.setHandled(true);
appHandler.handle(requestContext);
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
use of org.eclipse.jetty.server.Request in project blade by biezhi.
the class FormAuthenticator method validateRequest.
/* ------------------------------------------------------------ */
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
Request base_request = Request.getBaseRequest(request);
Response base_response = base_request.getResponse();
String uri = request.getRequestURI();
if (uri == null)
uri = URIUtil.SLASH;
mandatory |= isJSecurityCheck(uri);
if (!mandatory)
return new DeferredAuthentication(this);
if (isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(), request.getPathInfo())) && !DeferredAuthentication.isDeferred(response))
return new DeferredAuthentication(this);
HttpSession session = request.getSession(true);
try {
// Handle a request for authentication.
if (isJSecurityCheck(uri)) {
final String username = request.getParameter(__J_USERNAME);
final String password = request.getParameter(__J_PASSWORD);
UserIdentity user = login(username, password, request);
LOG.debug("jsecuritycheck {} {}", username, user);
session = request.getSession(true);
if (user != null) {
// Redirect to original request
String nuri;
FormAuthentication form_auth;
synchronized (session) {
nuri = (String) session.getAttribute(__J_URI);
if (nuri == null || nuri.length() == 0) {
nuri = request.getContextPath();
if (nuri.length() == 0)
nuri = URIUtil.SLASH;
}
form_auth = new FormAuthentication(getAuthMethod(), user);
}
LOG.debug("authenticated {}->{}", form_auth, nuri);
response.setContentLength(0);
int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
base_response.sendRedirect(redirectCode, response.encodeRedirectURL(nuri));
return form_auth;
}
// not authenticated
if (LOG.isDebugEnabled())
LOG.debug("Form authentication FAILED for " + StringUtil.printable(username));
if (_formErrorPage == null) {
LOG.debug("auth failed {}->403", username);
if (response != null)
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} else if (_dispatch) {
LOG.debug("auth failed {}=={}", username, _formErrorPage);
RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage);
response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
} else {
LOG.debug("auth failed {}->{}", username, _formErrorPage);
int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)));
}
return Authentication.SEND_FAILURE;
}
// Look for cached authentication
Authentication authentication = (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
if (authentication != null) {
// Has authentication been revoked?
if (authentication instanceof User && _loginService != null && !_loginService.validate(((User) authentication).getUserIdentity())) {
LOG.debug("auth revoked {}", authentication);
session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
} else {
synchronized (session) {
String j_uri = (String) session.getAttribute(__J_URI);
if (j_uri != null) {
//check if the request is for the same url as the original and restore
//params if it was a post
LOG.debug("auth retry {}->{}", authentication, j_uri);
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
if (j_uri.equals(buf.toString())) {
MultiMap<String> j_post = (MultiMap<String>) session.getAttribute(__J_POST);
if (j_post != null) {
LOG.debug("auth rePOST {}->{}", authentication, j_uri);
base_request.setContentParameters(j_post);
}
session.removeAttribute(__J_URI);
session.removeAttribute(__J_METHOD);
session.removeAttribute(__J_POST);
}
}
}
LOG.debug("auth {}", authentication);
return authentication;
}
}
// if we can't send challenge
if (DeferredAuthentication.isDeferred(response)) {
LOG.debug("auth deferred {}", session.getId());
return Authentication.UNAUTHENTICATED;
}
// remember the current URI
synchronized (session) {
// But only if it is not set already, or we save every uri that leads to a login form redirect
if (session.getAttribute(__J_URI) == null || _alwaysSaveUri) {
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
session.setAttribute(__J_URI, buf.toString());
session.setAttribute(__J_METHOD, request.getMethod());
if (MimeTypes.Type.FORM_ENCODED.is(req.getContentType()) && HttpMethod.POST.is(request.getMethod())) {
MultiMap<String> formParameters = new MultiMap<>();
base_request.extractFormParameters(formParameters);
session.setAttribute(__J_POST, formParameters);
}
}
}
// send the the challenge
if (_dispatch) {
LOG.debug("challenge {}=={}", session.getId(), _formLoginPage);
RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage);
response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
} else {
LOG.debug("challenge {}->{}", session.getId(), _formLoginPage);
int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formLoginPage)));
}
return Authentication.SEND_CONTINUE;
} catch (IOException | ServletException e) {
throw new ServerAuthException(e);
}
}
use of org.eclipse.jetty.server.Request in project blade by biezhi.
the class FormAuthenticator method prepareRequest.
/* ------------------------------------------------------------ */
@Override
public void prepareRequest(ServletRequest request) {
//if this is a request resulting from a redirect after auth is complete
//(ie its from a redirect to the original request uri) then due to
//browser handling of 302 redirects, the method may not be the same as
//that of the original request. Replace the method and original post
//params (if it was a post).
//
//See Servlet Spec 3.1 sec 13.6.3
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession session = httpRequest.getSession(false);
if (session == null || session.getAttribute(SessionAuthentication.__J_AUTHENTICATED) == null)
//not authenticated yet
return;
String juri = (String) session.getAttribute(__J_URI);
if (juri == null || juri.length() == 0)
//no original uri saved
return;
String method = (String) session.getAttribute(__J_METHOD);
if (method == null || method.length() == 0)
//didn't save original request method
return;
StringBuffer buf = httpRequest.getRequestURL();
if (httpRequest.getQueryString() != null)
buf.append("?").append(httpRequest.getQueryString());
if (!juri.equals(buf.toString()))
//this request is not for the same url as the original
return;
//restore the original request's method on this request
if (LOG.isDebugEnabled())
LOG.debug("Restoring original method {} for {} with method {}", method, juri, httpRequest.getMethod());
Request base_request = Request.getBaseRequest(request);
base_request.setMethod(method);
}
use of org.eclipse.jetty.server.Request in project camel by apache.
the class JettyHttpComponent method createServer.
protected Server createServer() {
Server s = null;
ThreadPool tp = threadPool;
QueuedThreadPool qtp = null;
// configure thread pool if min/max given
if (minThreads != null || maxThreads != null) {
if (getThreadPool() != null) {
throw new IllegalArgumentException("You cannot configure both minThreads/maxThreads and a custom threadPool on JettyHttpComponent: " + this);
}
qtp = new QueuedThreadPool();
if (minThreads != null) {
qtp.setMinThreads(minThreads.intValue());
}
if (maxThreads != null) {
qtp.setMaxThreads(maxThreads.intValue());
}
tp = qtp;
}
if (tp != null) {
try {
if (!Server.getVersion().startsWith("8")) {
s = Server.class.getConstructor(ThreadPool.class).newInstance(tp);
} else {
s = new Server();
if (isEnableJmx()) {
enableJmx(s);
}
Server.class.getMethod("setThreadPool", ThreadPool.class).invoke(s, tp);
}
} catch (Exception e) {
//ignore
}
}
if (s == null) {
s = new Server();
}
if (qtp != null) {
// let the thread names indicate they are from the server
qtp.setName("CamelJettyServer(" + ObjectHelper.getIdentityHashCode(s) + ")");
try {
qtp.start();
} catch (Exception e) {
throw new RuntimeCamelException("Error starting JettyServer thread pool: " + qtp, e);
}
}
ContextHandlerCollection collection = new ContextHandlerCollection();
s.setHandler(collection);
// setup the error handler if it set to Jetty component
if (getErrorHandler() != null) {
s.addBean(getErrorHandler());
} else if (!Server.getVersion().startsWith("8")) {
//need an error handler that won't leak information about the exception
//back to the client.
ErrorHandler eh = new ErrorHandler() {
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
String msg = HttpStatus.getMessage(response.getStatus());
request.setAttribute(RequestDispatcher.ERROR_MESSAGE, msg);
if (response instanceof Response) {
//need to use the deprecated method to support compiling with Jetty 8
((Response) response).setStatus(response.getStatus(), msg);
}
super.handle(target, baseRequest, request, response);
}
protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) throws IOException {
super.writeErrorPage(request, writer, code, message, false);
}
};
s.addBean(eh, false);
}
return s;
}
Aggregations