Search in sources :

Example 1 with RouterRequest

use of org.webpieces.ctx.api.RouterRequest in project webpieces by deanhiller.

the class RequestStreamWriter method handleCompleteRequest.

CompletableFuture<Void> handleCompleteRequest() {
    for (Http2Header h : requestHeaders.getHeaders()) {
        if (!headersSupported.contains(h.getKnownName()))
            log.error("This webserver has not thought about supporting header=" + h.getName() + " quite yet.  value=" + h.getValue() + " Please let us know and we can quickly add support");
    }
    RouterRequest routerRequest = new RouterRequest();
    routerRequest.orginalRequest = requestHeaders;
    //TODO(dhiller): figure out the firewall way to config when firewall terminates the ssl and we receive http
    //or the secure routes will not show up
    //We could add configuration to checking the terminating server socket locally as the firewall could
    //be defined to terminate ssl and drive to a specific port then.  the info is in stream.getSocket.getSvrSocketAddress
    routerRequest.isHttps = stream.getSocket().isHttps();
    String domain = requestHeaders.getAuthority();
    if (domain == null) {
        throw new IllegalArgumentException("Must contain Host(http1.1) or :authority(http2) header");
    }
    int port = 80;
    if (routerRequest.isHttps)
        port = 443;
    //if there is a firewall this port is wrong....and the above or below is right
    //int port = socketInfo.getLocalBoundAddress().getPort();
    int index2 = domain.indexOf(":");
    //TODO(dhiller): find when user is used and test implement
    if (index2 >= 0) {
        port = Integer.parseInt(domain.substring(index2 + 1));
        domain = domain.substring(0, index2);
    }
    String methodString = requestHeaders.getMethodString();
    HttpMethod method = HttpMethod.lookup(methodString);
    if (method == null)
        throw new UnsupportedOperationException("method not supported=" + methodString);
    parseCookies(requestHeaders, routerRequest);
    parseAcceptLang(requestHeaders, routerRequest);
    parseAccept(requestHeaders, routerRequest);
    routerRequest.encodings = headerParser.parseAcceptEncoding(requestHeaders);
    String referHeader = requestHeaders.getSingleHeaderValue(Http2HeaderName.REFERER);
    if (referHeader != null)
        routerRequest.referrer = referHeader;
    String xRequestedWithHeader = requestHeaders.getSingleHeaderValue(Http2HeaderName.X_REQUESTED_WITH);
    if ("XMLHttpRequest".equals(xRequestedWithHeader))
        routerRequest.isAjaxRequest = true;
    String fullPath = requestHeaders.getPath();
    if (fullPath == null)
        throw new IllegalArgumentException(":path header(http2) or path in request line(http1.1) is required");
    parseBody(requestHeaders, routerRequest);
    routerRequest.method = method;
    routerRequest.domain = domain;
    routerRequest.port = port;
    int index = fullPath.indexOf("?");
    if (index > 0) {
        routerRequest.relativePath = fullPath.substring(0, index);
        String postfix = fullPath.substring(index + 1);
        facade.urlEncodeParse(postfix, routerRequest);
    } else {
        routerRequest.queryParams = new HashMap<>();
        routerRequest.relativePath = fullPath;
    }
    //http1.1 so no...
    routerRequest.isSendAheadNextResponses = false;
    if (routerRequest.relativePath.contains("?"))
        throw new UnsupportedOperationException("not supported yet");
    ProxyResponse streamer = facade.createProxyResponse();
    try {
        streamer.init(routerRequest, requestHeaders, stream, facade.getBufferPool());
        return facade.incomingCompleteRequest(routerRequest, streamer);
    } catch (BadCookieException e) {
        log.warn("This occurs if secret key changed, or you booted another webapp with different key on same port or someone modified the cookie", e);
        streamer.sendRedirectAndClearCookie(routerRequest, e.getCookieName());
        return CompletableFuture.completedFuture(null);
    }
}
Also used : BadCookieException(org.webpieces.router.api.exceptions.BadCookieException) Http2Header(com.webpieces.http2parser.api.dto.lib.Http2Header) HttpMethod(org.webpieces.ctx.api.HttpMethod) RouterRequest(org.webpieces.ctx.api.RouterRequest)

