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.strategicgains.restexpress.plugin.cache.DateHeaderPostprocessorTest.java

License:Apache License

@Test
public void shouldNotAddDateHeaderOnPost() {
    FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            "/foo?param1=bar&param2=blah&yada");
    httpRequest.headers().add("Host", "testing-host");
    Response response = new Response();
    processor.process(new Request(httpRequest, null), response);
    assertFalse(response.hasHeader(HttpHeaders.Names.DATE));
}

From source file:com.strategicgains.restexpress.plugin.swagger.SwaggerPluginTest.java

License:Apache License

@BeforeClass
public static void intialize() {
    RestAssured.port = PORT;// www  .  ja  va2  s .  c  o m

    DummyController controller = new DummyController();
    SERVER.setBaseUrl(BASE_URL);

    SERVER.uri("/", controller).action("health", HttpMethod.GET).name("root");

    SERVER.uri("/anothers/{userId}", controller).action("readAnother", HttpMethod.GET);

    SERVER.uri("/users.{format}", controller).action("readAll", HttpMethod.GET)
            .action("options", HttpMethod.OPTIONS).method(HttpMethod.POST).name("Users Collection");

    SERVER.uri("/users/{userId}.{format}", controller).method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE)
            .action("options", HttpMethod.OPTIONS).name("Individual User");

    SERVER.uri("/users/{userId}/orders.{format}", controller).action("readAll", HttpMethod.GET)
            .method(HttpMethod.POST).name("User Orders Collection");

    SERVER.uri("/orders.{format}", controller).action("readAll", HttpMethod.GET).method(HttpMethod.POST)
            .name("Orders Collection");

    SERVER.uri("/orders/{orderId}.{format}", controller)
            .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE).name("Individual Order");

    SERVER.uri("/orders/{orderId}/items.{format}", controller).action("readAll", HttpMethod.GET)
            .method(HttpMethod.POST).name("Order Line-Items Collection");

    SERVER.uri("/orders/{orderId}/items/{itemId}.{format}", controller)
            .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE).name("Individual Order Line-Item");

    SERVER.uri("/products.{format}", controller).action("readAll", HttpMethod.GET).method(HttpMethod.POST)
            .name("Orders Collection");

    SERVER.uri("/products/{orderId}.{format}", controller)
            .method(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE).name("Individual Order");

    SERVER.uri("/health", controller).flag("somevalue").action("health", HttpMethod.GET).name("health");

    SERVER.uri("/nicknametest", controller).method(HttpMethod.GET).name(" |nickName sh0uld_str1p-CHARS$. ");

    SERVER.uri("/annotations/{userId}/users", controller)
            .action("readWithApiOperationAnnotation", HttpMethod.GET).method(HttpMethod.GET)
            .name("Read with Annotations");

    SERVER.uri("/annotations/hidden", controller).action("thisIsAHiddenAPI", HttpMethod.GET)
            .method(HttpMethod.GET).name("thisIsAHiddenAPI");

    SERVER.uri("/annotations/{userId}", controller).action("updateWithApiResponse", HttpMethod.PUT)
            .method(HttpMethod.PUT).name("Update with Annotations");

    SERVER.uri("/annotations/{userId}/users/list", controller)
            .action("createWithApiImplicitParams", HttpMethod.POST).method(HttpMethod.POST)
            .name("Create with Implicit Params");

    SERVER.uri("/annotations/{userId}/users/newlist", controller).action("createWithApiParam", HttpMethod.POST)
            .method(HttpMethod.POST).name("Create with Api Param");

    SERVER.uri("/annotations/{userId}/users/list2", controller)
            .action("createWithApiModelRequest", HttpMethod.POST).method(HttpMethod.POST)
            .name("Create with Implicit Params");

    new SwaggerPlugin().apiVersion("1.0").swaggerVersion("1.2").flag("flag1").flag("flag2")
            .parameter("parm1", "value1").parameter("parm2", "value2").register(SERVER);

    SERVER.bind(PORT);
}

