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:com.rackspacecloud.blueflood.inputs.handlers.HttpEventsIngestionHandlerTest.java

License:Apache License

@Test
public void testInvalidRequestBody() throws Exception {
    ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
    handler.handle(context, createRequest(HttpMethod.POST, "", "{\"xxx\": \"yyy\"}"));
    verify(searchIO, never()).insert(anyString(), anyList());
    verify(channel).write(argument.capture());

    String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset());
    ErrorResponse errorResponse = getErrorResponse(errorResponseBody);

    assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size());
    assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId());
    assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus());
}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpEventsIngestionHandlerTest.java

License:Apache License

@Test
public void testMalformedEventPut() throws Exception {
    final String malformedJSON = "{\"when\":, what]}"; //causes JsonParseException
    handler.handle(context, createRequest(HttpMethod.POST, "", malformedJSON));
    ArgumentCaptor<FullHttpResponse> argument = ArgumentCaptor.forClass(FullHttpResponse.class);
    verify(searchIO, never()).insert(anyString(), anyList());
    verify(channel).write(argument.capture());

    String errorResponseBody = argument.getValue().content().toString(Charset.defaultCharset());
    ErrorResponse errorResponse = getErrorResponse(errorResponseBody);

    assertEquals("Number of errors invalid", 1, errorResponse.getErrors().size());
    assertEquals("Invalid tenant", TENANT, errorResponse.getErrors().get(0).getTenantId());
    assertEquals("Invalid status", HttpResponseStatus.BAD_REQUEST, argument.getValue().getStatus());
}

From source file:com.relayrides.pushy.apns.ApnsClientHandler.java

License:Open Source License

@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise writePromise)
        throws Http2Exception {
    if (message instanceof PushNotificationAndResponsePromise) {
        final PushNotificationAndResponsePromise pushNotificationAndResponsePromise = (PushNotificationAndResponsePromise) message;

        final ApnsPushNotification pushNotification = pushNotificationAndResponsePromise.getPushNotification();

        if (this.responsePromises.containsKey(pushNotification)) {
            writePromise.tryFailure(new PushNotificationStillPendingException());
        } else {/*from  w w w . ja va  2 s .  c  o m*/
            this.responsePromises.put(pushNotification,
                    pushNotificationAndResponsePromise.getResponsePromise());

            pushNotificationAndResponsePromise.getResponsePromise().addListener(
                    new GenericFutureListener<Future<PushNotificationResponse<ApnsPushNotification>>>() {

                        @Override
                        public void operationComplete(
                                final Future<PushNotificationResponse<ApnsPushNotification>> future) {
                            // Regardless of the outcome, when the response promise is finished, we want to remove it from
                            // the map of pending promises.
                            ApnsClientHandler.this.responsePromises.remove(pushNotification);
                        }
                    });

            this.write(context, pushNotification, writePromise);
        }
    } else if (message instanceof ApnsPushNotification) {
        final ApnsPushNotification pushNotification = (ApnsPushNotification) message;

        try {
            final int streamId = (int) this.nextStreamId;

            final Http2Headers headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName())
                    .authority(this.authority).path(APNS_PATH_PREFIX + pushNotification.getToken())
                    .addInt(APNS_EXPIRATION_HEADER, pushNotification.getExpiration() == null ? 0
                            : (int) (pushNotification.getExpiration().getTime() / 1000));

            final String authenticationToken = this.apnsClient
                    .getAuthenticationTokenSupplierForTopic(pushNotification.getTopic()).getToken();
            headers.add(APNS_AUTHORIZATION_HEADER, "bearer " + authenticationToken);

            if (pushNotification.getCollapseId() != null) {
                headers.add(APNS_COLLAPSE_ID_HEADER, pushNotification.getCollapseId());
            }

            if (pushNotification.getPriority() != null) {
                headers.addInt(APNS_PRIORITY_HEADER, pushNotification.getPriority().getCode());
            }

            if (pushNotification.getTopic() != null) {
                headers.add(APNS_TOPIC_HEADER, pushNotification.getTopic());
            }

            final ChannelPromise headersPromise = context.newPromise();
            this.encoder().writeHeaders(context, streamId, headers, 0, false, headersPromise);
            log.trace("Wrote headers on stream {}: {}", streamId, headers);

            final ByteBuf payloadBuffer = context.alloc().ioBuffer(INITIAL_PAYLOAD_BUFFER_CAPACITY);
            payloadBuffer.writeBytes(pushNotification.getPayload().getBytes(StandardCharsets.UTF_8));

            final ChannelPromise dataPromise = context.newPromise();
            this.encoder().writeData(context, streamId, payloadBuffer, 0, true, dataPromise);
            log.trace("Wrote payload on stream {}: {}", streamId, pushNotification.getPayload());

            final PromiseCombiner promiseCombiner = new PromiseCombiner();
            promiseCombiner.addAll(headersPromise, dataPromise);
            promiseCombiner.finish(writePromise);

            writePromise.addListener(new GenericFutureListener<ChannelPromise>() {

                @Override
                public void operationComplete(final ChannelPromise future) throws Exception {
                    if (future.isSuccess()) {
                        ApnsClientHandler.this.pushNotificationsByStreamId.put(streamId, pushNotification);
                        ApnsClientHandler.this.authenticationTokensByStreamId.put(streamId,
                                authenticationToken);
                    } else {
                        log.trace("Failed to write push notification on stream {}.", streamId, future.cause());

                        final Promise<PushNotificationResponse<ApnsPushNotification>> responsePromise = ApnsClientHandler.this.responsePromises
                                .get(pushNotification);

                        if (responsePromise != null) {
                            responsePromise.tryFailure(future.cause());
                        } else {
                            log.error("Notification write failed, but no response promise found.");
                        }
                    }
                }
            });

            this.nextStreamId += 2;

            if (this.nextStreamId >= STREAM_ID_RESET_THRESHOLD) {
                // This is very unlikely, but in the event that we run out of stream IDs (the maximum allowed is
                // 2^31, per https://httpwg.github.io/specs/rfc7540.html#StreamIdentifiers), we need to open a new
                // connection. Just closing the context should be enough; automatic reconnection should take things
                // from there.
                context.close();
            }
        } catch (NoKeyForTopicException | SignatureException e) {
            writePromise.tryFailure(e);
        }

    } else {
        // This should never happen, but in case some foreign debris winds up in the pipeline, just pass it through.
        log.error("Unexpected object in pipeline: {}", message);
        context.write(message, writePromise);
    }
}

