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:io.liveoak.container.protocols.http.HttpResourceRequestDecoderTest.java

License:Open Source License

@Test
public void testDecodePost() throws Exception {
    DefaultResourceRequest decoded = decode(HttpMethod.POST, "/memory/people/bob",
            "{ name: 'bob', int: 1024, maxInt: 2147483647, minInt: -2147483648, longNeg: -2147483659, longPos: 2147483648 }");

    assertThat(decoded.requestType()).isEqualTo(RequestType.CREATE);

    assertThat(decoded.resourcePath().segments()).hasSize(3);
    assertThat(decoded.resourcePath().segments().get(0).name()).isEqualTo("memory");
    assertThat(decoded.resourcePath().segments().get(1).name()).isEqualTo("people");
    assertThat(decoded.resourcePath().segments().get(2).name()).isEqualTo("bob");

    //assertThat(decoded.mediaType()).isEqualTo(MediaType.JSON);

    assertThat(decoded.requestContext().pagination()).isNotNull();
    assertThat(decoded.requestContext().pagination()).isEqualTo(Pagination.NONE);

    assertThat(decoded.state()).isNotNull();
    assertThat(decoded.state()).isInstanceOf(ResourceState.class);

    ResourceState state = decoded.state();

    assertThat(state.getProperty("name")).isEqualTo("bob");
    assertThat(state.getProperty("int")).isEqualTo(1024);
    assertThat(state.getProperty("maxInt")).isEqualTo(2147483647);
    assertThat(state.getProperty("minInt")).isEqualTo(-2147483648);
    assertThat(state.getProperty("longNeg")).isEqualTo(-2147483659L);
    assertThat(state.getProperty("longPos")).isEqualTo(2147483648L);
}

From source file:io.nebo.container.ServletContentHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        log.info("uri" + request.getUri());
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, false);
        NettyHttpServletResponse servletResponse = new NettyHttpServletResponse(ctx, servletContext, response);
        servletRequest = new NettyHttpServletRequest(ctx, servletContext, request, inputStream,
                servletResponse);// www  .j  a  v  a2 s .  c  o  m
        if (HttpMethod.GET.equals(request.getMethod())) {
            HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request));
            if (HttpHeaders.is100ContinueExpected(request)) {
                ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE),
                        ctx.voidPromise());
            }
            ctx.fireChannelRead(servletRequest);
        } else if (HttpMethod.POST.equals(request.getMethod())) {
            decoder = new HttpPostRequestDecoder(factory, request);
        }
    }

    if (decoder != null && msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        log.info("HttpContent" + chunk.content().readableBytes());
        inputStream.addContent(chunk);
        List<InterfaceHttpData> interfaceHttpDatas = decoder.getBodyHttpDatas();

        for (InterfaceHttpData data : interfaceHttpDatas) {
            try {
                if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    Attribute attribute = (Attribute) data;
                    Map<String, String[]> params = servletRequest.getParameterMap();
                    HttpRequestUtils.setParamMap(attribute.getName(), attribute.getValue(), params);
                }
            } finally {
                // data.release();
            }
        }

    }

    if (decoder != null && msg instanceof LastHttpContent) {
        ctx.fireChannelRead(servletRequest);
        reset();
    }
}

From source file:io.reactivex.netty.examples.http.post.SimplePostClient.java

License:Apache License

public String postMessage() {
    PipelineConfigurator<HttpClientResponse<ByteBuf>, HttpClientRequest<String>> pipelineConfigurator = PipelineConfigurators
            .httpClientConfigurator();/* www.  j a v  a  2s  .  c  o m*/

    HttpClient<String, ByteBuf> client = RxNetty.<String, ByteBuf>newHttpClientBuilder("localhost", port)
            .pipelineConfigurator(pipelineConfigurator).enableWireLogging(LogLevel.ERROR).build();

    HttpClientRequest<String> request = HttpClientRequest.create(HttpMethod.POST, "test/post");
    request.withRawContentSource(Observable.just(MESSAGE), StringTransformer.DEFAULT_INSTANCE);

    String result = client.submit(request)
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<String>>() {
                @Override
                public Observable<String> call(HttpClientResponse<ByteBuf> response) {
                    return response.getContent().map(new Func1<ByteBuf, String>() {
                        @Override
                        public String call(ByteBuf byteBuf) {
                            return byteBuf.toString(Charset.defaultCharset());
                        }
                    });
                }
            }).toBlocking().single();

    return result;
}

From source file:io.reactivex.netty.examples.http.wordcounter.WordCounterClient.java

License:Apache License