Example 2 with RouterRequest

use of org.webpieces.ctx.api.RouterRequest in project webpieces by deanhiller.

the class ServiceProxy method parseBodyFromContentType.

private void parseBodyFromContentType(Route route, RequestContext ctx, BodyContentBinder bodyContentBinder) {
    RouterRequest req = ctx.getRequest();
    if (bodyContentBinder != null)
        //A route that defines the content gets to override the content type header so just return
        return;
    if (req.contentLengthHeaderValue == null)
        return;
    if (req.contentTypeHeaderValue == null) {
        log.info("Incoming content length was specified, but no contentType was(We will not parse the body).  req=" + req);
        return;
    }
    BodyParser parser = requestBodyParsers.lookup(req.contentTypeHeaderValue);
    if (parser == null) {
        log.error("Incoming content length was specified but content type was not 'application/x-www-form-urlencoded'(We will not parse body).  req=" + req);
        return;
    }
    DataWrapper body = req.body;
    Charset encoding = config.getDefaultFormAcceptEncoding();
    parser.parse(body, req, encoding);
    if (config.isTokenCheckOn() && route.isCheckSecureToken()) {
        String token = ctx.getSession().get(SessionImpl.SECURE_TOKEN_KEY);
        List<String> formToken = req.multiPartFields.get(RequestContext.SECURE_TOKEN_FORM_NAME);
        if (formToken == null)
            throw new BadRequestException("missing form token(or route added without setting checkToken variable to false)" + "...someone posting form without getting it first(hacker or otherwise) OR " + "you are not using the #{form}# tag or the #{secureToken}# tag to secure your forms");
        else if (!token.equals(formToken.get(0)))
            throw new BadRequestException("bad form token...someone posting form with invalid token(hacker or otherwise)");
    }
}
Also used : DataWrapper(org.webpieces.data.api.DataWrapper) BodyParser(org.webpieces.router.impl.body.BodyParser) Charset(java.nio.charset.Charset) BadRequestException(org.webpieces.router.api.exceptions.BadRequestException) RouterRequest(org.webpieces.ctx.api.RouterRequest)

Example 3 with RouterRequest

use of org.webpieces.ctx.api.RouterRequest in project webpieces by deanhiller.

the class ResponseProcessor method createRenderResponse.

public CompletableFuture<Void> createRenderResponse(RenderImpl controllerResponse) {
    if (responseSent)
        throw new IllegalStateException("You already sent a response.  do not call Actions.redirect or Actions.render more than once");
    responseSent = true;
    RouterRequest request = ctx.getRequest();
    Method method = matchedMeta.getMethod();
    //not broken)
    if (matchedMeta.getRoute().getRouteType() == RouteType.HTML && HttpMethod.POST == request.method) {
        throw new IllegalReturnValueException("Controller method='" + method + "' MUST follow the PRG " + "pattern(https://en.wikipedia.org/wiki/Post/Redirect/Get) so " + "users don't have a poor experience using your website with the browser back button.  " + "This means on a POST request, you cannot return RenderHtml object and must return Redirects");
    }
    String controllerName = matchedMeta.getControllerInstance().getClass().getName();
    String methodName = matchedMeta.getMethod().getName();
    String relativeOrAbsolutePath = controllerResponse.getRelativeOrAbsolutePath();
    if (relativeOrAbsolutePath == null) {
        relativeOrAbsolutePath = methodName + ".html";
    }
    Map<String, Object> pageArgs = controllerResponse.getPageArgs();
    // Add context as a page arg:
    pageArgs.put("_context", ctx);
    pageArgs.put("_session", ctx.getSession());
    pageArgs.put("_flash", ctx.getFlash());
    View view = new View(controllerName, methodName, relativeOrAbsolutePath);
    RenderResponse resp = new RenderResponse(view, pageArgs, matchedMeta.getRoute().getRouteType());
    return wrapFunctionInContext(() -> responseCb.sendRenderHtml(resp));
}
Also used : IllegalReturnValueException(org.webpieces.router.api.exceptions.IllegalReturnValueException) Method(java.lang.reflect.Method) HttpMethod(org.webpieces.ctx.api.HttpMethod) RenderResponse(org.webpieces.router.api.dto.RenderResponse) View(org.webpieces.router.api.dto.View) RouterRequest(org.webpieces.ctx.api.RouterRequest)