From source file:com.schibsted.triathlon.main.TriathlonRouter.java

License:Apache License

public TriathlonRouter(HealthCheckEndpoint healthCheckEndpoint, TriathlonEndpointImpl triathlonEndpoint) {

    delegate = new SimpleUriRouter<>();
    delegate.addUri("/healthcheck", healthCheckEndpoint).addUri("/v2/apps", (request, response) -> {
        Observable<Void> result = Observable.defer(response::close);
        if (request.getHttpMethod() == HttpMethod.POST) {
            result = triathlonEndpoint.postApps(request, response);
        }//from w  w  w .  ja  v a  2s . c o  m
        return result;
    });
}

From source file:com.schibsted.triathlon.main.TriathlonRouterTest.java

License:Apache License

@Test
public void testRouteTriathlon() throws Exception {
    Observable<Void> observable = Mockito.mock(Observable.class);
    when(this.triathlonEndpoint.postApps(any(), any())).thenReturn(observable);
    HttpRequestHeaders headers = Mockito.mock(HttpRequestHeaders.class);

    List<String> uris = Lists.newArrayList("/v2/apps");
    while (uris.size() > 0) {
        String uri = uris.remove(0);
        request = getRequest(uri, headers, HttpMethod.POST);
        response = getResponse();//from   w w  w  .j  a va2s  . c  om
        this.triathlonRouter.handle(request, response);
        verify(this.triathlonEndpoint, times(1)).postApps(request, response);
    }
    request = getRequest("/someOtherUri", headers, HttpMethod.POST);
    response = getResponse();
    this.triathlonRouter.handle(request, response);
    verify(this.triathlonEndpoint, times(0)).postApps(request, response);
    verify(response, times(1)).setStatus(argThat(matchResponseStatus(HttpResponseStatus.NOT_FOUND)));
}

From source file:com.schibsted.triathlon.service.RxTestServer.java

License:Apache License

