Example usage for io.vertx.core.http HttpServerResponse end

List of usage examples for io.vertx.core.http HttpServerResponse end

Introduction

In this page you can find the example usage for io.vertx.core.http HttpServerResponse end.

Prototype

@Override
Future<Void> end();

Source Link

Document

Ends the response.

Usage

From source file:RestAPI.java

private void handleAddProduct(RoutingContext routingContext) {

    JsonObject project = new JsonObject(routingContext.getBodyAsString());

    project.getString("name");
    project.getString("board");
    project.getString("ic");
    project.getString("detail");
    project.getString("visibility");
    //        System.out.println("from post "+routingContext.getBodyAsString());
    //        String productID = routingContext.request().getParam("productID");
    HttpServerResponse response = routingContext.response();
    //        if (productID == null) {
    //            sendError(400, response);
    //        } else {
    //            JsonObject product = routingContext.getBodyAsJson();
    //            if (product == null) {
    //                sendError(400, response);
    //            } else {
    //                products.put(productID, product);
    response.end();
    //            }
    //        }//from w w w. jav a  2  s .c  o m
}

From source file:com.baldmountain.depot.AbstractController.java

License:Open Source License

protected AbstractController redirectTo(RoutingContext context, String route) {
    HttpServerResponse response = context.response();
    response.putHeader("location", route);
    response.setStatusCode(302);/*from   w  w w  .  ja  v  a2 s . c  om*/
    response.end();
    return this;
}

From source file:com.baldmountain.depot.DepotVerticle.java

License:Open Source License

@CodeTranslate
@Override//www .  j  a  v a  2 s.  c o m
public void start() throws Exception {

    JsonObject config = new JsonObject().put("db_name", "depot_development");
    mongoService = MongoService.create(vertx, config);
    mongoService.start();

    // Now do stuff with it:

    //        mongoService.count("products", new JsonObject(), res -> {
    //
    //            // ...
    //            if (res.succeeded()) {
    //                log.error("win: "+res.result());
    //            } else {
    //                log.error("fail: "+res.cause().getMessage());
    //            }
    //        });
    final Router router = Router.router(vertx);

    // We need cookies, sessions and request bodies
    router.route().handler(CookieHandler.create());
    router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
    router.route().handler(BodyHandler.create());

    // Simple auth service which uses a properties file for user/role info
    //        final AuthService authService = ShiroAuthService.create(vertx,
    //                ShiroAuthRealmType.PROPERTIES, new JsonObject());

    // Any requests to URI starting '/private/' require login
    //        router.route("/private/*").handler(
    //                RedirectAuthHandler.create(authService, "/loginpage.html"));

    // Serve the static private pages from directory 'private'
    //        router.route("/private/*").handler(
    //                StaticHandler.create().setCachingEnabled(false)
    //                        .setWebRoot("private"));

    // Handles the actual login
    //        router.route("/loginhandler").handler(
    //                FormLoginHandler.create(authService));

    // Implement logout
    //        router.route("/logout").handler(context -> {
    //            context.session().logout();
    //            // Redirect back to the index page
    //            context.response().putHeader("location", "/")
    //                    .setStatusCode(302).end();
    //        });

    controllers.add(new StoreController(router, mongoService).setupRoutes());
    controllers.add(new ProductsController(router, mongoService).setupRoutes());
    controllers.add(new LineItemsController(router, mongoService).setupRoutes());
    controllers.add(new CartsController(router, mongoService).setupRoutes());

    router.route("/").handler(context -> {
        HttpServerResponse response = context.response();
        response.putHeader("location", "/store");
        response.setStatusCode(302);
        response.end();
    });

    //        router.route("/").handler(context -> {
    //            Product.all(mongoService, result -> {
    //                if (result.succeeded()) {
    //                    log.info("product count: " + result.result().size());
    //                } else {
    //                    context.response().end("Hello world");
    //                }
    //            });
    //        });

    // Serve the non private static pages
    router.route().handler(StaticHandler.create());

    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}

