Example usage for io.vertx.core.http HttpMethod PUT

List of usage examples for io.vertx.core.http HttpMethod PUT

Introduction

In this page you can find the example usage for io.vertx.core.http HttpMethod PUT.

Prototype

HttpMethod PUT

To view the source code for io.vertx.core.http HttpMethod PUT.

Click Source Link

Usage

From source file:com.englishtown.vertx.jersey.impl.DefaultJerseyHandler.java

License:Open Source License

protected boolean shouldReadData(HttpServerRequest vertxRequest) {

    HttpMethod method = vertxRequest.method();

    // Only read input stream data for post/put methods
    if (!(HttpMethod.POST == method || HttpMethod.PUT == method)) {
        return false;
    }/*  w ww.ja  va 2  s  .  co  m*/

    String contentType = vertxRequest.headers().get(HttpHeaders.CONTENT_TYPE);

    if (contentType == null || contentType.isEmpty()) {
        // Special handling for IE8 XDomainRequest where content-type is missing
        // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
        return true;
    }

    MediaType mediaType = MediaType.valueOf(contentType);

    // Allow text/plain
    if (MediaType.TEXT_PLAIN_TYPE.getType().equals(mediaType.getType())
            && MediaType.TEXT_PLAIN_TYPE.getSubtype().equals(mediaType.getSubtype())) {
        return true;
    }

    // Only other media types accepted are application (will check subtypes next)
    String applicationType = MediaType.APPLICATION_FORM_URLENCODED_TYPE.getType();
    if (!applicationType.equalsIgnoreCase(mediaType.getType())) {
        return false;
    }

    // Need to do some special handling for forms:
    // Jersey doesn't properly handle when charset is included
    if (mediaType.getSubtype().equalsIgnoreCase(MediaType.APPLICATION_FORM_URLENCODED_TYPE.getSubtype())) {
        if (!mediaType.getParameters().isEmpty()) {
            vertxRequest.headers().remove(HttpHeaders.CONTENT_TYPE);
            vertxRequest.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
        }
        return true;
    }

    // Also accept json/xml sub types
    return MediaType.APPLICATION_JSON_TYPE.getSubtype().equalsIgnoreCase(mediaType.getSubtype())
            || MediaType.APPLICATION_XML_TYPE.getSubtype().equalsIgnoreCase(mediaType.getSubtype());
}

From source file:com.hubrick.vertx.rest.impl.DefaultRestClient.java

License:Apache License

@Override
public <T> RestClientRequest<T> put(String uri, Class<T> responseClass,
        Handler<RestClientResponse<T>> responseHandler) {
    return handleRequest(HttpMethod.PUT, uri, responseClass, responseHandler);
}

From source file:com.hubrick.vertx.rest.rx.impl.DefaultRxRestClient.java

License:Apache License

@Override
public Observable<RestClientResponse<Void>> put(String uri, Action1<RestClientRequest> requestBuilder) {
    return request(HttpMethod.PUT, uri, Void.class, requestBuilder);
}

From source file:com.hubrick.vertx.rest.rx.impl.DefaultRxRestClient.java

License:Apache License

@Override
public <T> Observable<RestClientResponse<T>> put(String uri, Class<T> responseClass,
        Action1<RestClientRequest> requestBuilder) {
    return request(HttpMethod.PUT, uri, responseClass, requestBuilder);
}

