Search in sources :

Example 1 with HttpServerResponse

use of io.vertx.core.http.HttpServerResponse in project vert.x by eclipse.

the class Http2ServerResponseImpl method sendFile.

@Override
public HttpServerResponse sendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
    synchronized (conn) {
        checkEnded();
        Context resultCtx = resultHandler != null ? stream.vertx.getOrCreateContext() : null;
        File file = stream.vertx.resolveFile(filename);
        if (!file.exists()) {
            if (resultHandler != null) {
                resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(new FileNotFoundException())));
            } else {
                log.error("File not found: " + filename);
            }
            return this;
        }
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");
        } catch (IOException e) {
            if (resultHandler != null) {
                resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(e)));
            } else {
                log.error("Failed to send file", e);
            }
            return this;
        }
        long contentLength = Math.min(length, file.length() - offset);
        if (headers.get(HttpHeaderNames.CONTENT_LENGTH) == null) {
            putHeader(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(contentLength));
        }
        if (headers.get(HttpHeaderNames.CONTENT_TYPE) == null) {
            String contentType = MimeMapping.getMimeTypeForFilename(filename);
            if (contentType != null) {
                putHeader(HttpHeaderNames.CONTENT_TYPE, contentType);
            }
        }
        checkSendHeaders(false);
        FileStreamChannel fileChannel = new FileStreamChannel(ar -> {
            if (ar.succeeded()) {
                bytesWritten += ar.result();
                end();
            }
            if (resultHandler != null) {
                resultCtx.runOnContext(v -> {
                    resultHandler.handle(Future.succeededFuture());
                });
            }
        }, stream, offset, contentLength);
        drainHandler(fileChannel.drainHandler);
        ctx.channel().eventLoop().register(fileChannel);
        fileChannel.pipeline().fireUserEventTriggered(raf);
    }
    return this;
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) RandomAccessFile(java.io.RandomAccessFile) MultiMap(io.vertx.core.MultiMap) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) IOException(java.io.IOException) Context(io.vertx.core.Context) Future(io.vertx.core.Future) LoggerFactory(io.vertx.core.logging.LoggerFactory) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Unpooled(io.netty.buffer.Unpooled) Nullable(io.vertx.codegen.annotations.Nullable) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Buffer(io.vertx.core.buffer.Buffer) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) StreamResetException(io.vertx.core.http.StreamResetException) RandomAccessFile(java.io.RandomAccessFile) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 2 with HttpServerResponse

use of io.vertx.core.http.HttpServerResponse in project vert.x by eclipse.

the class HTTP2Examples method example6.

public void example6(HttpServerRequest request) {
    HttpServerResponse response = request.response();
    // Push main.js to the client
    response.push(HttpMethod.GET, "/main.js", ar -> {
        if (ar.succeeded()) {
            HttpServerResponse pushedResponse = ar.result();
            pushedResponse.putHeader("content-type", "application/json").end("alert(\"Push response hello\")");
        } else {
            System.out.println("Could not push client resource " + ar.cause());
        }
    });
    // Send the requested resource
    response.sendFile("<html><head><script src=\"/main.js\"></script></head><body></body></html>");
}
Also used : HttpServerResponse(io.vertx.core.http.HttpServerResponse)

Example 3 with HttpServerResponse

use of io.vertx.core.http.HttpServerResponse in project vert.x by eclipse.

the class CoreExamples method example4.

public void example4(HttpServerRequest request) {
    HttpServerResponse response = request.response();
    response.putHeader("Content-Type", "text/plain");
    response.write("some text");
    response.end();
}
Also used : HttpServerResponse(io.vertx.core.http.HttpServerResponse)

Example 4 with HttpServerResponse

use of io.vertx.core.http.HttpServerResponse in project vert.x by eclipse.

the class Http2ClientTest method testPushPromise.

