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;
}
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;
}
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();
}
}
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);
}
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);
}
}
Aggregations