Search in sources :

Example 16 with QueryStringDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.QueryStringDecoder in project vertx-web by vert-x3.

the class BaseValidationHandler method validateCookieParams.

private Map<String, RequestParameter> validateCookieParams(RoutingContext routingContext) throws ValidationException {
    // Validation process validate only params that are registered in the validation -> extra params are allowed
    if (!routingContext.request().headers().contains("Cookie"))
        return null;
    // Some hack to reuse this object
    QueryStringDecoder decoder = new QueryStringDecoder("/?" + routingContext.request().getHeader("Cookie"));
    Map<String, List<String>> cookies = new HashMap<>();
    for (Map.Entry<String, List<String>> e : decoder.parameters().entrySet()) {
        String key = e.getKey().trim();
        if (cookies.containsKey(key))
            cookies.get(key).addAll(e.getValue());
        else
            cookies.put(key, e.getValue());
    }
    Map<String, RequestParameter> parsedParams = new HashMap<>();
    for (ParameterValidationRule rule : cookieParamsRules.values()) {
        String name = rule.getName().trim();
        if (cookies.containsKey(name)) {
            List<String> p = cookies.get(name);
            if (p.size() != 0) {
                RequestParameter parsedParam = rule.validateArrayParam(p);
                if (parsedParams.containsKey(parsedParam.getName()))
                    parsedParam = parsedParam.merge(parsedParams.get(parsedParam.getName()));
                parsedParams.put(parsedParam.getName(), parsedParam);
            } else {
                throw ValidationException.ValidationExceptionFactory.generateNotMatchValidationException(name + " can't be empty");
            }
        } else {
            if (rule.parameterTypeValidator().getDefault() != null) {
                RequestParameter parsedParam = new RequestParameterImpl(name, rule.parameterTypeValidator().getDefault());
                if (parsedParams.containsKey(parsedParam.getName()))
                    parsedParam = parsedParam.merge(parsedParams.get(parsedParam.getName()));
                parsedParams.put(parsedParam.getName(), parsedParam);
            } else if (!rule.isOptional())
                throw ValidationException.ValidationExceptionFactory.generateNotFoundValidationException(name, ParameterLocation.COOKIE);
        }
    }
    return parsedParams;
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) RequestParameterImpl(io.vertx.ext.web.api.impl.RequestParameterImpl) RequestParameter(io.vertx.ext.web.api.RequestParameter) MultiMap(io.vertx.core.MultiMap)

Example 17 with QueryStringDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.QueryStringDecoder in project vertx-web by vert-x3.

the class RouteImpl method matches.

