Example usage for io.netty.handler.codec.http HttpMethod GET

List of usage examples for io.netty.handler.codec.http HttpMethod GET

Introduction

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

Prototype

HttpMethod GET

To view the source code for io.netty.handler.codec.http HttpMethod GET.

Click Source Link

Document

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.

Usage

From source file:org.jboss.aerogear.simplepush.server.netty.SimplePushSockJSServiceTest.java

License:Apache License

private FullHttpRequest websocketUpgradeRequest(final String path) {
    final FullHttpRequest req = new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, path);
    req.headers().set(Names.HOST, "server.test.com");
    req.headers().set(Names.UPGRADE, WEBSOCKET.toString());
    req.headers().set(Names.CONNECTION, "Upgrade");
    req.headers().set(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
    req.headers().set(Names.SEC_WEBSOCKET_ORIGIN, "http://test.com");
    req.headers().set(Names.SEC_WEBSOCKET_VERSION, "13");
    req.headers().set(Names.CONTENT_LENGTH, "0");
    return req;/*from   w  w  w  . ja va  2  s . c o m*/
}

From source file:org.kaaproject.kaa.server.transports.http.transport.netty.RequestDecoderTest.java

License:Apache License

@Test(expected = BadRequestException.class)
public void invalidMethodRequestTest() throws Exception {
    HttpObject request = createHttpRequestMock(HttpMethod.GET, true, HttpRequest.class);
    requestDecoder.channelRead0(channelHandlerContext, request);
}