From source file:com.stremebase.examples.todomvc.HttpRouter.java

License:Apache License

private static HttpResponse createResponse(HttpRequest req, Router<Integer> router) {
    RouteResult<Integer> routeResult = router.route(req.getMethod(), req.getUri());

    Integer request = routeResult.target();

    String data = "";
    String mimeType = "";

    if (request == CSS) {
        data = Todo.getCss();//from   w w  w  .j a v  a2  s .c om
        mimeType = "text/css";
    } else if (request == ICON) {
        mimeType = "image/x-icon";
    } else if (request == GET) {
        data = Todo.get();
        mimeType = "text/html";
    } else if (request == FILTER) {
        data = Todo.filter(routeResult.pathParams().get("filtertype"));
        mimeType = "text/html";
    } else if (req.getMethod().equals(HttpMethod.POST)) {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);

        Attribute attribute;

        String item_text = null;
        InterfaceHttpData httpData = decoder.getBodyHttpData("item-text");
        if (httpData != null) {
            attribute = (Attribute) httpData;
            try {
                item_text = attribute.getValue();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String item_id = null;
        httpData = decoder.getBodyHttpData("item-id");
        if (httpData != null) {
            attribute = (Attribute) httpData;
            try {
                item_id = attribute.getValue();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (request == POST) {
            if (item_id == null)
                data = Todo.create(item_text);
            else
                data = Todo.save(Long.valueOf(item_id), item_text);
        } else if (request == DELETE) {
            data = Todo.delete(Long.valueOf(item_id));
        } else if (request == DELETECOMPLETED) {
            data = Todo.clearCompleted();
        } else if (request == TOGGLESTATUS)
            data = Todo.toggleStatus(Long.valueOf(item_id));

        mimeType = "text/html";
        decoder.destroy();
    }

    FullHttpResponse res;

    if (request == NOTFOUND) {
        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
        res.headers().add(HttpHeaders.Names.LOCATION, "/");
        return res;
    }

    if (request == ICON)
        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.copiedBuffer(Todo.favicon));
    else
        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.copiedBuffer(data, CharsetUtil.UTF_8));

    res.headers().set(HttpHeaders.Names.CONTENT_TYPE, mimeType);
    res.headers().set(HttpHeaders.Names.CONTENT_LENGTH, res.content().readableBytes());
    if (request == CSS || request == ICON)
        setDateAndCacheHeaders(res);

    return res;
}

From source file:com.titilink.camel.rest.client.CamelClient.java

License:LGPL

/**
 * ??Http post//from ww  w  . j  a v a  2  s .  c  o  m
 *
 * @param uri               
 * @param reqBuffer         ?
 * @param additionalHeaders header????token 
 * @param challengeResponse
 * @param msTimeout         ?0?10s
 * @return
 */
public static RestResponse handlePost(URI uri, byte[] reqBuffer, Map<String, String> additionalHeaders,
        ChallengeResponse challengeResponse, long msTimeout) {
    return handle(HttpMethod.POST, uri, reqBuffer, additionalHeaders, challengeResponse, true, msTimeout);
}

From source file:com.topsec.bdc.platform.api.test.http.upload.HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory management)
 * /* w  w  w  .j av  a 2s.c o  m*/
 * @return the list of HttpData object (attribute and file) to be reused on next post
 */
private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple,
        File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception {

    // XXX /formpost
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false => not multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    bodyRequestEncoder.addBodyAttribute("getform", "POST");
    bodyRequestEncoder.addBodyAttribute("info", "first value");
    bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &");
    bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
    bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
    bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

    // finalize request
    request = bodyRequestEncoder.finalizeRequest();

    // Create the bodylist to be reused on the last version with Multipart support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Do not clear here since we will reuse the InterfaceHttpData on the next request
    // for the example (limit action on client side). Take this as a broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
    return bodylist;
}