From source file:de.elsibay.EbbTicketShowcase.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) throws Exception {

    SessionStore sessionStore = LocalSessionStore.create(vertx);
    Router backendRouter = Router.router(vertx);
    backendRouter.route().handler(LoggerHandler.create(LoggerHandler.DEFAULT_FORMAT));
    CookieHandler cookieHandler = CookieHandler.create();
    SessionHandler sessionHandler = SessionHandler.create(sessionStore);
    // the CORS OPTION request must not set cookies
    backendRouter.get().handler(cookieHandler);
    backendRouter.get().handler(sessionHandler);
    backendRouter.post().handler(cookieHandler);
    backendRouter.post().handler(sessionHandler);

    // setup CORS
    CorsHandler corsHandler = CorsHandler.create("http(s)?://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT)
            .allowCredentials(true).allowedHeader(HttpHeaders.ACCEPT.toString())
            .allowedHeader(HttpHeaders.ORIGIN.toString()).allowedHeader(HttpHeaders.AUTHORIZATION.toString())
            .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()).allowedHeader(HttpHeaders.COOKIE.toString())
            .exposedHeader(HttpHeaders.SET_COOKIE.toString()).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.PUT).allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.DELETE);

    // setup event bus bridge
    TicketEventbusBridge sebb = new TicketEventbusBridge(sessionStore);
    backendRouter.mountSubRouter("/eventbus", sebb.route(vertx));

    // dummy eventbus services
    vertx.eventBus().consumer("ping", (Message<JsonObject> msg) -> {
        msg.reply(new JsonObject().put("answer", "pong " + msg.body().getString("text", "")));
    });/*from   w  w  w.j av  a 2  s .  c  o m*/

    vertx.setPeriodic(5000, id -> {
        vertx.eventBus().send("topic", new JsonObject().put("timestamp", new Date().getTime()));
    });

    // session manager for login
    backendRouter.route("/api/*").handler(corsHandler);
    backendRouter.route("/api/*").method(HttpMethod.POST).method(HttpMethod.PUT).handler(BodyHandler.create());

    backendRouter.route("/api/session").handler((RoutingContext rc) -> {
        JsonObject user = rc.getBodyAsJson();
        String sessionId = rc.session().id();
        rc.session().put("user", user);
        rc.response().end(user.copy().put("sessionId", sessionId).encodePrettily());
    });

    // dummy ping REST service
    backendRouter.route("/api/ping").handler((RoutingContext rc) -> {
        JsonObject replyMsg = new JsonObject();
        replyMsg.put("timestamp", new Date().getTime());
        Cookie sessionCookie = rc.getCookie(SessionHandler.DEFAULT_SESSION_COOKIE_NAME);
        if (sessionCookie != null) {
            replyMsg.put("sessionId", sessionCookie.getValue());
        }
        rc.response().end(replyMsg.encode());
    });

    // start backend on one port
    vertx.createHttpServer().requestHandler(backendRouter::accept).listen(BACKENDSERVER_PORT,
            BACKENDSERVER_HOST, (AsyncResult<HttpServer> async) -> {
                System.out
                        .println(async.succeeded() ? "Backend Server started" : "Backend Server start FAILED");
            });

    // static files on other port
    Router staticFilesRouter = Router.router(vertx);
    staticFilesRouter.route("/*").handler(StaticHandler.create("src/main/www").setCachingEnabled(false));
    vertx.createHttpServer().requestHandler(staticFilesRouter::accept).listen(WEBSERVER_PORT, WEBSERVER_HOST,
            (AsyncResult<HttpServer> async) -> {
                System.out.println(async.succeeded()
                        ? "Web Server started\ngoto http://" + WEBSERVER_HOST + ":" + WEBSERVER_PORT + "/"
                        : "Web Server start FAILED");
            });
}

From source file:es.upv.grycap.opengateway.core.http.BaseRestService.java

License:Apache License

@Override
public void start() throws Exception {
    requireNonNull(serviceConfig, "A valid service configuration expected");
    requireNonNull(loadBalancerClient, "A valid load balancer client expected");
    // set body limit and create router
    final long maxBodySize = context.config().getLong("http-server.max-body-size", MAX_BODY_SIZE_MIB) * 1024l
            * 1024l;/*from  w  w w.jav a 2  s .c o  m*/
    final Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create().setBodyLimit(maxBodySize));
    // enable CORS
    router.route().handler(CorsHandler.create("*").allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.PUT).allowedMethod(HttpMethod.DELETE).allowedMethod(HttpMethod.OPTIONS)
            .allowedHeader("Content-Type").allowedHeader("Authorization"));
    // configure index page      
    router.route(serviceConfig.getFrontpage().orElse("/")).handler(StaticHandler.create());
    // serve resources
    serviceConfig.getServices().values().stream().forEach(s -> {
        final String path = requireNonNull(s.getPath(), "A valid path required");
        router.get(String.format("%s/:id", path)).produces("application/json").handler(e -> handleGet(s, e));
        router.get(path).produces("application/json").handler(e -> handleList(s, e));
        router.post(path).handler(e -> handleCreate(s, e));
        router.put(String.format("%s/:id", path)).consumes("application/json").handler(e -> handleModify(s, e));
        router.delete(String.format("%s/:id", path)).handler(e -> handleDelete(s, e));
    });
    // start HTTP server
    final int port = context.config().getInteger("http.port", 8080);
    vertx.createHttpServer().requestHandler(router::accept).listen(port);
    logger.trace("New instance created: [id=" + context.deploymentID() + "].");
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example27(Vertx vertx) {
    vertx.createHttpServer().requestHandler(request -> {
        HttpServerResponse response = request.response();
        if (request.method() == HttpMethod.PUT) {
            response.setChunked(true);/*from   ww  w  . j a v a 2  s  .  c o  m*/
            Pump.pump(request, response).start();
            request.endHandler(v -> response.end());
        } else {
            response.setStatusCode(400).end();
        }
    }).listen(8080);
}