From source file:com.ddp.interpreter.SimpleREST.java

License:Open Source License

private void handleAddProduct(RoutingContext routingContext) {
    String productID = routingContext.request().getParam("productID");
    HttpServerResponse response = routingContext.response();
    if (productID == null) {
        sendError(400, response);// w ww .  j a v a2 s .c om
    } else {
        JsonObject product = routingContext.getBodyAsJson();
        if (product == null) {
            sendError(400, response);
        } else {
            products.put(productID, product);
            response.end();
        }
    }
}

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

License:Open Source License

/**
 * {@inheritDoc}//w  w w  . ja va  2 s  .  com
 */
@Override
public void failure(Throwable error) {

    logger.error(error.getMessage(), error);
    HttpServerResponse response = vertxRequest.response();

    // Set error status and end
    Response.Status status = Response.Status.INTERNAL_SERVER_ERROR;
    response.setStatusCode(status.getStatusCode());
    response.setStatusMessage(status.getReasonPhrase());
    response.end();

}

From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailMicroserviceVerticle.java

License:Open Source License

/**
 * Render thumbnail event handler. Responds with a <code>image/jpeg</code>
 * body on success based on the <code>longestSide</code> and
 * <code>imageId</code> encoded in the URL or HTTP 404 if the {@link Image}
 * does not exist or the user does not have permissions to access it.
 * @param event Current routing context.
 *///from  www. j a v a  2  s .  co m
private void renderThumbnail(RoutingContext event) {
    final HttpServerRequest request = event.request();
    final HttpServerResponse response = event.response();
    final Map<String, Object> data = new HashMap<String, Object>();
    data.put("longestSide",
            Optional.ofNullable(request.getParam("longestSide")).map(Integer::parseInt).orElse(96));
    data.put("imageId", Long.parseLong(request.getParam("imageId")));
    data.put("omeroSessionKey", event.get("omero.session_key"));
    data.put("renderingDefId",
            Optional.ofNullable(request.getParam("rdefId")).map(Long::parseLong).orElse(null));

    vertx.eventBus().<byte[]>send(ThumbnailVerticle.RENDER_THUMBNAIL_EVENT, Json.encode(data), result -> {
        try {
            if (result.failed()) {
                Throwable t = result.cause();
                int statusCode = 404;
                if (t instanceof ReplyException) {
                    statusCode = ((ReplyException) t).failureCode();
                }
                response.setStatusCode(statusCode);
                return;
            }
            byte[] thumbnail = result.result().body();
            response.headers().set("Content-Type", "image/jpeg");
            response.headers().set("Content-Length", String.valueOf(thumbnail.length));
            response.write(Buffer.buffer(thumbnail));
        } finally {
            response.end();
            log.debug("Response ended");
        }
    });
}

From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailMicroserviceVerticle.java

License:Open Source License

/**
 * Get thumbnails event handler. Responds with a JSON dictionary of Base64
 * encoded <code>image/jpeg</code> thumbnails keyed by {@link Image}
 * identifier. Each dictionary value is prefixed with
 * <code>data:image/jpeg;base64,</code> so that it can be used with
 * <a href="http://caniuse.com/#feat=datauri">data URIs</a>.
 * @param event Current routing context.
 *///from   w  w w. ja  v  a 2 s .c om
