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

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

Introduction

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

Prototype

HttpMethod POST

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

Click Source Link

Document

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.

Usage

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:
        ///* w ww  .j  a va2s .  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.HttpServerHandler.java

License:Apache License

private BodyParser newBodyParser(RoutingResult routing, HttpRequest request) {
    HttpMethod method = request.getMethod();
    if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH)) {

        if (routing.bodyParser() != null) {
            BodyParser bp = routing.bodyParser().get();
            if (bp != null) {
                return bp;
            }/*w  w w .  ja v  a2 s.  c  o m*/
        }

        String contentType = request.headers().get(HttpHeaders.Names.CONTENT_TYPE);

        if (contentType != null) {
            String lowerCaseContentType = contentType.toLowerCase();
            boolean isURLEncoded = lowerCaseContentType
                    .startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
            boolean isMultiPart = lowerCaseContentType.startsWith(HttpHeaders.Values.MULTIPART_FORM_DATA);

            if (isMultiPart) {
                return new FormParamsBodyParser(maxMultipartRequestSize);
            }

            if (isURLEncoded) {
                return new FormParamsBodyParser(maxRequestSize);
            }
        }

        return new RawBodyParser(maxRequestSize);
    } else {
        return new EmptyBodyParser();
    }
}

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.pidome.server.system.network.http.HttpRequestHandler.java

/**
 * Process the request made for http2/*  w w  w  .  jav  a  2  s.co m*/
 *
 * @param chc The channel context.
 * @param request The url request.
 * @param writer The output writer of type HttpRequestWriterInterface.
 * @param streamId The stream Id in case of http2, when http1 leave null.
 */
protected static void processManagement(ChannelHandlerContext chc, FullHttpRequest request,
        HttpRequestWriterInterface writer, String streamId) {
    String plainIp = getPlainIp(chc.channel().remoteAddress());
    String localIp = getPlainIp(chc.channel().localAddress());
    int localPort = getPort(chc.channel().localAddress());
    try {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        String fileRequest = queryStringDecoder.path();

        if (fileRequest.equals("/")) {
            fileRequest = "/index.html";
        } else if (fileRequest.endsWith("/")) {
            fileRequest = fileRequest + "index.html";
        }

        String nakedfile = fileRequest.substring(1, fileRequest.lastIndexOf("."));
        String fileType = fileRequest.substring(fileRequest.lastIndexOf(".") + 1);

        String loginError = "";
        RemoteClientInterface client = null;
        RemoteClient remoteClient = null;

        WebRenderInterface renderClass = null;

        try {
            Set<Cookie> cookie = cookieParser(request);
            Map<RemoteClientInterface, RemoteClient> clientSet = getAuthorizedClient(request, plainIp,
                    (cookie.isEmpty() ? "" : ((Cookie) cookie.toArray()[0]).getValue()), fileRequest);
            client = clientSet.keySet().iterator().next();
            remoteClient = clientSet.get(client);
        } catch (Exception ex) {
            if (ex instanceof HttpClientNotAuthorizedException) {
                LOG.error("Not authorized at {}", plainIp, request.uri());
                loginError = "Not authorized or bad username/password";
            } else if (ex instanceof HttpClientLoggedInOnOtherLocationException) {
                LOG.error("Not authorized at {} (Logged in on other location: {}!)", plainIp, ex.getMessage());
                loginError = "Client seems to be already logged in on another location";
            } else {
                LOG.error("Not authorized at: {} (Cookie problem? ({}))", ex, ex.getMessage(), ex);
                loginError = "Problem getting authentication data, refer to log file";
            }
            if (!request.uri().equals("/jsonrpc.json")) {
                fileType = "xhtml";
                nakedfile = "login";
                fileRequest = "/login.xhtml";
            }
        }

        if (!fileType.isEmpty()) {
            switch (fileType) {
            case "xhtml":
            case "json":
            case "upload":
            case "xml":
            case "/":
                if (request.uri().startsWith("/jsonrpc.json")) {
                    renderClass = getJSONRPCRenderer(request);
                } else if (request.uri().startsWith("/xmlapi/")) {
                    /// This is a temp solution until the xml output has been transfered to the json rpc api.
                    Class classToLoad = Class.forName(
                            HttpServer.getXMLClassesRoot() + nakedfile.replace("xmlapi/", ".Webclient_"));
                    renderClass = (WebRenderInterface) classToLoad.getConstructor().newInstance();
                } else {
                    Class classToLoad = Class
                            .forName(HttpServer.getDocumentClassRoot() + nakedfile.replace("/", ".Webclient_"));
                    renderClass = (WebRenderInterface) classToLoad.getConstructor().newInstance();
                }
                renderClass.setHostData(localIp, localPort, plainIp);
                renderClass.setRequestData(queryStringDecoder.parameters());
                Map<String, String> postData = new HashMap<>();
                Map<String, byte[]> fileMap = new HashMap<>();
                if (request.method().equals(HttpMethod.POST)) {
                    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(
                            new DefaultHttpDataFactory(false), request);
                    decoder.setDiscardThreshold(0);
                    if (request instanceof HttpContent) {
                        HttpContent chunk = (HttpContent) request;
                        decoder.offer(chunk);
                        try {
                            while (decoder.hasNext()) {
                                InterfaceHttpData data = decoder.next();
                                if (data != null) {
                                    if (data.getHttpDataType()
                                            .equals(InterfaceHttpData.HttpDataType.Attribute)) {
                                        postData.put(data.getName(), ((HttpData) data).getString());
                                    } else if (data.getHttpDataType()
                                            .equals(InterfaceHttpData.HttpDataType.FileUpload)) {
                                        FileUpload fileUpload = (FileUpload) data;
                                        fileMap.put(fileUpload.getFilename(), fileUpload.get());
                                    }
                                }
                            }
                        } catch (HttpPostRequestDecoder.EndOfDataDecoderException e1) {

                        }
                        if (chunk instanceof LastHttpContent) {
                            decoder.destroy();
                            decoder = null;
                        }
                    }
                }
                renderClass.setPostData(postData);
                renderClass.setFileData(fileMap);
                renderClass.setLoginData(client, remoteClient, loginError);
                renderClass.collect();
                renderClass.setTemplate(fileRequest);

                ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
                renderClass.setOutputStream(outputWriter);

                String output = renderClass.render();
                outputWriter.close();
                writer.writeResponse(chc, HttpResponseStatus.OK, output.getBytes(), fileType, streamId, false);
                break;
            default:
                sendStaticFile(chc, writer, fileRequest, queryStringDecoder, streamId);
                break;
            }
        }
    } catch (ClassNotFoundException | Webservice404Exception ex) {
        LOG.warn("404 error: {} - {} (by {})", ex.getMessage(), ex, plainIp);
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw);) {
            ex.printStackTrace(pw);
            writer.writeResponse(chc, HttpResponseStatus.NOT_FOUND, return404Error().getBytes(), "html",
                    streamId, false);
        } catch (IOException exWriters) {
            LOG.error("Problem outputting 404 error: {}", exWriters.getMessage(), exWriters);
        }
    } catch (Exception ex) {
        LOG.error("500 error: {}", ex.getLocalizedMessage(), ex);
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw);) {
            ex.printStackTrace(pw);
            String errorOutput = sw.toString() + "\n\n" + getRandQuote();
            writer.writeResponse(chc, HttpResponseStatus.INTERNAL_SERVER_ERROR,
                    (errorOutput + "<br/><br/><p>" + getRandQuote() + "</p>").getBytes(), "", streamId, false);
        } catch (IOException exWriters) {
            LOG.error("Problem outputting 500 error: {}", exWriters.getMessage(), exWriters);
        }
    }
}

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