From source file:io.gravitee.gateway.http.vertx.VertxHttpClient.java

License:Apache License

private HttpMethod convert(io.gravitee.common.http.HttpMethod httpMethod) {
    switch (httpMethod) {
    case CONNECT:
        return HttpMethod.CONNECT;
    case DELETE:/*from  w w w . j  a  v  a  2s  .co  m*/
        return HttpMethod.DELETE;
    case GET:
        return HttpMethod.GET;
    case HEAD:
        return HttpMethod.HEAD;
    case OPTIONS:
        return HttpMethod.OPTIONS;
    case PATCH:
        return HttpMethod.PATCH;
    case POST:
        return HttpMethod.POST;
    case PUT:
        return HttpMethod.PUT;
    case TRACE:
        return HttpMethod.TRACE;
    }

    return null;
}

From source file:io.servicecomb.serviceregistry.client.http.RestUtils.java

License:Apache License

public static void put(IpPort ipPort, String uri, RequestParam requestParam,
        Handler<RestResponse> responseHandler) {
    httpDo(createRequestContext(HttpMethod.PUT, ipPort, uri, requestParam), responseHandler);
}

From source file:io.ventu.rpc.rest.HttpRestInvokerImpl.java

License:MIT License

@Override
public <RQ, RS> CompletableFuture<RS> invoke(final RQ request, final Class<RS> responseClass) {
    final CompletableFuture<RS> answer = new CompletableFuture<>();
    try {//from  ww  w .  j a va  2s. c om
        String url = requestRouter.route(request);

        HttpMethod method = HttpMethod.POST;
        switch (requestRouter.type(request)) {
        case GET:
            method = HttpMethod.GET;
            break;
        case PUT:
            method = HttpMethod.PUT;
            break;
        case DELETE:
            method = HttpMethod.DELETE;
            break;
        default: // POST, keep as is
        }

        HttpClientRequest httpRequest = client.request(method, url, httpResponse -> {
            int statusCode = httpResponse.statusCode();
            if (statusCode < 400) {
                httpResponse.bodyHandler(buffer -> {
                    try {
                        RS resp = serializer.decode(buffer.getBytes(), responseClass);
                        responseValidator.validate(resp);
                        answer.complete(resp);
                    } catch (ApiException | EncodingException | IllegalArgumentException
                            | NullPointerException ex) {
                        answer.completeExceptionally(ex);
                    }
                });
            } else {
                answer.completeExceptionally(new HttpException(statusCode, httpResponse.statusMessage()));
            }
        });
        for (Entry<String, String> entry : headers.entrySet()) {
            httpRequest.putHeader(entry.getKey(), entry.getValue());
        }
        httpRequest.putHeader("Content-type", CONTENT_TYPE).putHeader("Accept", CONTENT_TYPE);

        if ((method == HttpMethod.POST) || (method == HttpMethod.PUT)) {
            byte[] payload = serializer.encode(request);
            httpRequest.setChunked(true).end(Buffer.buffer(payload));
        } else {
            httpRequest.end();
        }
    } catch (IllegalArgumentException | EncodingException ex) {
        answer.completeExceptionally(ex);
    }
    return answer;
}