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

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

Introduction

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

Prototype

void close();

Source Link

Document

Close the underlying TCP connection corresponding to the request.

Usage

From source file:org.wisdom.framework.vertx.HttpHandler.java

License:Apache License

/**
 * This method must be called in a Vert.X context. It finalizes the response and send it to the client.
 *
 * @param context                     the HTTP context
 * @param request                     the Vert.x request
 * @param result                      the computed result
 * @param stream                      the stream of the result
 * @param success                     a flag indicating whether or not the request was successfully handled
 * @param handleFlashAndSessionCookie if the flash and session cookie need to be send with the response
 * @param closeConnection             whehter or not the (underlying) TCP connection must be closed
 *///from w  w w. java2s .c  om
private void finalizeWriteReponse(final ContextFromVertx context, final HttpServerRequest request,
        Result result, InputStream stream, boolean success, boolean handleFlashAndSessionCookie,
        boolean closeConnection) {

    Renderable<?> renderable = result.getRenderable();
    if (renderable == null) {
        renderable = NoHttpBody.INSTANCE;
    }
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpUtils.isKeepAlive(request);

    // Build the response object.
    final HttpServerResponse response = request.response();

    // Copy headers from the result
    for (Map.Entry<String, String> header : result.getHeaders().entrySet()) {
        response.putHeader(header.getKey(), header.getValue());
    }

    if (!result.getHeaders().containsKey(HeaderNames.SERVER)) {
        // Add the server metadata
        response.putHeader(HeaderNames.SERVER, SERVER_NAME);
    }

    String fullContentType = result.getFullContentType();
    if (fullContentType == null) {
        if (renderable.mimetype() != null) {
            response.putHeader(HeaderNames.CONTENT_TYPE, renderable.mimetype());
        }
    } else {
        response.putHeader(HeaderNames.CONTENT_TYPE, fullContentType);
    }

    // copy cookies / flash and session
    if (handleFlashAndSessionCookie) {
        context.flash().save(context, result);
        context.session().save(context, result);
    }

    // copy cookies
    for (org.wisdom.api.cookies.Cookie cookie : result.getCookies()) {
        // Encode cookies:
        final String encoded = ServerCookieEncoder.LAX
                .encode(CookieHelper.convertWisdomCookieToNettyCookie(cookie));
        // Here we use the 'add' method to add a new value to the header.
        response.headers().add(HeaderNames.SET_COOKIE, encoded);
    }
    response.setStatusCode(HttpUtils.getStatusFromResult(result, success));
    if (renderable.mustBeChunked()) {
        LOGGER.debug("Building the chunked response for {} {} ({})", request.method(), request.uri(), context);
        if (renderable.length() > 0 && !response.headers().contains(HeaderNames.CONTENT_LENGTH)) {
            response.putHeader(HeaderNames.CONTENT_LENGTH, Long.toString(renderable.length()));
        }

        if (!response.headers().contains(HeaderNames.CONTENT_TYPE)) {
            // No content is not legal, set default to binary.
            response.putHeader(HeaderNames.CONTENT_TYPE, MimeTypes.BINARY);
        }

        // Can't determine the size, so switch to chunked.
        response.setChunked(true);
        response.putHeader(HeaderNames.TRANSFER_ENCODING, "chunked");
        // In addition, we can't keep the connection open.
        response.putHeader(HeaderNames.CONNECTION, "close");

        final AsyncInputStream s = new AsyncInputStream(vertx, accessor.getExecutor(), stream);
        s.setContext(context.vertxContext());
        final Pump pump = Pump.pump(s, response);
        s.endHandler(event -> context.vertxContext().runOnContext(event1 -> {
            LOGGER.debug("Ending chunked response for {}", request.uri());
            response.end();
            response.close();
            cleanup(context);
        }));
        s.exceptionHandler(event -> context.vertxContext().runOnContext(event1 -> {
            LOGGER.error("Cannot read the result stream", event1);
            response.close();
            cleanup(context);
        }));
        context.vertxContext().runOnContext(event -> pump.start());

    } else {
        byte[] cont = new byte[0];
        try {
            cont = IOUtils.toByteArray(stream);
        } catch (IOException e) {
            LOGGER.error("Cannot copy the response to {}", request.uri(), e);
        }

        if (!response.headers().contains(HeaderNames.CONTENT_LENGTH)) {
            // Because of the HEAD implementation, if the length is already set, do not update it.
            // (HEAD would mean no content)
            response.putHeader(HeaderNames.CONTENT_LENGTH, Long.toString(cont.length));
        }

        if (keepAlive) {
            // Add keep alive header as per:
            // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
            response.putHeader(HeaderNames.CONNECTION, "keep-alive");
        }
        response.write(Buffer.buffer(cont));
        if (HttpUtils.isKeepAlive(request) && !closeConnection) {
            response.end();
        } else {
            response.end();
            response.close();
        }
        cleanup(context);
    }
}

From source file:vertx_react.verticles.WebApp.java

@Override
public void start(final Future<Void> fut) {

    HttpServer server = vertx.createHttpServer();
    Router router = Router.router(vertx);

    //routes /assets/js to webroot/js
    router.route("/assets/*").handler(StaticHandler.create());

    //routes//  ww w .  j  a  v a  2s.c  o  m
    SockJSHandlerOptions options = new SockJSHandlerOptions();
    options.setHeartbeatInterval(30000);
    SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);
    BridgeOptions bOptions = new BridgeOptions();
    bOptions.addInboundPermitted(new PermittedOptions().setAddress("incoming"));
    bOptions.addOutboundPermitted(new PermittedOptions().setAddress("incoming"));
    sockJSHandler.bridge(bOptions);

    router.route("/eventbus/*").handler(sockJSHandler);

    //routes root to index.html and not found to custom 404 error.
    router.route("/*").handler(StaticHandler.create().setIndexPage("index.html"))
            .failureHandler(routingContext -> {
                HttpServerResponse response = routingContext.response();
                response.putHeader("content-type", "text/html");
                response.setStatusCode(404);
                response.sendFile("webroot/404.html");
                response.close();
            });

    server.requestHandler(router::accept).listen(config().getInteger("http.port", 8080), result -> {
        if (result.succeeded()) {
            fut.complete();
            log.info("Http Server started on port {0}", config().getInteger("http.port", 8080).toString());
        } else {
            fut.fail(result.cause());
        }
    });
}