Search in sources :

Example 41 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest 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 42 with FullHttpRequest

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

the class WebSocketRequestHandler method doHandshake.

public void doHandshake(ChannelHandlerContext ctx, FullHttpRequest message) {
    WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory("ws://" + message.headers().get(HOST) + "/" + WEBSOCKET_ROUTE, null, false);
    this.handshaker = handshakerFactory.newHandshaker(message);
    if (handshaker == null) {
        this.log.info("client is incompatible!");
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        return;
    }
    this.log.debug("handshaking now...");
    this.handshaker.handshake(ctx.channel(), message).addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            log.debug("Success!");
        } else {
            log.debug("Failed!");
        }
    });
}
Also used : WebSocketServerHandshakerFactory(io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) User(org.spongepowered.api.entity.living.player.User) EMPTY_HEADERS(io.netty.handler.codec.http.HttpHeaders.EMPTY_HEADERS) HOST(io.netty.handler.codec.http.HttpHeaders.Names.HOST) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) InetSocketAddress(java.net.InetSocketAddress) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ChannelFuture(io.netty.channel.ChannelFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CommandManager(org.cubeengine.libcube.service.command.CommandManager) Charset(java.nio.charset.Charset) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) ChannelFutureListener(io.netty.channel.ChannelFutureListener) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) WebSocketServerHandshaker(io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker) JsonNode(com.fasterxml.jackson.databind.JsonNode) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) Log(org.cubeengine.logscribe.Log) WebSocketServerHandshakerFactory(io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory)

Example 43 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project xian by happyyangyuan.

the class ReqReceived method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest httpRequest = (FullHttpRequest) msg;
        String outerMsg = OuterMsgId.get(httpRequest);
        if (StringUtil.isEmpty(outerMsg)) {
            MsgIdHolder.init();
        } else {
            MsgIdHolder.set(outerMsg);
            LOG.info("xian独立节点传入了msgId=" + outerMsg);
        }
        String $ip = httpRequest.headers().get("X-Real-IP");
        if (StringUtil.isEmpty($ip)) {
            InetSocketAddress address = (InetSocketAddress) (ctx.channel().remoteAddress());
            $ip = address.getAddress().getHostAddress();
        }
        LOG.info(String.format("收到来自%s的FullHttpRequest \r\n %s!", $ip, msg));
        ctx.fireChannelRead(msg);
    } else {
        LOG.info("收到chucked http message...直接忽略,等待组装完毕");
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) InetSocketAddress(java.net.InetSocketAddress)

Example 44 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project xian by happyyangyuan.

the class RequestDecoderAux method decode.

@Override
protected void decode(ChannelHandlerContext ctx, FullHttpRequest msg, List<Object> out) throws Exception {
    LOG.debug("    httpRequest  ---->   UnitRequest Pojo");
    /*if (!HttpMethod.POST.equals(msg.method())) {
            throw new BadRequestException(new IllegalArgumentException("拒绝非POST请求!"));
        }*/
    DecoderResult result = msg.decoderResult();
    if (!result.isSuccess()) {
        throw new BadRequestException(result.cause());
    }
    updateLongConnectionStatus(msg, ctx);
    Request request = new Request(msg, MsgIdHolder.get());
    offerReqQueue(ctx, request);
    out.add(request);
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) Request(info.xiancloud.nettyhttpserver.http.bean.Request) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DecoderResult(io.netty.handler.codec.DecoderResult) BadRequestException(info.xiancloud.nettyhttpserver.http.bean.BadRequestException)

Example 45 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project scalecube by scalecube.

the class CorsHeadersHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof FullHttpRequest)) {
        super.channelRead(ctx, msg);
        return;
    }
    FullHttpRequest request = (FullHttpRequest) msg;
    if (!(HttpMethod.OPTIONS.equals(request.method()))) {
        super.channelRead(ctx, msg);
        return;
    }
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, config.getAccessControlAllowOrigin());
    response.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, config.getAccessControlAllowMethods());
    String accessControlRequestHeaders = request.headers().get(HttpHeaderNames.ACCESS_CONTROL_REQUEST_HEADERS);
    if (accessControlRequestHeaders != null) {
        response.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, accessControlRequestHeaders);
    }
    response.headers().add(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, config.getAccessControlMaxAge());
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
    ctx.writeAndFlush(response);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Aggregations

FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)287 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)180 Test (org.junit.jupiter.api.Test)74 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)69 Test (org.junit.Test)64 ByteBuf (io.netty.buffer.ByteBuf)54 HttpResponse (io.netty.handler.codec.http.HttpResponse)49 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)43 URI (java.net.URI)35 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)31 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)30 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)30 AsciiString (io.netty.util.AsciiString)25 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)23 Map (java.util.Map)22 ChannelPromise (io.netty.channel.ChannelPromise)21 HttpMethod (io.netty.handler.codec.http.HttpMethod)20 IOException (java.io.IOException)19 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)18 ResponseParts (com.github.ambry.rest.NettyClient.ResponseParts)16