synchronized boolean matches(RoutingContextImplBase context, String mountPoint, boolean failure) {
    if (failure && !hasNextFailureHandler(context) || !failure && !hasNextContextHandler(context)) {
        return false;
    }
    if (!enabled) {
        return false;
    }
    HttpServerRequest request = context.request();
    if (!methods.isEmpty() && !methods.contains(request.method())) {
        return false;
    }
    if (path != null && pattern == null && !pathMatches(mountPoint, context)) {
        return false;
    }
    if (pattern != null) {
        String path = useNormalisedPath ? Utils.normalizePath(context.request().path()) : context.request().path();
        if (mountPoint != null) {
            path = path.substring(mountPoint.length());
        }
        Matcher m = pattern.matcher(path);
        if (m.matches()) {
            if (m.groupCount() > 0) {
                if (groups != null) {
                    // decode the path as it could contain escaped chars.
                    for (int i = 0; i < groups.size(); i++) {
                        final String k = groups.get(i);
                        String undecodedValue;
                        // 3. No group name
                        try {
                            undecodedValue = m.group("p" + i);
                        } catch (IllegalArgumentException e) {
                            try {
                                undecodedValue = m.group(k);
                            } catch (IllegalArgumentException e1) {
                                // Groups starts from 1 (0 group is total match)
                                undecodedValue = m.group(i + 1);
                            }
                        }
                        addPathParam(context, k, undecodedValue);
                    }
                } else {
                    // decode the path as it could contain escaped chars.
                    for (String namedGroup : namedGroupsInRegex) {
                        String namedGroupValue = m.group(namedGroup);
                        if (namedGroupValue != null) {
                            addPathParam(context, namedGroup, namedGroupValue);
                        }
                    }
                    for (int i = 0; i < m.groupCount(); i++) {
                        String group = m.group(i + 1);
                        if (group != null) {
                            final String k = "param" + i;
                            addPathParam(context, k, group);
                        }
                    }
                }
            }
        } else {
            return false;
        }
    }
    // Check if query params are already parsed
    if (context.queryParams().size() == 0) {
        // Decode query parameters and put inside context.queryParams
        Map<String, List<String>> decodedParams = new QueryStringDecoder(request.uri()).parameters();
        for (Map.Entry<String, List<String>> entry : decodedParams.entrySet()) context.queryParams().add(entry.getKey(), entry.getValue());
    }
    if (!consumes.isEmpty()) {
        // Can this route consume the specified content type
        MIMEHeader contentType = context.parsedHeaders().contentType();
        MIMEHeader consumal = contentType.findMatchedBy(consumes);
        if (consumal == null) {
            return false;
        }
    }
    List<MIMEHeader> acceptableTypes = context.parsedHeaders().accept();
    if (!produces.isEmpty() && !acceptableTypes.isEmpty()) {
        MIMEHeader selectedAccept = context.parsedHeaders().findBestUserAcceptedIn(acceptableTypes, produces);
        if (selectedAccept != null) {
            context.setAcceptableContentType(selectedAccept.rawValue());
            return true;
        }
        return false;
    }
    return true;
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) Matcher(java.util.regex.Matcher) HttpServerRequest(io.vertx.core.http.HttpServerRequest) MIMEHeader(io.vertx.ext.web.MIMEHeader)

Example 18 with QueryStringDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.QueryStringDecoder in project sidewinder by srotya.