public int countWords() throws IOException {
    PipelineConfigurator<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>> pipelineConfigurator = PipelineConfigurators
            .httpClientConfigurator();/*w  w  w.j  av a 2s  . c  om*/

    HttpClient<ByteBuf, ByteBuf> client = RxNetty.createHttpClient("localhost", port, pipelineConfigurator);
    HttpClientRequest<ByteBuf> request = HttpClientRequest.create(HttpMethod.POST, "test/post");

    FileContentSource fileContentSource = new FileContentSource(new File(textFile));
    request.withRawContentSource(fileContentSource, StringTransformer.DEFAULT_INSTANCE);

    WordCountAction wAction = new WordCountAction();
    client.submit(request).toBlocking().forEach(wAction);

    return wAction.wordCount;
}

From source file:io.reactivex.netty.protocol.http.client.HttpClientRequest.java

License:Apache License

public static HttpClientRequest<ByteBuf> createPost(String uri) {
    return create(HttpMethod.POST, uri);
}

From source file:io.reactivex.netty.protocol.http.client.HttpClientTest.java

License:Apache License

@Test
public void testPostWithRawContentSource() {
    PipelineConfigurator<HttpClientResponse<ByteBuf>, HttpClientRequest<String>> pipelineConfigurator = PipelineConfigurators
            .httpClientConfigurator();//from  w w w.  j av  a  2  s . c o  m

    HttpClient<String, ByteBuf> client = RxNetty.createHttpClient("localhost", port, pipelineConfigurator);
    HttpClientRequest<String> request = HttpClientRequest.create(HttpMethod.POST, "test/post");
    request.withRawContentSource(Observable.just("Hello world"), StringTransformer.DEFAULT_INSTANCE);
    Observable<HttpClientResponse<ByteBuf>> response = client.submit(request);
    String result = response.flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<String>>() {
        @Override
        public Observable<String> call(HttpClientResponse<ByteBuf> response) {
            return response.getContent().map(new Func1<ByteBuf, String>() {
                @Override
                public String call(ByteBuf byteBuf) {
                    return byteBuf.toString(Charset.defaultCharset());
                }
            });
        }
    }).toBlocking().single();
    assertEquals("Hello world", result);
}

From source file:io.reactivex.netty.protocol.http.client.RepeatableRequestTest.java

License:Apache License

@Test
public void testRepeatableRequest() {
    final List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < 10; i++) {
        list.add(i);//from  w  w w .  ja  va  2s  .co m
    }

    ContentSource<Integer> source = new ContentSource<Integer>() {
        Iterator<Integer> iterator = list.iterator();

        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }

        @Override
        public Integer next() {
            return iterator.next();
        }
    };

    HttpClientRequest<Integer> request = HttpClientRequest
            .<Integer>create(HttpVersion.HTTP_1_1, HttpMethod.POST, "/").withContentSource(source);
    HttpClientRequest<Integer> repeatable = new RepeatableContentHttpRequest<Integer>(request);
    ContentSourceFactory<Integer, ContentSource<Integer>> factory = repeatable.contentFactory;
    ContentSource<Integer> source2 = factory.newContentSource();
    source2.next();
    source2.next();
    source2 = factory.newContentSource();
    List<Integer> result = new ArrayList<Integer>();
    while (source2.hasNext()) {
        result.add(source2.next());
    }
    assertEquals(list, result);

    // go over again
    source2 = factory.newContentSource();
    result = new ArrayList<Integer>();
    while (source2.hasNext()) {
        result.add(source2.next());
    }
    assertEquals(list, result);
}

From source file:io.reactivex.netty.protocol.http.client.RequestProcessor.java

License:Apache License

@Override
public Observable<Void> handle(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) {
    String uri = request.getUri();
    if (uri.startsWith("/") && uri.length() > 1) {
        uri = uri.substring(1);//  w  ww  .  ja  v a 2 s  .c  om
    }
    if ("/".equals(uri) || uri.contains("test/singleEntity")) {
        // in case of redirect, uri starts with /test/singleEntity 
        return handleSingleEntity(response);
    } else if (uri.startsWith("test/stream")) {
        return handleStream(response);
    } else if (uri.startsWith("test/nochunk_stream")) {
        return handleStreamWithoutChunking(response);
    } else if (uri.startsWith("test/largeStream")) {
        return handleLargeStream(response);
    } else if (uri.startsWith("test/timeout")) {
        return simulateTimeout(request, response);
    } else if (uri.contains("test/post")) {
        return handlePost(request, response);
    } else if (uri.startsWith("test/closeConnection")) {
        return handleCloseConnection(response);
    } else if (uri.startsWith("test/keepAliveTimeout")) {
        return handleKeepAliveTimeout(response);
    } else if (uri.startsWith("test/redirectInfinite")) {
        return redirectCustom(request, response);
    } else if (uri.startsWith("test/redirectLoop")) {
        return redirectCustom(request, response);
    } else if (uri.startsWith("test/redirectLimited")) {
        return redirectCustom(request, response);
    } else if (uri.startsWith("test/redirect") && request.getHttpMethod().equals(HttpMethod.GET)) {
        return redirectGet(request, response);
    } else if (uri.startsWith("test/redirectPost") && request.getHttpMethod().equals(HttpMethod.POST)) {
        return redirectPost(request, response);
    } else {
        response.setStatus(HttpResponseStatus.NOT_FOUND);
        return response.flush();
    }
}