private void getThumbnails(RoutingContext event) {
    final HttpServerRequest request = event.request();
    final HttpServerResponse response = event.response();
    final Map<String, Object> data = new HashMap<String, Object>();
    final String callback = request.getParam("callback");
    data.put("longestSide",
            Optional.ofNullable(request.getParam("longestSide")).map(Integer::parseInt).orElse(96));
    data.put("imageIds",
            request.params().getAll("id").stream().map(Long::parseLong).collect(Collectors.toList()).toArray());
    data.put("omeroSessionKey", event.get("omero.session_key"));

    vertx.eventBus().<String>send(ThumbnailVerticle.GET_THUMBNAILS_EVENT, Json.encode(data), result -> {
        try {
            if (result.failed()) {
                Throwable t = result.cause();
                int statusCode = 404;
                if (t instanceof ReplyException) {
                    statusCode = ((ReplyException) t).failureCode();
                }
                response.setStatusCode(statusCode);
                return;
            }
            String json = result.result().body();
            String contentType = "application/json";
            if (callback != null) {
                json = String.format("%s(%s);", callback, json);
                contentType = "application/javascript";
            }
            response.headers().set("Content-Type", contentType);
            response.headers().set("Content-Length", String.valueOf(json.length()));
            response.write(json);
        } finally {
            response.end();
            log.debug("Response ended");
        }
    });
}

From source file:com.opinionlab.woa.WallOfAwesome.java

License:Open Source License

private static Handler<RoutingContext> makeDownloadRoute() {
    return routingContext -> EXECUTOR.execute(() -> {
        try {/* w ww. ja va  2 s.  co m*/
            final HttpServerResponse response = routingContext.response();
            final AtomicBoolean first = new AtomicBoolean(true);
            response.putHeader("Content-Type", "text/plain");
            response.putHeader("Content-Disposition", "inline;filename=awesome.txt");

            response.setChunked(true);
            response.write("BEGIN AWESOME\n\n");
            AwesomeImap.fetchAwesome().forEach(awesome -> {
                if (!first.get()) {
                    response.write("\n\n---\n\n");
                } else {
                    first.set(false);
                }

                response.write(new ST(AWESOME_TEMPLATE).add("awesome", awesome).render());
            });
            response.write("\n\nEND AWESOME");
            response.end();
        } catch (Throwable t) {
            LOGGER.error("Unable to fetch messages.", t);
        }
    });
}

From source file:com.sibvisions.vertx.HttpServer.java

License:Apache License

/**
 * Handles a download request./* ww w.  j av  a  2  s  . c om*/
 * 
 * @param pRequest the request
 */
private void handleDownload(HttpServerRequest pRequest) {
    String sKey = pRequest.params().get("KEY");

    if (sKey == null) {
        pRequest.response().setStatusCode(HttpResponseStatus.BAD_REQUEST.code());
        pRequest.response().end();

        return;
    }

    IFileHandle fh = (IFileHandle) ObjectCache.get(sKey);

    HttpServerResponse response = pRequest.response();

    String sType = MimeMapping.getMimeTypeForExtension(FileUtil.getExtension(fh.getFileName()));

    if (sType != null) {
        response.putHeader(HttpHeaders.CONTENT_TYPE, sType);
    }

    response.putHeader("Content-Disposition", "attachment; filename=\"" + fh.getFileName() + "\"");

    int iLen;

    byte[] byContent = new byte[4096];

    try {
        response.putHeader(HttpHeaders.CONTENT_LENGTH, "" + fh.getLength());

        InputStream in = fh.getInputStream();

        Buffer buffer;

        while ((iLen = in.read(byContent)) >= 0) {
            buffer = Buffer.buffer();
            buffer.appendBytes(byContent, 0, iLen);

            response.write(buffer);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    response.end();
}

From source file:de.bischinger.anotherblog.RestVerticle.java

License:Open Source License

private void handleAddBlog(RoutingContext routingContext) {
    String blogKey = routingContext.request().getParam("blogKey");
    HttpServerResponse response = routingContext.response();
    if (blogKey == null) {
        sendError(400, response);/*from  ww  w  . j  a  v  a2s  .  co  m*/
    } else {
        JsonObject blog = routingContext.getBodyAsJson();
        if (blog == null) {
            sendError(400, response);
        } else {
            String id = blog.getString("title");
            IndexRequest indexRequest = new IndexRequest(indexName, typeName, id).source(blog.toString());

            vertx.executeBlocking(future -> {
                client.index(indexRequest).actionGet();
                future.complete();
            }, res -> response.end());
        }
    }
}