the class HTTPDataPointDecoder method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {
        if (ResourceMonitor.getInstance().isReject()) {
            logger.warning("Write rejected, insufficient memory");
            if (writeResponse(request, ctx)) {
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest request = this.request = (HttpRequest) msg;
            if (HttpUtil.is100ContinueExpected(request)) {
                send100Continue(ctx);
            }
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
            path = queryStringDecoder.path();
            Map<String, List<String>> params = queryStringDecoder.parameters();
            if (!params.isEmpty()) {
                for (Entry<String, List<String>> p : params.entrySet()) {
                    String key = p.getKey();
                    if (key.equalsIgnoreCase("db")) {
                        dbName = p.getValue().get(0);
                    }
                }
            }
            if (path != null && path.contains("query")) {
                Gson gson = new Gson();
                JsonObject obj = new JsonObject();
                JsonArray ary = new JsonArray();
                ary.add(new JsonObject());
                obj.add("results", ary);
                responseString.append(gson.toJson(obj));
            }
        }
        if (msg instanceof HttpContent) {
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf byteBuf = httpContent.content();
            if (byteBuf.isReadable()) {
                requestBuffer.append(byteBuf.toString(CharsetUtil.UTF_8));
            }
            if (msg instanceof LastHttpContent) {
                if (dbName == null) {
                    responseString.append("Invalid database null");
                    logger.severe("Invalid database null");
                } else {
                    String payload = requestBuffer.toString();
                    logger.fine("Request:" + payload);
                    List<Point> dps = InfluxDecoder.pointsFromString(dbName, payload);
                    meter.inc(dps.size());
                    for (Point dp : dps) {
                        try {
                            engine.writeDataPoint(dp);
                            logger.fine("Accepted:" + dp + "\t" + new Date(dp.getTimestamp()));
                        } catch (IOException e) {
                            logger.fine("Dropped:" + dp + "\t" + e.getMessage());
                            responseString.append("Dropped:" + dp);
                        }
                    }
                }
                if (writeResponse(request, ctx)) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) Point(com.srotya.sidewinder.core.rpc.Point) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) Date(java.util.Date) IOException(java.io.IOException) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) JsonArray(com.google.gson.JsonArray) List(java.util.List) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 19 with QueryStringDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.QueryStringDecoder in project modules-extra by CubeEngine.

the class HttpRequestHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest message) throws Exception {
    InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
    this.log.info("{} connected...", inetSocketAddress.getAddress().getHostAddress());
    if (!this.server.isAddressAccepted(inetSocketAddress.getAddress())) {
        this.log.info("Access denied!");
        ctx.channel().close();
    }
    if (message.getDecoderResult().isFailure()) {
        this.error(ctx, RequestStatus.UNKNOWN_ERROR);
        this.log.info(message.getDecoderResult().cause(), "The decoder failed on this request...");
        return;
    }
    boolean authorized = this.server.isAuthorized(inetSocketAddress.getAddress());
    QueryStringDecoder qsDecoder = new QueryStringDecoder(message.getUri(), this.UTF8, true, 100);
    final Parameters params = new Parameters(qsDecoder.parameters(), cm.getProviders());
    User authUser = null;
    if (!authorized) {
        String user = params.get("user", String.class);
        String pass = params.get("pass", String.class);
        if (user == null || pass == null) {
            this.error(ctx, AUTHENTICATION_FAILURE, new ApiRequestException("Could not complete authentication", 200));
            return;
        }
        Optional<User> byName = Sponge.getServiceManager().provide(UserStorageService.class).get().get(user);
        if (!byName.isPresent()) {
            this.error(ctx, AUTHENTICATION_FAILURE, new ApiRequestException("Could not complete authentication", 200));
            return;
        }
        UUID id = byName.get().getUniqueId();
        // TODO make properly async
        CompletableFuture<Boolean> cf = am.isPasswordSet(id).thenCompose(isSet -> am.checkPassword(id, pass).thenApply(correctPassword -> !isSet || !correctPassword));
        Boolean authFailed = cf.get();
        if (authFailed) {
            this.error(ctx, AUTHENTICATION_FAILURE, new ApiRequestException("Could not complete authentication", 200));
            return;
        }
        authUser = byName.get();
    }
    String path = qsDecoder.path().trim();
    if (path.length() == 0 || "/".equals(path)) {
        this.error(ctx, RequestStatus.ROUTE_NOT_FOUND);
        return;
    }
    path = normalizePath(path);
    // is this request intended to initialize a websockets connection?
    if (WEBSOCKET_ROUTE.equals(path)) {
        WebSocketRequestHandler handler;
        if (!(ctx.pipeline().last() instanceof WebSocketRequestHandler)) {
            handler = new WebSocketRequestHandler(cm, server, objectMapper, authUser);
            ctx.pipeline().addLast("wsEncoder", new TextWebSocketFrameEncoder(objectMapper));
            ctx.pipeline().addLast("handler", handler);
        } else {
            handler = (WebSocketRequestHandler) ctx.pipeline().last();
        }
        this.log.info("received a websocket request...");
        handler.doHandshake(ctx, message);
        return;
    }
    this.handleHttpRequest(ctx, message, path, params, authUser);
}
Also used : EMPTY_BUFFER(io.netty.buffer.Unpooled.EMPTY_BUFFER) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Unpooled(io.netty.buffer.Unpooled) UserStorageService(org.spongepowered.api.service.user.UserStorageService) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ApiRequestException(org.cubeengine.module.apiserver.exception.ApiRequestException) CONTENT_TYPE(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE) CommandManager(org.cubeengine.libcube.service.command.CommandManager) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) HTTP_1_1(io.netty.handler.codec.http.HttpVersion.HTTP_1_1) JsonNode(com.fasterxml.jackson.databind.JsonNode) CLOSE(io.netty.channel.ChannelFutureListener.CLOSE) CLOSE_ON_FAILURE(io.netty.channel.ChannelFutureListener.CLOSE_ON_FAILURE) Log(org.cubeengine.logscribe.Log) User(org.spongepowered.api.entity.living.player.User) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Sponge(org.spongepowered.api.Sponge) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) WEBSOCKET_ROUTE(org.cubeengine.module.apiserver.WebSocketRequestHandler.WEBSOCKET_ROUTE) UUID(java.util.UUID) InetSocketAddress(java.net.InetSocketAddress) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Authorization(org.cubeengine.module.authorization.Authorization) AUTHENTICATION_FAILURE(org.cubeengine.module.apiserver.RequestStatus.AUTHENTICATION_FAILURE) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) Optional(java.util.Optional) User(org.spongepowered.api.entity.living.player.User) InetSocketAddress(java.net.InetSocketAddress) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) ApiRequestException(org.cubeengine.module.apiserver.exception.ApiRequestException) UUID(java.util.UUID)

