Example usage for io.netty.handler.codec.http QueryStringDecoder parameters

List of usage examples for io.netty.handler.codec.http QueryStringDecoder parameters

Introduction

In this page you can find the example usage for io.netty.handler.codec.http QueryStringDecoder parameters.

Prototype

public Map<String, List<String>> parameters() 

Source Link

Document

Returns the decoded key-value parameter pairs of the URI.

Usage

From source file:com.netty.fileTest.http.upload.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);//  w w  w  .  ja v a 2 s  .co m
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        for (Entry<String, String> entry : request.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        if (request.getMethod().equals(HttpMethod.GET)) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So stop here
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
            return;
        }

        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}

From source file:com.nettyhttpserver.server.util.HttpRequestHandler.java

public static void handle(ChannelHandlerContext ctx, HttpRequest req, DefaultChannelGroup channels) {
    allChannels = channels;//from   ww w. j  a va2s. c  o m
    FullHttpResponse response = null;
    boolean keepAlive = isKeepAlive(req);
    String requestUri = req.getUri().toLowerCase();

    /*
     * Write data about request to database
     */
    ServerRequestDTO requestServiceDTO = new ServerRequestDTO();
    requestServiceDTO.setIP(((InetSocketAddress) ctx.channel().remoteAddress()).getHostString());
    requestServiceDTO.setLastTimestamp(new Timestamp(System.currentTimeMillis()).toString());
    serverRequestService.setServerRequest(requestServiceDTO);

    if (is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }

    /*
     * If request /hello
     */
    if (Requests.HELLO.toString().equalsIgnoreCase(requestUri)) {
        content = Unpooled
                .unreleasableBuffer(Unpooled.copiedBuffer("<h1>Hello World!</h1>", CharsetUtil.UTF_8));
        response = new DefaultFullHttpResponse(HTTP_1_1, OK, content.duplicate());
        /*
         * Create timer for /hello page.
         */
        timer.newTimeout(new ResponseTimerTask(ctx, response, keepAlive), 10, TimeUnit.SECONDS);

        writeToResponse(ctx, response, keepAlive);
        return;
    }

    /*
     * if request uri is /status
     */
    if (Requests.STATUS.toString().equalsIgnoreCase(requestUri)) {
        content = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(generateStatus(), CharsetUtil.UTF_8));
        response = new DefaultFullHttpResponse(HTTP_1_1, OK, content.duplicate());
        writeToResponse(ctx, response, keepAlive);
        return;
    }
    /*
     * If redirect
     */
    if (requestUri.matches(Requests.REDIRECT.toString())) {
        QueryStringDecoder qsd = new QueryStringDecoder(requestUri);
        List<String> redirectUrl = qsd.parameters().get("url");
        response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
        response.headers().set(LOCATION, redirectUrl);
        /*
         * Redirect database routine
         * Write url to database 
         */
        RedirectRequestDTO requestRedirectDTO = new RedirectRequestDTO();
        requestRedirectDTO.setUrl(redirectUrl.get(0));
        redirectRequestService.setRedirectRequest(requestRedirectDTO);
    } else {
        /*
         * If request URI is not handled by server.
         */
        response = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN);
    }
    writeToResponse(ctx, response, keepAlive);

}