From source file:org.knoxcraft.netty.server.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    try {/*from   w  w  w  . j av  a 2  s . com*/
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest fullRequest = (FullHttpRequest) msg;
            if (fullRequest.getUri().startsWith("/kctupload")) {

                if (fullRequest.getMethod().equals(HttpMethod.GET)) {
                    // HTTP Get request!
                    // Write the HTML page with the form
                    writeMenu(ctx);
                } else if (fullRequest.getMethod().equals(HttpMethod.POST)) {
                    /* 
                     * HTTP Post request! Handle the uploaded form
                     * HTTP parameters:
                            
                    /kctupload
                    username (should match player's Minecraft name)
                    language (java, python, etc)
                    jsonfile (a file upload, or empty)
                    sourcefile (a file upload, or empty)
                    jsontext (a JSON string, or empty)
                    sourcetext (code as a String, or empty)
                     */

                    String language = null;
                    String playerName = null;
                    String client = null;
                    String jsonText = null;
                    String sourceText = null;
                    Map<String, UploadedFile> files = new LinkedHashMap<String, UploadedFile>();

                    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(fullRequest);
                    try {
                        logger.trace("is multipart? " + decoder.isMultipart());
                        while (decoder.hasNext()) {
                            InterfaceHttpData data = decoder.next();
                            if (data == null)
                                continue;

                            try {
                                if (data.getHttpDataType() == HttpDataType.Attribute) {
                                    Attribute attribute = (Attribute) data;
                                    String name = attribute.getName();
                                    String value = attribute.getValue();
                                    logger.trace(String.format("http attribute: %s => %s", name, value));
                                    if (name.equals("language")) {
                                        language = value;
                                    } else if (name.equals("playerName")) {
                                        playerName = value;
                                    } else if (name.equals("client")) {
                                        client = value;
                                    } else if (name.equals("jsontext")) {
                                        jsonText = value;
                                    } else if (name.equals("sourcetext")) {
                                        sourceText = value;
                                    } else {
                                        logger.warn(String.format("Unknown kctupload attribute: %s => %s", name,
                                                value));
                                    }
                                } else if (data.getHttpDataType() == HttpDataType.FileUpload) {
                                    // Handle file upload
                                    // We may have json, source, or both
                                    FileUpload fileUpload = (FileUpload) data;
                                    logger.debug(String.format("http file upload name %s, filename: ",
                                            data.getName(), fileUpload.getFilename()));
                                    String filename = fileUpload.getFilename();
                                    ByteBuf buf = fileUpload.getByteBuf();
                                    String fileBody = new String(buf.array(), "UTF-8");
                                    files.put(data.getName(), new UploadedFile(filename, fileBody));
                                }
                            } finally {
                                data.release();
                            }
                        }
                    } finally {
                        if (decoder != null) {
                            // clean up resources
                            decoder.cleanFiles();
                            decoder.destroy();
                        }
                    }

                    /*
                     * Error checking here makes the most sense, since we can send back a reasonable error message
                     * to the uploading client at this point. Makes less sense to wait to compile.
                     * 
                     * Upload possibilities:
                     * 
                     * bluej: file1, file2, etc. All source code. Language should be set to Java.
                     * Convert to JSON, then to KCTScript. Signal an error if one happens.
                     * 
                     * web: jsontext and/or sourcetext. json-only is OK; source-only is OK if it's Java. 
                     * Cannot send source-only for non-Java languages, since we can't build them (yet).
                     * 
                     * anything else: convert to Json and hope for the best
                     */
                    try {
                        KCTUploadHook hook = new KCTUploadHook();
                        StringBuilder res = new StringBuilder();

                        if (playerName == null || playerName.equals("")) {
                            // XXX How do we know that the playerName is valid?
                            // TODO: authenticate against Mojang's server?
                            throw new TurtleException("You must specify your MineCraft player name!");
                        }

                        if (client == null) {
                            throw new TurtleException("Your uploading and submission system must specify "
                                    + "the type of client used for the upload (i.e. bluej, web, pykc, etc)");
                        }

                        hook.setPlayerName(playerName);
                        res.append(
                                String.format("Hello %s! Thanks for using KnoxCraft Turtles\n\n", playerName));

                        TurtleCompiler turtleCompiler = new TurtleCompiler(logger);
                        int success = 0;
                        int failure = 0;
                        if (client.equalsIgnoreCase("web") || client.equalsIgnoreCase("testclient")
                                || client.startsWith("pykc")) {
                            // WEB OR PYTHON UPLOAD
                            logger.trace("Upload from web");
                            // must have both Json and source, either in text area or as uploaded files
                            //XXX Conlfict of comments of the top and here??? What do we need both/ only JSon?
                            //Is there a want we want, thus forcing it
                            if (sourceText != null && jsonText != null) {
                                KCTScript script = turtleCompiler.parseFromJson(jsonText);
                                script.setLanguage(language);
                                script.setSourceCode(sourceText);
                                res.append(String.format(
                                        "Successfully uploaded KnoxCraft Turtle program "
                                                + "named %s, in programming language %s\n",
                                        script.getScriptName(), script.getLanguage()));
                                success++;
                                hook.addScript(script);
                            } else if (files.containsKey("jsonfile") && files.containsKey("sourcefile")) {
                                UploadedFile sourceUpload = files.get("sourcefile");
                                UploadedFile jsonUpload = files.get("jsonfile");
                                KCTScript script = turtleCompiler.parseFromJson(jsonUpload.body);
                                script.setLanguage(language);
                                script.setSourceCode(sourceUpload.body);
                                res.append(String.format(
                                        "Successfully uploaded KnoxCraft Turtle program "
                                                + "named %s, in programming language %s\n",
                                        script.getScriptName(), script.getLanguage()));
                                success++;
                                hook.addScript(script);
                            } else {
                                throw new TurtleException(
                                        "You must upload BOTH json and the corresponding source code "
                                                + " (either as files or pasted into the text areas)");
                            }
                        } else if ("bluej".equalsIgnoreCase(client)) {
                            // BLUEJ UPLOAD
                            logger.trace("Upload from bluej");
                            for (Entry<String, UploadedFile> entry : files.entrySet()) {
                                try {
                                    UploadedFile uploadedFile = entry.getValue();
                                    res.append(String.format("Trying to upload and compile file %s\n",
                                            uploadedFile.filename));
                                    logger.trace(String.format("Trying to upload and compile file %s\n",
                                            uploadedFile.filename));
                                    KCTScript script = turtleCompiler
                                            .compileJavaTurtleCode(uploadedFile.filename, uploadedFile.body);
                                    logger.trace("Returned KCTScript (it's JSON is): " + script.toJSONString());
                                    hook.addScript(script);
                                    res.append(String.format(
                                            "Successfully uploaded file %s and compiled KnoxCraft Turtle program "
                                                    + "named %s in programming language %s\n\n",
                                            uploadedFile.filename, script.getScriptName(),
                                            script.getLanguage()));
                                    success++;
                                } catch (TurtleCompilerException e) {
                                    logger.warn("Unable to compile Turtle code", e);
                                    res.append(String.format("%s\n\n", e.getMessage()));
                                    failure++;
                                } catch (TurtleException e) {
                                    logger.error("Error in compiling (possibly a server side error)", e);
                                    res.append(String.format("Unable to process Turtle code %s\n\n",
                                            e.getMessage()));
                                    failure++;
                                } catch (Exception e) {
                                    logger.error("Unexpected error compiling Turtle code to KCTScript", e);
                                    failure++;
                                    res.append(String.format("Failed to load script %s\n", entry.getKey()));
                                }
                            }
                        } else {
                            // UNKNOWN CLIENT UPLOAD
                            // TODO Unknown client; make a best effort to handle upload
                            res.append(String.format(
                                    "Unknown upload client: %s; making our best effort to handle the upload"));
                        }

                        res.append(String.format("\nSuccessfully uploaded %d KnoxCraft Turtles programs\n",
                                success));
                        if (failure > 0) {
                            res.append(String.format("\nFailed to upload %d KnoxCraft Turtles programs\n",
                                    failure));
                        }
                        Canary.hooks().callHook(hook);
                        writeResponse(ctx.channel(), fullRequest, res.toString(), client);
                    } catch (TurtleException e) {
                        // XXX can this still happen? Don't we catch all of these?
                        writeResponse(ctx.channel(), fullRequest, e.getMessage(), "error");
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("Internal Server Error: Channel error", e);
        throw e;
    }
}

From source file:org.mitre.svmp.webrtc.http.PeerConnectionServerHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    //System.out.println(msg.getClass().getName());

    DefaultFullHttpResponse response = null;

    if (msg instanceof HttpRequest) {

        // All HTTP messages used by the peerconnection_client:
        ///*from  w ww.j av  a  2s.c  o  m*/
        // "GET /sign_in?%s HTTP/1.0\r\n\r\n", client_name_.c_str());
        // "POST /message?peer_id=%i&to=%i HTTP/1.0\r\n"
        // "GET /sign_out?peer_id=%i HTTP/1.0\r\n\r\n", my_id_);
        // "GET /wait?peer_id=%i HTTP/1.0\r\n\r\n", my_id_);

        HttpRequest request = (HttpRequest) msg;

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

        HttpMethod method = request.getMethod();
        String uri = request.getUri();
        //        QueryStringDecoder queryDecoder = new QueryStringDecoder(uri);
        //        Map<String, List<String>> params = queryDecoder.parameters();

        System.out.println("Incoming HTTP request:\n" + method + " " + uri);

        if (method.equals(HttpMethod.GET)) {

            // Case: GET /sign_in?%s
            if (uri.startsWith("/sign_in")) {
                // should have a username parameter and it should be "fbstreamer"
                String username = uri.split("[?]")[1];

                // return a comma delimited list of name,peer_id,is_connected
                // where the first line is the info of the peer we're talking to
                // and all subsequent lines are the set of other connected peers

                // since fbstreamer on the HTTP side will always be the first peer to connect
                // lie about the other peer being there

                ByteBuf content = copiedBuffer(
                        username + "," + FBSTREAM_PEER_ID + ",1\n" + "svmpclient," + CLIENT_PEER_ID + ",1",
                        CharsetUtil.US_ASCII);
                response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, content);

                response.headers().set(CONTENT_TYPE, "text/plain");
                response.headers().set(CONNECTION, "close");
                response.headers().set(PRAGMA, FBSTREAM_PEER_ID);

                // do we have to set the content-length header ourselves?
                // if so, how do we calculate it?
            }

            // Case: GET /sign_out?peer_id=%i
            else if (uri.startsWith("/sign_out")) {
                // TODO might be worth checking that the peer_id is actually FBSTREAM_PEER_ID
                // doesn't really matter though

                response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
                response.headers().set(CONNECTION, "close");
                response.headers().set(CONTENT_LENGTH, 0);

                // create a BYE message, no other peers to notify
                // add it to the sendQueue
                // TODO
            }

            // Case: GET /wait?peer_id=%i
            else if (uri.startsWith("/wait")) {
                // pull something off receiveQueue
                SVMPProtocol.Request pbMsg = receiveQueue.take();

                // convert it to JSON
                String json = Translator.ProtobufToJSON(pbMsg.getWebrtcMsg());
                ByteBuf content = copiedBuffer(json, CharsetUtil.US_ASCII);

                System.out.println("JSON from client:\n" + json);

                // make HTTP response
                response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, content);
                response.headers().set(CONTENT_TYPE, "text/plain");

                // if it's a peer presence info message, set pragma to the client's ID
                // function handleServerNotification(data) {(String)
                //   trace("Server notification: " + data);
                //   var parsed = data.split(',');
                //   if (parseInt(parsed[2]) != 0)
                //   other_peers[parseInt(parsed[1])] = parsed[0];
                // }

                // shouldn't be any presence messages since we're hard coding
                // it above in the sign_in case

                // if it's a message from another peer, set pragma to that peer's ID
                response.headers().set(PRAGMA, CLIENT_PEER_ID);
                // peerconnection_server appears to set "Connection: close" for these
                response.headers().set(CONNECTION, "close");

                // send in HTTP response
                response = null;
            } else {
                // some other bad URL
                response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND);
            }

            // send response
            System.out.println("HTTP response:\n" + response.toString());
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);

        } else if (method.equals(HttpMethod.POST) && uri.startsWith("/message")) {
            // Case: POST /message?peer_id=%i&to=%i

            isProcessingPost = true;

        } else {
            // some other HTTP request we don't support
            // send an error or something
            response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);

            // send response
            System.out.println("HTTP response:\n" + response.toString());
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        }
    } else if (msg instanceof HttpContent && isProcessingPost) {
        // handle body of the POST /message

        // decode the JSON payload
        String content = ((HttpContent) msg).content().toString(CharsetUtil.UTF_8);
        System.out.println("JSON in from fbstream:\n" + content);

        // convert it to protobuf
        SVMPProtocol.Response.Builder pbResp = SVMPProtocol.Response.newBuilder();
        pbResp.setType(ResponseType.WEBRTC);
        pbResp.setWebrtcMsg(Translator.JSONToProtobuf(content));

        // add it to sendQueue
        sendQueue.add(pbResp.build());

        // generate appropriate HTTP response
        response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
        response.headers().set(CONNECTION, "close");

        // send response
        System.out.println("HTTP response:\n" + response.toString());
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);

        isProcessingPost = false;
    }
}