License:Apache License

@Test
public void shouldWrapPostInJsendJson() {
    sendEvent(HttpMethod.POST, "/normal_post.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 POST action\"}",
            httpResponse.toString());/*from  w w  w .  ja v  a2s.com*/
}

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

License:Apache License

@Test
public void shouldWrapPostInJsendJsonUsingQueryString() {
    sendEvent(HttpMethod.POST, "/normal_post?format=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 POST action\"}",
            httpResponse.toString());//from   w  ww  . java  2 s  . com
}

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

License:Apache License

@Test
public void shouldWrapPostInJsendXml() {
    sendEvent(HttpMethod.POST, "/normal_post.xml", "");
    assertEquals(1, observer.getReceivedCount());
    assertEquals(1, observer.getCompleteCount());
    assertEquals(1, observer.getSuccessCount());
    assertEquals(0, observer.getExceptionCount());
    //      System.out.println(httpResponse.toString());
    assertTrue(httpResponse.toString().startsWith("<response>"));
    assertTrue(httpResponse.toString().contains("<code>200</code>"));
    assertTrue(httpResponse.toString().contains("<status>success</status>"));
    assertTrue(httpResponse.toString().contains("<data class=\"string\">Normal POST action</data>"));
    assertTrue(httpResponse.toString().endsWith("</response>"));
}

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

License:Apache License

@Test
public void shouldWrapPostInJsendXmlUsingQueryString() {
    sendEvent(HttpMethod.POST, "/normal_post?format=xml", "");
    assertEquals(1, observer.getReceivedCount());
    assertEquals(1, observer.getCompleteCount());
    assertEquals(1, observer.getSuccessCount());
    assertEquals(0, observer.getExceptionCount());
    //      System.out.println(httpResponse.toString());
    assertTrue(httpResponse.toString().startsWith("<response>"));
    assertTrue(httpResponse.toString().contains("<code>200</code>"));
    assertTrue(httpResponse.toString().contains("<status>success</status>"));
    assertTrue(httpResponse.toString().contains("<data class=\"string\">Normal POST action</data>"));
    assertTrue(httpResponse.toString().endsWith("</response>"));
}

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

License:Apache License

@Test
public void shouldWrapPostInRawJson() {
    sendEvent(HttpMethod.POST, "/normal_post.json", "");
    assertEquals(1, observer.getReceivedCount());
    assertEquals(1, observer.getCompleteCount());
    assertEquals(1, observer.getSuccessCount());
    assertEquals(0, observer.getExceptionCount());
    //      System.out.println(httpResponse.toString());
    assertEquals("\"Normal POST action\"", httpResponse.toString());
}