Example 20 with QueryStringDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.QueryStringDecoder in project modules-extra by CubeEngine.

the class WebSocketRequestHandler method handleTextWebSocketFrame.

private void handleTextWebSocketFrame(final ChannelHandlerContext ctx, TextWebSocketFrame frame) {
    // TODO log exceptions!!!
    JsonNode jsonNode;
    try {
        jsonNode = objectMapper.readTree(frame.text());
    } catch (IOException e) {
        this.log.info("the frame data was no valid json!");
        return;
    }
    JsonNode action = jsonNode.get("action");
    JsonNode msgid = jsonNode.get("msgid");
    ObjectNode responseNode = objectMapper.createObjectNode();
    if (action == null) {
        responseNode.put("response", "No action");
    } else {
        JsonNode data = jsonNode.get("data");
        switch(action.asText()) {
            case "http":
                QueryStringDecoder qsDecoder = new QueryStringDecoder(HttpRequestHandler.normalizePath(data.get("uri").asText()), this.UTF8, true, 100);
                JsonNode reqMethod = data.get("method");
                RequestMethod method = reqMethod != null ? RequestMethod.getByName(reqMethod.asText()) : RequestMethod.GET;
                JsonNode reqdata = data.get("body");
                ApiHandler handler = this.server.getApiHandler(HttpRequestHandler.normalizePath(qsDecoder.path()));
                if (handler == null) {
                    responseNode.put("response", "Unknown route");
                    break;
                }
                Parameters params = new Parameters(qsDecoder.parameters(), cm.getProviders());
                ApiRequest request = new ApiRequest((InetSocketAddress) ctx.channel().remoteAddress(), ((InetSocketAddress) ctx.channel().localAddress()), method, params, EMPTY_HEADERS, reqdata, authUser);
                ApiResponse response = handler.execute(request);
                if (msgid != null) {
                    responseNode.set("response", objectMapper.valueToTree(response.getContent()));
                }
                break;
            case "subscribe":
                this.server.subscribe(data.asText().trim(), this);
                break;
            case "unsubscribe":
                this.server.unsubscribe(data.asText().trim(), this);
                break;
            default:
                responseNode.put("response", action.asText() + " -- " + data.asText());
        }
    }
    if (msgid != null && responseNode.elements().hasNext()) {
        responseNode.set("msgid", msgid);
        ctx.writeAndFlush(responseNode);
    }
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) InetSocketAddress(java.net.InetSocketAddress) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException)

Aggregations

QueryStringDecoder (io.netty.handler.codec.http.QueryStringDecoder)69 List (java.util.List)29 Test (org.junit.Test)15 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)14 Map (java.util.Map)10 HashMap (java.util.HashMap)9 IOException (java.io.IOException)8 URI (java.net.URI)7 ByteBuf (io.netty.buffer.ByteBuf)6 HttpContent (io.netty.handler.codec.http.HttpContent)6 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)6 HttpPostRequestDecoder (io.netty.handler.codec.http.multipart.HttpPostRequestDecoder)6 ArrayList (java.util.ArrayList)6 HttpMethod (io.netty.handler.codec.http.HttpMethod)5 HttpRequest (io.netty.handler.codec.http.HttpRequest)5 DeviceSession (org.traccar.DeviceSession)5 Position (org.traccar.model.Position)5 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)4 Channel (io.netty.channel.Channel)3 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)3