From source file:io.reactivex.netty.samples.SimplePostClient.java

License:Apache License

public Observable<String> postMessage() {

    HttpClient<String, ByteBuf> client = RxNetty.<String, ByteBuf>newHttpClientBuilder(host, port)
            .pipelineConfigurator(PipelineConfigurators.httpClientConfigurator())
            .enableWireLogging(LogLevel.ERROR).build();

    HttpClientRequest<String> request = HttpClientRequest.create(HttpMethod.POST, path);

    request.withHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");

    String authString = USERNAME + ":" + PASSWORD;
    ByteBuf authByteBuf = Unpooled.copiedBuffer(authString.toCharArray(), CharsetUtil.UTF_8);
    ByteBuf encodedAuthByteBuf = Base64.encode(authByteBuf);
    request.withHeader(HttpHeaders.Names.AUTHORIZATION,
            "Basic " + encodedAuthByteBuf.toString(CharsetUtil.UTF_8));

    request.withRawContentSource(Observable.just(MESSAGE), StringTransformer.DEFAULT_INSTANCE);

    return client.submit(request).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<String>>() {

        @Override/*from  www.j  a va2 s . co m*/
        public Observable<String> call(HttpClientResponse<ByteBuf> response) {

            if (!response.getStatus().equals(HttpResponseStatus.OK)) {
                return Observable.<String>error(new HttpStatusNotOKException());
            }

            return response.getContent()
                    // .defaultIfEmpty(Unpooled.EMPTY_BUFFER)
                    .map(new Func1<ByteBuf, ByteBuf>() {

                        @Override
                        public ByteBuf call(ByteBuf buf) {
                            return Unpooled.copiedBuffer(buf);
                        }
                    }).reduce(new Func2<ByteBuf, ByteBuf, ByteBuf>() {

                        @Override
                        public ByteBuf call(ByteBuf buf1, ByteBuf buf2) {
                            ByteBuf buf3 = Unpooled.copiedBuffer(buf1, buf2);
                            buf1.release();
                            buf2.release();
                            return buf3;
                        }
                    }).map(new Func1<ByteBuf, String>() {

                        @Override
                        public String call(ByteBuf buf4) {

                            String str = buf4.toString(Charset.defaultCharset());
                            buf4.release();

                            return str;
                        }
                    });
        }
    }).retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {

        @Override
        public Observable<?> call(Observable<? extends Throwable> notificationHandler) {
            return notificationHandler.flatMap(new Func1<Throwable, Observable<Throwable>>() {

                @Override
                public Observable<Throwable> call(Throwable e) {

                    if ((e instanceof ConnectException
                            && e.getMessage().subSequence(0, 18).equals("Connection refused"))
                            || (e instanceof HttpStatusNotOKException) || (e instanceof NoSuchElementException
                                    && e.getMessage().equals("Sequence contains no elements"))) {
                        // logger.error(e.getMessage(), e);
                        return Observable.<Throwable>just(e);
                    }

                    return Observable.<Throwable>error(e);
                }
            }).zipWith(Observable.range(1, 4), (e, i) -> {
                // TODO create tuple class to contain both e, i
                if (i < 4) {
                    return new Throwable(String.valueOf(i));
                } else {
                    return e;
                }
            }).flatMap((e) -> {
                try {
                    int i = Integer.valueOf(e.getMessage());
                    logger.info("retry({}{}) after {}sec", i,
                            (i == 1) ? "st" : (i == 2) ? "nd" : (i == 3) ? "rd" : "th", 1);
                    return Observable.timer(3, TimeUnit.SECONDS);
                } catch (NumberFormatException nfe) {
                    return Observable.<Throwable>error(e);
                }
            });
        }

    });
    // .toBlocking().singleOrDefault("No Data");
}

From source file:io.scalecube.socketio.pipeline.HandshakeHandlerTest.java

License:Apache License

@Test
public void testChannelReadPost() throws Exception {
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/socket.io/1/");
    LastOutboundHandler lastOutboundHandler = new LastOutboundHandler();
    EmbeddedChannel channel = new EmbeddedChannel(lastOutboundHandler, handshakeHandler);
    channel.writeInbound(request);// w  w  w . j a  va2 s  .  c  o  m
    Object object = channel.readInbound();
    Assert.assertTrue(object instanceof HttpRequest);
    Assert.assertEquals(request, object);
    channel.finish();
}