From source file:org.nosceon.titanite.ControllersTest.java

License:Apache License

@Test
public void test() {
    given().expect().statusCode(200).body(equalTo(HttpMethod.GET.name())).when().get(uri("/a"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.POST.name())).when().post(uri("/a"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.PUT.name())).when().put(uri("/a"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.DELETE.name())).when().delete(uri("/a"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.PATCH.name())).when().patch(uri("/a"));

    given().expect().statusCode(200).body(equalTo(HttpMethod.GET.name())).when().get(uri("/b"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.POST.name())).when().post(uri("/b"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.PUT.name())).when().put(uri("/b"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.DELETE.name())).when().delete(uri("/b"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.PATCH.name())).when().patch(uri("/b"));
}

From source file:org.nosceon.titanite.MethodsTest.java

License:Apache License

@Test
public void test() {
    given().expect().statusCode(200).body(equalTo(HttpMethod.GET.name())).when().get(uri("/resource"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.POST.name())).when().post(uri("/resource"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.PUT.name())).when().put(uri("/resource"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.DELETE.name())).when().delete(uri("/resource"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.PATCH.name())).when().patch(uri("/resource"));

    given().expect().statusCode(200).body(equalTo(HttpMethod.GET.name())).when().get(uri("/controller"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.POST.name())).when().post(uri("/controller"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.PUT.name())).when().put(uri("/controller"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.DELETE.name())).when().delete(uri("/controller"));
    given().expect().statusCode(200).body(equalTo(HttpMethod.PATCH.name())).when().patch(uri("/controller"));
}