@Test
public void testPushPromise() throws Exception {
    waitFor(2);
    server.requestHandler(req -> {
        req.response().push(HttpMethod.GET, "/wibble?a=b", ar -> {
            assertTrue(ar.succeeded());
            HttpServerResponse response = ar.result();
            response.end("the_content");
        }).end();
    });
    startServer();
    AtomicReference<Context> ctx = new AtomicReference<>();
    HttpClientRequest req = client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
        Context current = Vertx.currentContext();
        if (ctx.get() == null) {
            ctx.set(current);
        } else {
            assertEquals(ctx.get(), current);
        }
        resp.endHandler(v -> {
            complete();
        });
    });
    req.pushHandler(pushedReq -> {
        Context current = Vertx.currentContext();
        if (ctx.get() == null) {
            ctx.set(current);
        } else {
            assertEquals(ctx.get(), current);
        }
        assertOnIOContext(current);
        assertEquals(HttpMethod.GET, pushedReq.method());
        assertEquals("/wibble?a=b", pushedReq.uri());
        assertEquals("/wibble", pushedReq.path());
        assertEquals("a=b", pushedReq.query());
        pushedReq.handler(resp -> {
            assertEquals(200, resp.statusCode());
            Buffer content = Buffer.buffer();
            resp.handler(content::appendBuffer);
            resp.endHandler(v -> {
                complete();
            });
        });
    });
    req.end();
    await();
}
Also used : Arrays(java.util.Arrays) JksOptions(io.vertx.core.net.JksOptions) BiFunction(java.util.function.BiFunction) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) AsciiString(io.netty.util.AsciiString) Cert(io.vertx.test.core.tls.Cert) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) StreamResetException(io.vertx.core.http.StreamResetException) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Http2FrameListener(io.netty.handler.codec.http2.Http2FrameListener) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) io.vertx.core(io.vertx.core) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) ConnectException(java.net.ConnectException) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) SocketAddress(io.vertx.core.net.SocketAddress) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2ServerUpgradeCodec(io.netty.handler.codec.http2.Http2ServerUpgradeCodec) HttpMethod(io.vertx.core.http.HttpMethod) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Buffer(io.vertx.core.buffer.Buffer) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpServerResponse(io.vertx.core.http.HttpServerResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 5 with HttpServerResponse

use of io.vertx.core.http.HttpServerResponse in project vert.x by eclipse.

the class Http2ClientTest method testResponseBody.

private void testResponseBody(String expected) throws Exception {
    server.requestHandler(req -> {
        HttpServerResponse resp = req.response();
        resp.end(expected);
    });
    startServer();
    client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
        AtomicInteger count = new AtomicInteger();
        Buffer content = Buffer.buffer();
        resp.handler(buff -> {
            content.appendBuffer(buff);
            count.incrementAndGet();
        });
        resp.endHandler(v -> {
            assertTrue(count.get() > 0);
            assertEquals(expected, content.toString());
            testComplete();
        });
    }).exceptionHandler(err -> fail()).end();
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Arrays(java.util.Arrays) JksOptions(io.vertx.core.net.JksOptions) BiFunction(java.util.function.BiFunction) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) AsciiString(io.netty.util.AsciiString) Cert(io.vertx.test.core.tls.Cert) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) StreamResetException(io.vertx.core.http.StreamResetException) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Http2FrameListener(io.netty.handler.codec.http2.Http2FrameListener) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) io.vertx.core(io.vertx.core) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) ConnectException(java.net.ConnectException) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) SocketAddress(io.vertx.core.net.SocketAddress) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2ServerUpgradeCodec(io.netty.handler.codec.http2.Http2ServerUpgradeCodec) HttpMethod(io.vertx.core.http.HttpMethod) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpServerResponse(io.vertx.core.http.HttpServerResponse)

Aggregations

HttpServerResponse (io.vertx.core.http.HttpServerResponse)37 Test (org.junit.Test)29 Buffer (io.vertx.core.buffer.Buffer)20 HttpClientRequest (io.vertx.core.http.HttpClientRequest)20 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)19 HttpClientOptions (io.vertx.core.http.HttpClientOptions)17 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)16 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)16 HttpMethod (io.vertx.core.http.HttpMethod)15 HttpServerOptions (io.vertx.core.http.HttpServerOptions)15 NetSocket (io.vertx.core.net.NetSocket)14 TimeUnit (java.util.concurrent.TimeUnit)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)14 ChannelFuture (io.netty.channel.ChannelFuture)13 HttpConnection (io.vertx.core.http.HttpConnection)13 HttpVersion (io.vertx.core.http.HttpVersion)13 TestUtils.assertIllegalStateException (io.vertx.test.core.TestUtils.assertIllegalStateException)13 ArrayList (java.util.ArrayList)13 Collections (java.util.Collections)13 List (java.util.List)13