From source file:com.phei.netty.nio.http.snoop.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaderUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);//from www . jav  a2  s  .  c  o m
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(request.headers().get(HOST, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Entry<CharSequence, CharSequence> h : headers) {
                CharSequence key = h.getKey();
                CharSequence value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (CharSequence name : trailer.trailingHeaders().names()) {
                    for (CharSequence value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:com.phei.netty.nio.http.upload.HttpUploadServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.uri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);/*  ww w . j  a va  2s.  co  m*/
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        for (Entry<CharSequence, CharSequence> entry : request.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().getAndConvert(HttpHeaderNames.COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = ServerCookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        if (request.method().equals(HttpMethod.GET)) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So stop here
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
            return;
        }
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        }

        readingChunks = HttpHeaderUtil.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}

From source file:com.rackspacecloud.blueflood.http.HttpRequestWithDecodedQueryParams.java

License:Apache License

public static HttpRequestWithDecodedQueryParams create(FullHttpRequest request) {
    final QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
    request.setUri(decoder.path());//w  ww . j  a v  a 2 s .c o m
    return new HttpRequestWithDecodedQueryParams(request, decoder.parameters());
}

From source file:com.sample.HelloWorldWithJavaScript.PingVerticle.java

License:Apache License

void startHttpServer() {
    final EventBus eb = vertx.eventBus();

    final Yoke app = new Yoke(this);
    app.secretSecurity("keyboard cat");

    final Middleware RequiredAuth = new Middleware() {
        @Override//from   www  .j  a v  a2s . c o  m
        public void handle(@NotNull final YokeRequest request, @NotNull final Handler<Object> next) {
            SessionObject session = request.get("session");

            if (session != null) {
                if (session.getString("id") != null) {
                    next.handle(null);
                    return;
                }
            }

            request.response().redirect("/examples");
        }
    };

    final Mac hmac = app.security().getMac("HmacSHA256");

    app.use(new Favicon()).store(new InMemorySessionStore()).engine(new StringPlaceholderEngine("webroot"))
            .use(new BodyParser()).use(new CookieParser(hmac)).use(new Session(hmac))
            .use(new Static("webroot/examples")).use(new Router().get("/examples", new Handler<YokeRequest>() {
                @Override
                public void handle(YokeRequest request) {

                    System.out.println("ex:" + Thread.currentThread().getId());
                    request.response().render("examples/login.shtml");
                }
            })

                    .get("/profile", RequiredAuth, new Middleware() {
                        @Override
                        public void handle(final YokeRequest request, Handler<Object> next) {
                            SessionObject session = request.get("session");
                            System.out.println("lo:" + Thread.currentThread().getId());

                            for (String key : session.getFieldNames()) {
                                request.put(key, session.getString(key));
                            }
                            request.response().render("examples/profile.shtml");

                        }
                    })

                    .get(".*", new Handler<YokeRequest>() {
                        public void handle(YokeRequest req) {
                            req.response().sendFile("webroot/" + req.path());
                        }
                    })

                    .post("/login", new Middleware() {
                        @Override
                        public void handle(final YokeRequest request, Handler<Object> next) {

                            System.out.println("lo:" + Thread.currentThread().getId());

                            final JsonObject session = request.createSession();

                            if (request.body() != null) {

                                eb.send("test.address", "This is a message", new Handler<Message<String>>() {
                                    public void handle(Message<String> message) {
                                        System.out.println("I received a reply " + message.body());

                                        QueryStringDecoder qsd = new QueryStringDecoder(
                                                request.body().toString(), false);
                                        Map<String, List<String>> params = qsd.parameters();

                                        System.out.println(request.body());

                                        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
                                            session.putString(entry.getKey().toString(),
                                                    entry.getValue().toString());
                                            request.put(entry.getKey().toString(), entry.getValue().toString());

                                        }
                                        request.response().render("examples/welcome.shtml");
                                    }
                                });
                            } else {
                                eb.send("test.address", "This is a message", new Handler<Message<String>>() {
                                    public void handle(Message<String> message) {
                                        System.out.println("I received a reply " + message.body());

                                        System.out.println(request.formAttributes());

                                        for (Map.Entry entry : request.formAttributes().entries()) {
                                            session.putString(entry.getKey().toString(),
                                                    entry.getValue().toString());
                                            request.put(entry.getKey().toString(), entry.getValue().toString());
                                        }

                                        request.put("tag",
                                                "<button class='ui active button' id='One'>${name}${name}</button>");
                                        request.response().render("examples/welcome.shtml");
                                    }
                                });
                            }
                        }
                    })

            ).listen(9090);
}

From source file:com.sample.HelloWorldWithUnity3d.PingVerticle.java

License:Apache License

void startHttpServer() {
    HttpServer server = vertx.createHttpServer();
    RouteMatcher routeMatcher = new RouteMatcher();

    routeMatcher.get("/", new Handler<HttpServerRequest>() {
        public void handle(HttpServerRequest req) {
            req.response().headers().set("Content-Type", "text/html; charset=UTF-8");
            System.out.println("Hello World!");

            TestReq fooBarMessage = new TestReq();
            fooBarMessage.key = 123456789;
            fooBarMessage.value = "abc";
            ByteArrayOutputStream outStream = new ByteArrayOutputStream(256);
            TProtocol tProtocol = new TBinaryProtocol(new TIOStreamTransport(null, outStream));

            try {
                fooBarMessage.write(tProtocol);
            } catch (TException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();//from  w  ww .ja va  2s.  c  om
            }

            byte[] content = outStream.toByteArray();

            tProtocol = new TBinaryProtocol(new TIOStreamTransport(new ByteArrayInputStream(content), null));
            TestReq fooBarMessage2 = new TestReq();
            try {
                fooBarMessage2.read(tProtocol);
            } catch (TException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                //  
                Session session = HibernateUtil.getCurrentSession();
                MyTestTable entity = (MyTestTable) session.get(MyTestTable.class, 1);
                entity.setName("bbb");
                Transaction tx = session.beginTransaction();
                session.update(entity);
                tx.commit();
                req.response().end("Hello World " + entity.getName());
            } catch (HibernateException e) {
                e.printStackTrace();
            } finally {
                //  
                HibernateUtil.closeSession();
            }
        }
    });

    routeMatcher.get("/login", new Handler<HttpServerRequest>() {
        public void handle(HttpServerRequest req) {

            try {

                String sid = GetSessionId(req);
                if (sid == null) {
                    req.response().headers().set("Set-Cookie",
                            ServerCookieEncoder.encode(new DefaultCookie("sessionId", generateSessionId())));
                }

                KeyPair keyPair = RSA.CreateKeyPair();

                PublicKey publicKey = keyPair.getPublic();
                PrivateKey privateKey = keyPair.getPrivate();

                RSAPublicKeySpec publicSpec = RSA.GetPublicKeySpec(keyPair);

                byte[] publicKeyModulus = publicSpec.getModulus().toByteArray();
                byte[] publicKeyExponent = publicSpec.getPublicExponent().toByteArray();

                // test
                byte[] encryptedData = RSA.Encrypt(publicKey, "haha!");
                String decryptedText = RSA.DecryptToString(privateKey, encryptedData);

                JsonObject json = new JsonObject();
                json.putBinary("publicKeyModulus", publicKeyModulus);
                json.putBinary("publicKeyExponent", publicKeyExponent);

                UserSession userSession = new UserSession();
                userSession.privateKey = privateKey;

                vertx.sharedData().getMap("1").put("userSession", userSession);
                req.response().end(json.toString());

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

    routeMatcher.post("/hello", new Handler<HttpServerRequest>() {
        public void handle(final HttpServerRequest req) {

            String sid = GetSessionId(req);

            req.bodyHandler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer buff) {
                    String contentType = req.headers().get("Content-Type");
                    if ("application/octet-stream".equals(contentType)) {
                        /*
                         QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
                         Map<String, List<String>> params = qsd.parameters();
                         System.out.println(params);
                         */

                        UserSession userSession = (UserSession) vertx.sharedData().getMap("1")
                                .get("userSession");

                        try {
                            String decryptedText = RSA.DecryptToString(userSession.privateKey, buff.getBytes());

                            JsonObject json = new JsonObject();
                            json.putString("decryptedText", decryptedText);

                            req.response().end(json.toString());
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    });

    routeMatcher.post("/name/:name", new Handler<HttpServerRequest>() {
        public void handle(final HttpServerRequest req) {

            req.bodyHandler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer buff) {

                    QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
                    Map<String, List<String>> params = qsd.parameters();
                    System.out.println(params);

                    req.response().end("Your name is " + req.params().get("name"));
                }
            });

        }
    });

    routeMatcher.put("/age/:age", new Handler<HttpServerRequest>() {
        public void handle(final HttpServerRequest req) {

            req.bodyHandler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer buff) {

                    QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
                    Map<String, List<String>> params = qsd.parameters();
                    System.out.println(params);

                    if (params.size() > 0)
                        req.response()
                                .end("Your age is " + req.params().get("age") + params.get("name").get(0));
                    else
                        req.response().end("Your age is " + req.params().get("age"));
                }
            });

        }
    });

    routeMatcher.get("/json", new Handler<HttpServerRequest>() {
        public void handle(HttpServerRequest req) {
            JsonObject obj = new JsonObject().putString("name", "chope");
            req.response().end(obj.encode());
        }
    });

    server.requestHandler(routeMatcher).listen(808, "localhost");
}

From source file:com.seagate.kinetic.simulator.io.provider.nio.http.HttpMessageServiceHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

    int contentLength = 0;

    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;

        logger.finest("protocol version: " + request.getProtocolVersion());

        logger.finest("host: " + getHost(request, "unknown"));

        logger.finest("REQUEST_URI: " + request.getUri());

        List<Map.Entry<String, String>> headers = request.headers().entries();

        String lenstr = request.headers().get(HttpHeaders.Names.CONTENT_LENGTH);
        contentLength = Integer.parseInt(lenstr);

        logger.finest("content length=" + contentLength);

        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> h : request.headers().entries()) {
                String key = h.getKey();
                String value = h.getValue();
                logger.finest("HEADER: " + key + " = " + value);
            }//from www . jav a2s.c  om
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    logger.finest("PARAM: " + key + " = " + val);
                }
            }

        }

    }

    // create extended builder
    ExtendedMessage.Builder extendedMessage = ExtendedMessage.newBuilder();

    if (msg instanceof HttpContent) {

        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {

            byte[] body = new byte[contentLength];
            content.getBytes(0, body);

            // read from serialized bytes
            extendedMessage.mergeFrom(body);
        }

        // build message
        ExtendedMessage extended = extendedMessage.build();

        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("received request: " + extended);
        }

        // create kinetic message for processing
        KineticMessage km = new KineticMessage();

        // set interface message
        km.setMessage(extended.getInterfaceMessage());

        // get command bytes
        ByteString commandBytes = extendedMessage.getInterfaceMessage().getCommandBytes();

        // build command
        Command.Builder commandBuilder = Command.newBuilder();

        try {
            commandBuilder.mergeFrom(commandBytes);
            km.setCommand(commandBuilder.build());
        } catch (InvalidProtocolBufferException e) {
            logger.log(Level.WARNING, e.getMessage(), e);
        }

        // set value
        if (extended.hasValue()) {
            km.setValue(extended.getValue().toByteArray());
        }

        // process request
        KineticMessage kmresp = this.lcservice.processRequest(km);

        // construct response message
        ExtendedMessage.Builder extendedResponse = ExtendedMessage.newBuilder();

        // set interface message
        extendedResponse.setInterfaceMessage((Message.Builder) kmresp.getMessage());

        // set value
        if (kmresp.getValue() != null) {
            extendedResponse.setValue(ByteString.copyFrom(kmresp.getValue()));
        }

        // get serialized value
        ByteBuf data = Unpooled.copiedBuffer(extendedResponse.build().toByteArray());

        FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                data);

        httpResponse.headers().set(CONTENT_TYPE, "application/octet-stream");

        httpResponse.headers().set(HttpHeaders.Names.CONTENT_ENCODING, HttpHeaders.Values.BINARY);

        httpResponse.headers().set(CONTENT_LENGTH, httpResponse.content().readableBytes());

        httpResponse.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);

        // send response message
        ctx.writeAndFlush(httpResponse);

        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("wrote and flushed response: " + kmresp);
        }
    }
}