From source file:org.nosceon.titanite.Router.java

License:Apache License

RoutingResult find(HttpMethod httpMethod, String path) {
    Method method = map(httpMethod);

    List<Route> candidates = this.routes.stream().filter(r -> r.pattern().matches(path)).collect(toList());

    if (candidates.isEmpty()) {
        return NOT_FOUND;
    } else {/*from  www . j a v  a2s .  com*/
        return candidates.stream().filter(route -> route.hasMethod(method)).findFirst().map(route -> {
            ParameterizedPattern.Matcher matcher = route.pattern().matcher(path);
            return Method.OPTIONS.equals(method)
                    ? new RoutingResult(matcher.parameters(), route.bodyParser(),
                            new CompositeHandler(allowedMethodsFilter(candidates), route.handler()))
                    : new RoutingResult(matcher.parameters(), route.bodyParser(), route.handler());
        }).orElseGet(() -> {
            if (Method.OPTIONS.equals(method)) {
                return new RoutingResult(emptyMap(), EmptyBodyParser::new, new CompositeHandler(
                        allowedMethodsFilter(candidates), req -> Response.ok().toFuture()));
            } else if (Method.HEAD.equals(method)) {
                return find(HttpMethod.GET, path);
            } else {
                return METHOD_NOT_ALLOWED;
            }
        });
    }

}