From source file:com.topsec.bdc.platform.api.test.http.upload.HttpUploadClient.java

License:Apache License

/**
 * Multipart example/*from www. j a va  2s .  c  o  m*/
 */
private static void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile,
        HttpDataFactory factory, List<Entry<String, String>> headers, List<InterfaceHttpData> bodylist)
        throws Exception {

    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); // true => multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute from previous request in formpost()
    bodyRequestEncoder.setBodyHttpDatas(bodylist);

    // finalize request
    bodyRequestEncoder.finalizeRequest();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}

From source file:com.turo.pushy.apns.AbstractMockApnsServerHandler.java

License:Open Source License

@Override
public void onHeadersRead(final ChannelHandlerContext context, final int streamId, final Http2Headers headers,
        final int padding, final boolean endOfStream) throws Http2Exception {
    if (this.emulateInternalErrors) {
        context.channel().writeAndFlush(new InternalServerErrorResponse(streamId));
    } else {/*from   w ww  .  j  a va 2s .c  om*/
        final Http2Stream stream = this.connection().stream(streamId);

        UUID apnsId = null;

        try {
            {
                final CharSequence apnsIdSequence = headers.get(APNS_ID_HEADER);

                if (apnsIdSequence != null) {
                    try {
                        apnsId = UUID.fromString(apnsIdSequence.toString());
                    } catch (final IllegalArgumentException e) {
                        throw new RejectedNotificationException(ErrorReason.BAD_MESSAGE_ID);
                    }
                } else {
                    // If the client didn't send us a UUID, make one up (for now)
                    apnsId = UUID.randomUUID();
                }
            }

            if (!HttpMethod.POST.asciiName()
                    .contentEquals(headers.get(Http2Headers.PseudoHeaderName.METHOD.value()))) {
                throw new RejectedNotificationException(ErrorReason.METHOD_NOT_ALLOWED);
            }

            if (endOfStream) {
                throw new RejectedNotificationException(ErrorReason.PAYLOAD_EMPTY);
            }

            this.verifyHeaders(headers);

            // At this point, we've made it through all of the headers without an exception and know we're waiting
            // for a data frame. The data frame handler will want the APNs ID in case it needs to send an error
            // response.
            stream.setProperty(this.apnsIdPropertyKey, apnsId);
        } catch (final RejectedNotificationException e) {
            context.channel().writeAndFlush(new RejectNotificationResponse(streamId, apnsId, e.getErrorReason(),
                    e.getDeviceTokenExpirationTimestamp()));
        }
    }
}

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

License:Open Source License

protected Http2Headers getHeadersForPushNotification(final ApnsPushNotification pushNotification,
        final int streamId) {
    final Http2Headers headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName())
            .authority(this.authority).path(APNS_PATH_PREFIX + pushNotification.getToken())
            .scheme(HttpScheme.HTTPS.name())
            .addInt(APNS_EXPIRATION_HEADER, pushNotification.getExpiration() == null ? 0
                    : (int) (pushNotification.getExpiration().getTime() / 1000));

    if (pushNotification.getCollapseId() != null) {
        headers.add(APNS_COLLAPSE_ID_HEADER, pushNotification.getCollapseId());
    }//from   ww w.j av  a2s .  c om

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

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

    if (pushNotification.getApnsId() != null) {
        headers.add(APNS_ID_HEADER, FastUUID.toString(pushNotification.getApnsId()));
    }

    return headers;
}

From source file:com.turo.pushy.apns.server.ValidatingPushNotificationHandler.java

License:Open Source License