Example 4 with RouterRequest

use of org.webpieces.ctx.api.RouterRequest in project webpieces by deanhiller.

the class ResponseProcessor method createRawRedirect.

public CompletableFuture<Void> createRawRedirect(RawRedirect controllerResponse) {
    String url = controllerResponse.getUrl();
    if (url.startsWith("http")) {
        return wrapFunctionInContext(() -> responseCb.sendRedirect(new RedirectResponse(url)));
    }
    RouterRequest request = ctx.getRequest();
    RedirectResponse redirectResponse = new RedirectResponse(false, request.isHttps, request.domain, request.port, url);
    return wrapFunctionInContext(() -> responseCb.sendRedirect(redirectResponse));
}
Also used : RedirectResponse(org.webpieces.router.api.dto.RedirectResponse) RouterRequest(org.webpieces.ctx.api.RouterRequest)

Example 5 with RouterRequest

use of org.webpieces.ctx.api.RouterRequest in project webpieces by deanhiller.

the class ReverseRoutes method convertToUrl.

public String convertToUrl(String routeId, Map<String, String> args, boolean isValidating) {
    RouteMeta routeMeta = get(routeId);
    Route route = routeMeta.getRoute();
    String urlPath = route.getFullPath();
    List<String> pathParamNames = route.getPathParamNames();
    for (String param : pathParamNames) {
        String val = args.get(param);
        if (val == null) {
            String strArgs = "";
            for (Entry<String, String> entry : args.entrySet()) {
                boolean equals = entry.getKey().equals(param);
                strArgs = " ARG:'" + entry.getKey() + "'='" + entry.getValue() + "'   equals=" + equals + "\n";
            }
            throw new RouteNotFoundException("missing argument.  param=" + param + " is required" + " to exist(and cannot be null as well).  route=" + routeId + " args=" + strArgs);
        }
        String encodedVal = urlEncode(val);
        urlPath = urlPath.replace("{" + param + "}", encodedVal);
    }
    if (isValidating)
        return urlPath;
    RequestContext ctx = Current.getContext();
    RouterRequest request = ctx.getRequest();
    if (!route.isHttpsRoute() || request.isHttps)
        return urlPath;
    //we are rendering an http page with a link to https so need to do special magic
    String domain = request.domain;
    if (ports == null)
        ports = portConfigCallback.fetchPortConfig();
    int httpsPort = ports.getHttpsPort();
    return "https://" + domain + ":" + httpsPort + urlPath;
}
Also used : RequestContext(org.webpieces.ctx.api.RequestContext) RouteNotFoundException(org.webpieces.router.api.exceptions.RouteNotFoundException) RouterRequest(org.webpieces.ctx.api.RouterRequest)

Aggregations

RouterRequest (org.webpieces.ctx.api.RouterRequest)23 Test (org.junit.Test)8 RequestContext (org.webpieces.ctx.api.RequestContext)8 MockResponseStream (org.webpieces.router.api.mocks.MockResponseStream)8 RouterService (org.webpieces.router.api.RouterService)5 RedirectResponse (org.webpieces.router.api.dto.RedirectResponse)5 FlashImpl (org.webpieces.router.impl.ctx.FlashImpl)5 SessionImpl (org.webpieces.router.impl.ctx.SessionImpl)5 ValidationImpl (org.webpieces.router.impl.ctx.ValidationImpl)5 HttpMethod (org.webpieces.ctx.api.HttpMethod)4 Method (java.lang.reflect.Method)3 Annotation (java.lang.annotation.Annotation)2 Parameter (java.lang.reflect.Parameter)2 ArrayList (java.util.ArrayList)2 RenderResponse (org.webpieces.router.api.dto.RenderResponse)2 ErrorCommonTest (org.webpieces.router.api.error.ErrorCommonTest)2 IllegalReturnValueException (org.webpieces.router.api.exceptions.IllegalReturnValueException)2 Http2Header (com.webpieces.http2parser.api.dto.lib.Http2Header)1 Field (java.lang.reflect.Field)1 ParameterizedType (java.lang.reflect.ParameterizedType)1