From source file:org.restexpress.pipeline.DefaultRequestHandlerTest.java

License:Apache License

private void sendGetEvent(String path) {
    try {//from w  ww  .j a v  a2s . c o m
        pl.fireChannelRead(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path));
    } catch (Throwable t) {
        System.out.println(t.getMessage());
    }
}

From source file:org.restexpress.pipeline.DefaultRequestHandlerTest.java

License:Apache License

private void sendGetEvent(String path, String body) {
    try {//from w ww  .jav  a2 s. com
        pl.fireChannelRead(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path,
                Unpooled.copiedBuffer(body, Charset.defaultCharset())));
    } catch (Throwable t) {
        System.out.println(t.getMessage());
    }
}

From source file:org.restexpress.pipeline.JsendWrappedResponseTest.java

License:Apache License

@Test
public void shouldWrapGetInJsendJson() {
    sendEvent(HttpMethod.GET, "/normal_get.json", "");
    assertEquals(1, observer.getReceivedCount());
    assertEquals(1, observer.getCompleteCount());
    assertEquals(1, observer.getSuccessCount());
    assertEquals(0, observer.getExceptionCount());
    //      System.out.println(httpResponse.toString());
    assertEquals("{\"code\":200,\"status\":\"success\",\"data\":\"Normal GET action\"}",
            httpResponse.toString());//from w w  w .j  av  a 2  s. c  o m
}