@Override
public void handlePushNotification(final Http2Headers headers, final ByteBuf payload)
        throws RejectedNotificationException {

    try {//from   w  ww . jav  a2 s  .  com
        final CharSequence apnsIdSequence = headers.get(APNS_ID_HEADER);

        if (apnsIdSequence != null) {
            FastUUID.parseUUID(apnsIdSequence);
        }
    } catch (final IllegalArgumentException e) {
        throw new RejectedNotificationException(RejectionReason.BAD_MESSAGE_ID);
    }

    if (!HttpMethod.POST.asciiName().contentEquals(headers.get(Http2Headers.PseudoHeaderName.METHOD.value()))) {
        throw new RejectedNotificationException(RejectionReason.METHOD_NOT_ALLOWED);
    }

    final String topic;
    {
        final CharSequence topicSequence = headers.get(APNS_TOPIC_HEADER);

        if (topicSequence == null) {
            throw new RejectedNotificationException(RejectionReason.MISSING_TOPIC);
        }

        topic = topicSequence.toString();
    }

    {
        final CharSequence collapseIdSequence = headers.get(APNS_COLLAPSE_ID_HEADER);

        if (collapseIdSequence != null && collapseIdSequence.toString()
                .getBytes(StandardCharsets.UTF_8).length > MAX_COLLAPSE_ID_SIZE) {
            throw new RejectedNotificationException(RejectionReason.BAD_COLLAPSE_ID);
        }
    }

    {
        final Integer priorityCode = headers.getInt(APNS_PRIORITY_HEADER);

        if (priorityCode != null) {
            try {
                DeliveryPriority.getFromCode(priorityCode);
            } catch (final IllegalArgumentException e) {
                throw new RejectedNotificationException(RejectionReason.BAD_PRIORITY);
            }
        }
    }

    {
        final CharSequence pathSequence = headers.get(Http2Headers.PseudoHeaderName.PATH.value());

        if (pathSequence != null) {
            final String pathString = pathSequence.toString();

            if (pathSequence.toString().equals(APNS_PATH_PREFIX)) {
                throw new RejectedNotificationException(RejectionReason.MISSING_DEVICE_TOKEN);
            } else if (pathString.startsWith(APNS_PATH_PREFIX)) {
                final String deviceToken = pathString.substring(APNS_PATH_PREFIX.length());

                final Matcher tokenMatcher = DEVICE_TOKEN_PATTERN.matcher(deviceToken);

                if (!tokenMatcher.matches()) {
                    throw new RejectedNotificationException(RejectionReason.BAD_DEVICE_TOKEN);
                }

                final Date expirationTimestamp = this.expirationTimestampsByDeviceToken.get(deviceToken);

                if (expirationTimestamp != null) {
                    throw new UnregisteredDeviceTokenException(expirationTimestamp);
                }

                final Set<String> allowedDeviceTokensForTopic = this.deviceTokensByTopic.get(topic);

                if (allowedDeviceTokensForTopic == null || !allowedDeviceTokensForTopic.contains(deviceToken)) {
                    throw new RejectedNotificationException(RejectionReason.DEVICE_TOKEN_NOT_FOR_TOPIC);
                }
            } else {
                throw new RejectedNotificationException(RejectionReason.BAD_PATH);
            }
        } else {
            throw new RejectedNotificationException(RejectionReason.BAD_PATH);
        }
    }

    this.verifyAuthentication(headers);

    if (payload == null || payload.readableBytes() == 0) {
        throw new RejectedNotificationException(RejectionReason.PAYLOAD_EMPTY);
    }

    if (payload.readableBytes() > MAX_PAYLOAD_SIZE) {
        throw new RejectedNotificationException(RejectionReason.PAYLOAD_TOO_LARGE);
    }
}

From source file:com.turo.pushy.apns.server.ValidatingPushNotificationHandlerTest.java

License:Open Source License

@Before
public void setUp() throws Exception {
    this.headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName()).authority(getClass().getName())
            .path(APNS_PATH_PREFIX + TOKEN);

    this.headers.add(APNS_TOPIC_HEADER, TOPIC);

    this.addAcceptableCredentialsToHeaders(this.headers);

    this.payload = UnpooledByteBufAllocator.DEFAULT.buffer();
    this.payload.writeBytes("{}".getBytes(StandardCharsets.UTF_8));
}