public HttpServer<ByteBuf, ByteBuf> createServer() {
    HttpServer<ByteBuf, ByteBuf> server = RxNetty
            .newHttpServerBuilder(port, new RequestHandler<ByteBuf, ByteBuf>() {
                @Override//w  ww.  ja  v  a  2  s.co  m
                public Observable<Void> handle(HttpServerRequest<ByteBuf> request,
                        final HttpServerResponse<ByteBuf> response) {
                    if (request.getPath().contains("/v2/apps")) {
                        if (request.getHttpMethod().equals(HttpMethod.POST)) {
                            return handleTest(request, response);
                        }
                    }
                    response.setStatus(HttpResponseStatus.NOT_FOUND);
                    return response.close();
                }
            }).pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpServerConfigurator())
            .enableWireLogging(LogLevel.ERROR).build();

    System.out.println("RxTetstServer server started...");
    return server;
}

From source file:com.seagate.kinetic.client.io.provider.nio.http.HttpTransportProvider.java

License:Open Source License

/**
 * {@inheritDoc}//from   w ww  .ja va 2  s.com
 */
@Override
public void write(KineticMessage km) throws IOException {

    // interface message
    Message.Builder message = (Builder) km.getMessage();

    // extended message
    ExtendedMessage.Builder extendedMessage = ExtendedMessage.newBuilder();

    // set interface message
    extendedMessage.setInterfaceMessage(message);

    // set optional value
    if (km.getValue() != null) {
        extendedMessage.setValue(ByteString.copyFrom(km.getValue()));
    }

    // get serialized bytes
    byte[] array = extendedMessage.build().toByteArray();

    // Prepare the HTTP request.
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/kinetic", Unpooled.copiedBuffer(array));

    request.headers().set(HttpHeaders.Names.HOST, host);

    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.BINARY);

    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    request.headers().set(CONNECTION, Values.KEEP_ALIVE);

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

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

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());

    if (logger.isLoggable(Level.INFO)) {
        logger.info("writing http message, len=" + request.content().readableBytes());
    }

    try {
        this.channel.writeAndFlush(request);
    } finally {
        // request.release();
    }
}

From source file:com.soho.framework.server.servlet.impl.HttpServletRequestImpl.java

License:Apache License

public HttpServletRequestImpl(HttpRequest request, FilterChainImpl chain) {
    this.originalRequest = request;

    if (request instanceof FullHttpRequest) {
        this.inputStream = new ServletInputStreamImpl((FullHttpRequest) request);
    } else {//from w ww .j a  va  2  s . c o  m
        this.inputStream = new ServletInputStreamImpl(request);
    }
    this.reader = new BufferedReader(new InputStreamReader(inputStream));
    this.queryStringDecoder = new QueryStringDecoder(request.uri());

    // post
    if (HttpMethod.POST.name().equalsIgnoreCase(request.method().name())) {
        postRequestDecoder = new HttpPostRequestDecoder(request);
    }

    this.uriParser = new URIParser(chain);
    this.uriParser.parse(request.uri());
    this.characterEncoding = Utils.getCharsetFromContentType(getContentType());
}

From source file:com.sohu.jafka.http.HttpServerHandler.java

License:Apache License

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

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);//from ww  w.java2 s . co m
        }
        body = new ByteArrayOutputStream(64);
        args = new HashMap<String, String>(4);
        //
        if (request.getMethod() != HttpMethod.POST) {
            sendStatusMessage(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, "POST METHOD REQUIRED");
            return;
        }
        HttpHeaders headers = request.headers();
        String contentType = headers.get("Content-Type");
        // ? text or octstream
        args.put("request_key", headers.get("request_key"));
        args.put("topic", headers.get("topic"));
        args.put("partition", headers.get("partition"));
    }

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

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            //body.write(content.array());
            content.readBytes(body, content.readableBytes());
            //body.append(content.toString(CharsetUtil.UTF_8));
        }

        if (msg instanceof LastHttpContent) {
            //process request
            if (server.handler != null) {
                server.handler.handle(args, body.toByteArray());
            }
            if (!writeResponse(ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
            body = null;
            args = null;
        }
    }
}

From source file:com.spotify.google.cloud.pubsub.client.Pubsub.java

License:Apache License

/**
 * Make a POST request./*from w  w  w  . jav  a2  s .c  o m*/
 */
private <T> PubsubFuture<T> post(final String operation, final String path, final Object payload,
        final ResponseReader<T> responseReader) {
    return request(operation, HttpMethod.POST, path, payload, responseReader);
}