From source file:com.shiyq.netty.http.HttpUploadServerHandler1.java

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.uri());
        if (!uri.getPath().startsWith("/upload")) {
            // Write Menu
            //writeMenu(ctx);
            responseContent.append("{code:-1,message:''}");
            writeResponse(ctx.channel());
            return;
        }//from  w w w.  ja  v  a  2s. com
        // new getMethod
        for (Entry<String, String> entry : request.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(HttpHeaderNames.COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = ServerCookieDecoder.STRICT.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                map.put(attr.getKey(), attrVal);
            }
        }

        // if GET Method: should not try to create a HttpPostRequestDecoder
        if (request.method().equals(HttpMethod.GET)) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So stop here
            responseContent.append("{code:-2,message:'??get'}");
            // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
            return;
        }
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append("{code:-3,message:'" + e1.getMessage() + "'}");
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        }

        readingChunks = HttpUtil.isTransferEncodingChunked(request);
        if (readingChunks) {
            // Chunk version
            //responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append("{code:-4,message:'" + e1.getMessage() + "'}");
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            //responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}

From source file:com.spotify.apollo.http.server.ApolloRequestHandlerTest.java

License:Apache License

private MockHttpServletRequest mockRequest(String method, String requestURI, Map<String, String> headers) {
    QueryStringDecoder decoder = new QueryStringDecoder(requestURI);

    final MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method, decoder.path());

    mockHttpServletRequest//from   w  w w.j a  v  a2s  .c  o  m
            .setParameters(decoder.parameters().entrySet().stream().collect(toMap(Map.Entry::getKey, e -> {
                List<String> value = e.getValue();
                return value.toArray(new String[value.size()]);
            })));
    mockHttpServletRequest.setQueryString(requestURI.replace(decoder.path() + "?", ""));

    headers.forEach(mockHttpServletRequest::addHeader);

    return mockHttpServletRequest;
}