protected void processRouteInterceptors(RouteContext routeContext) { if (interceptors.isEmpty()) { return; } List<RouteMatch> chain = new ArrayList<>(); for (RouteHandler interceptor : interceptors) { // create a route for interceptor Route route = new Route(routeContext.getRequestMethod(), routeContext.getRequestUri(), interceptor); route.setName(StringUtils.format("{}<{}>", Interceptor.class.getSimpleName(), route.getRouteHandler().getClass().getSimpleName())); route.bindAll(routeContext.getRoute().getAttributes()); // add route in chain RouteMatch match = new RouteMatch(route, null); chain.add(match); } // TODO DefaultRouteContext is hardcoded RouteContext context = new DefaultRouteContext(routeContext.getApplication(), routeContext.getRequest(), routeContext.getResponse(), chain); context.next(); }
protected String getSessionCsrfToken(RouteContext context) { return context.getSession(TOKEN); }
try { if (!canConsume(routeContext)) { routeContext.next(); int preInterceptStatus = routeContext.getResponse().getStatus(); processRouteInterceptors(routeContext); int postInterceptStatus = routeContext.getResponse().getStatus(); if (routeContext.getResponse().isCommitted()) { log.debug("Response committed by interceptor"); routeContext.next(); routeContext.getResponse().getStatus()); routeContext.getResponse().commit(); routeContext.next(); if (routeContext.getResponse().isCommitted()) { log.debug("Response committed in {}", LangUtils.toString(controllerMethod)); } else { routeContext.getResponse().notFound(); } else { routeContext.send(charSequence); } else if (result instanceof File) { routeContext.send(file); } else { routeContext.send(result);
private void checkForRecursion(RouteContext routeContext) { Integer depth = routeContext.removeLocal("__errorHandlerDepth"); if (depth == null) { depth = 0; } depth += 1; routeContext.setLocal("__errorHandlerDepth", depth); if (depth > 4) { throw new PippoRuntimeException("Recursion in error handler"); } }
/** * Removes a Flash instance from the session, binds it to the RouteContext, * and creates a new Flash instance. * * @param routeContext */ private void processFlash(RouteContext routeContext) { Flash flash = null; if (routeContext.hasSession()) { // get flash from session flash = routeContext.removeSession("flash"); // put an empty flash (outgoing flash) in session; defense against session.get("flash") routeContext.setSession("flash", new Flash()); } if (flash == null) { flash = new Flash(); } // make current flash available to templates routeContext.setLocal("flash", flash); }
/** * Specify the Response content-type by... * <ol> * <li>setting the first Produces content type</li> * <li>negotiating with the Request if multiple content-types are specified in Produces</li> * </ol> * * @param routeContext */ protected void specifyContentType(RouteContext routeContext) { if (!declaredProduces.isEmpty()) { // Specify first Produces content-type String defaultContentType = declaredProduces.get(0); routeContext.getResponse().contentType(defaultContentType); if (declaredProduces.size() > 1) { // negotiate content-type from Request Accept/Content-Type routeContext.negotiateContentType(); } } }
/** * Specify Response cache controls. * * @param routeContext */ protected void specifyCacheControls(RouteContext routeContext) { if (isNoCache) { log.debug("NoCache detected, response may not be cached"); routeContext.getResponse().noCache(); } }
protected void sendResource(URL resourceUrl, RouteContext routeContext) throws IOException { String filename = resourceUrl.getFile(); String mimeType = routeContext.getApplication().getMimeTypes().getContentType(filename); if (!StringUtils.isNullOrEmpty(mimeType)) { // stream the resource log.debug("Streaming as resource '{}'", resourceUrl); routeContext.getResponse().contentType(mimeType); routeContext.getResponse().ok().resource(resourceUrl.openStream()); } else { // stream the file log.debug("Streaming as file '{}'", resourceUrl); routeContext.getResponse().ok().file(filename, resourceUrl.openStream()); } }
String rawMethod = context.getRequest().getHttpServletRequest().getMethod(); if (HttpConstants.Method.POST.equals(rawMethod)) { String contentType = new ParameterValue(context.getRequest().getLocale(), context.getHeader("Content-Type")).toString("").toLowerCase(); contentType = StringUtils.getPrefix(contentType, ';').trim(); if (!guardedTypes.contains(contentType)) { log.debug("Ignoring '{}' request for {} '{}'", contentType, context.getRequestMethod(), context.getRequestUri()); return; String requestToken = context.getHeader("Csrf-Token"); if ("nocheck".equals(requestToken)) { log.debug("Ignoring 'nocheck' request for {} '{}'", context.getRequestMethod(), context.getRequestUri()); return; requestToken = context.getParameter(TOKEN).toString(); log.debug("Validated '{}' for {} '{}'", TOKEN, context.getRequestMethod(), context.getRequestUri()); context.setLocal(BINDING, sessionToken); String token = CryptoUtils.hmacDigest(sessionId, secretKey, algorithm); setSessionCsrfToken(context, token); log.debug("Generated '{}' for {} '{}'", TOKEN, context.getRequestMethod(), context.getRequestUri()); context.setLocal(BINDING, token); context.next();
checkForRecursion(routeContext); routeContext.status(statusCode); String contentType = routeContext.getResponse().getContentType(); if (!StringUtils.isNullOrEmpty(routeContext.getRequest().getAcceptType())) { String acceptType = routeContext.getRequest().getAcceptType(); if (acceptType.startsWith(HttpConstants.ContentType.TEXT_HTML) || acceptType.startsWith(HttpConstants.ContentType.TEXT_XHTML)) { routeContext.negotiateContentType(); contentType = routeContext.getResponse().getContentType(); Error error = prepareError(statusCode, routeContext); try { routeContext.getResponse().contentType(contentType).send(error); } catch (Exception e) { log.error("Unexpected error generating '{}' as '{}'", Error.class.getName(), contentType, e); routeContext.status(HttpConstants.StatusCode.INTERNAL_ERROR); routeContext.send(application.getMessages().get("pippo.statusCode500", routeContext));
@Override public void handle(RouteContext routeContext) { String language = enableQueryParameter ? routeContext.getParameter(PippoConstants.REQUEST_PARAMETER_LANG).toString() : null; if (StringUtils.isNullOrEmpty(language)) { language = languages.getLanguageOrDefault(routeContext); } Locale locale = languages.getLocaleOrDefault(language); routeContext.setLocal(PippoConstants.REQUEST_PARAMETER_LANG, language); routeContext.setLocal(PippoConstants.REQUEST_PARAMETER_LOCALE, locale); if (setCookie) { if (routeContext.getResponse().isCommitted()) { log.debug("LANG cookie NOT set, Response already committed!"); } else { languages.setLanguageCookie(language, routeContext); } } routeContext.next(); }
routeContext.getResponse().commit(); } else { if (statusCode == HttpConstants.StatusCode.NOT_FOUND) { content.append(routeContext.getRequestMethod()).append(' ').append(routeContext.getRequestUri()); content.append('\''); content.append('\n'); content.append("</body></html>"); routeContext.send(content); } else if (statusCode == HttpConstants.StatusCode.INTERNAL_ERROR) { StringBuilder content = new StringBuilder(); content.append("</body></html>"); routeContext.send(content);
Cookie cookie = routeContext.getResponse().getCookie(cookieName); if (cookie != null && !StringUtils.isNullOrEmpty(cookie.getValue())) { return getLanguageOrDefault(cookie.getValue()); cookie = routeContext.getRequest().getCookie(cookieName); if (cookie != null && !StringUtils.isNullOrEmpty(cookie.getValue())) { return getLanguageOrDefault(cookie.getValue()); if (routeContext.getResponse().getLocals().containsKey(PippoConstants.REQUEST_PARAMETER_LANG)) { String language = routeContext.getLocal(PippoConstants.REQUEST_PARAMETER_LANG); language = getLanguageOrDefault(language); return language; String acceptLanguage = routeContext.getHeader(HttpConstants.Header.ACCEPT_LANGUAGE); return getLanguageOrDefault(acceptLanguage);
protected void serveSpecification(RouteContext ctx, String specificationName) { String extension = Files.getFileExtension(specificationName); if (extension.isEmpty()) { // default to json specificationName += ".json"; } final String finalDocumentName = specificationName; final String finalExtension = Files.getFileExtension(finalDocumentName); String document = specifications.get(finalDocumentName.toLowerCase()); if (document == null) { ctx.getResponse().notFound(); } else { ctx.getResponse().ok(); httpCacheToolkit.addEtag(ctx, startTime); if ("json".equals(finalExtension)) { ctx.json(); } else if ("yaml".equals(finalExtension)) { ctx.yaml(); } else { ctx.text(); } if (HttpMethod.GET.equals(ctx.getRequestMethod())) { ctx.getResponse().send(document); } } }
private void initializeApplication() { // hook-up the Metrics dispatch listener MetricsDispatchListener metricsDispatchListener = new MetricsDispatchListener(metricRegistry); application.getRoutePreDispatchListeners().add(metricsDispatchListener); application.getRoutePostDispatchListeners().add(metricsDispatchListener); // set the RedirectException handler application.getErrorHandler().setExceptionHandler(RedirectException.class, (exception, ctx) -> { RedirectException redirectException = (RedirectException) exception; if (!Strings.isNullOrEmpty(redirectException.getSessionUrlAttribute())) { String requestUri = ctx.getRequest().getApplicationUriWithQuery(); ctx.setSession(redirectException.getSessionUrlAttribute(), requestUri); } ctx.redirect(redirectException.getPath()); }); // set the StatusCodeException handler application.getErrorHandler().setExceptionHandler(StatusCodeException.class, (exception, ctx) -> { StatusCodeException statusCodeException = (StatusCodeException) exception; ctx.setLocal("message", statusCodeException.getMessage()); application.getErrorHandler().handle(statusCodeException.getStatusCode(), ctx); }); }
String swaggerTemplate = settings.getString("swagger.ui.template", "swagger/index"); GET(swaggerPath, (ctx) -> { ctx.setLocal("apiTitle", settings.getString("swagger.api.title", settings.getApplicationName())); ctx.setLocal("bannerText", settings.getString("swagger.ui.bannerText", "swagger")); ctx.setLocal("swaggerPath", StringUtils.removeStart(swaggerPath, "/")); ctx.setLocal("hideApiKey", hideApiKey); ctx.setLocal("apiKeyName", apiKeyName); ctx.setLocal("apiKeyType", apiKeyType); Account session = ctx.getSession(AuthConstants.ACCOUNT_ATTRIBUTE); Account local = ctx.getLocal(AuthConstants.ACCOUNT_ATTRIBUTE); Account account = Optional.fromNullable(session).or(Optional.fromNullable(local).or(Account.GUEST)); ctx.setLocal("apiKey", Optional.fromNullable(account.getToken()).or("")); ctx.render(swaggerTemplate); });
@Override public void handle(RouteContext context) { final Response response = context.getResponse(); response.header(HttpConstants.Header.ACCESS_CONTROL_ALLOW_ORIGIN, allowOrigin); if (exposeHeaders != null) { response.header(HttpConstants.Header.ACCESS_CONTROL_EXPOSE_HEADERS, exposeHeaders); } if (maxAge != -1) { response.header(HttpConstants.Header.ACCESS_CONTROL_MAX_AGE, "" + maxAge); } // According to the documentation only if true is what needs to be set // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials#Directives if (allowCredentials) { response.header(HttpConstants.Header.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } if (allowMethods != null) { response.header(HttpConstants.Header.ACCESS_CONTROL_ALLOW_METHODS, allowMethods); } if (allowHeaders != null) { response.header(HttpConstants.Header.ACCESS_CONTROL_ALLOW_HEADERS, allowHeaders); } if (context.getRequestMethod().equals("OPTIONS")) { response.accepted(); return; } context.next(); }
public static Request get() { RouteContext routeContext = RouteDispatcher.getRouteContext(); return (routeContext != null) ? routeContext.getRequest() : null; }
if (file.exists()) { if (file.isFile()) { routeContext.getResponse().contentLength(file.length()); URL url = requestedPath.toUri().toURL(); switch (routeContext.getRequestMethod()) { case HttpConstants.Method.HEAD: setResponseHeaders(url, routeContext); routeContext.getResponse().commit(); break; case HttpConstants.Method.GET: default: log.warn("Unsupported request method {} for {}", routeContext.getRequestMethod(), routeContext.getRequestUri()); log.warn("{} not found for request path {}", requestedPath, routeContext.getRequestUri());
protected void streamResource(URL resourceUrl, RouteContext routeContext) { try { setResponseHeaders(resourceUrl, routeContext); if (routeContext.getResponse().getStatus() == HttpConstants.StatusCode.NOT_MODIFIED) { // do not stream anything out, simply return 304 routeContext.getResponse().commit(); } else { sendResource(resourceUrl, routeContext); } } catch (IOException e) { String message = e.getMessage(); if (!StringUtils.isNullOrEmpty(message)) { log.warn("Error sending resource {} to {}: {}", resourceUrl, routeContext.getRequest().getClientIp(), message); } else { throw new PippoRuntimeException(e, "Failed to stream resource {}", resourceUrl); } } catch (Exception e) { throw new PippoRuntimeException(e, "Failed to stream resource {}", resourceUrl); } }