Search in sources :

Example 11 with AsyncFile

use of io.vertx.core.file.AsyncFile in project vert.x by eclipse.

the class Http2ServerResponse method sendFile.

@Override
public HttpServerResponse sendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
    synchronized (conn) {
        checkValid();
    }
    Handler<AsyncResult<Void>> h;
    if (resultHandler != null) {
        Context resultCtx = stream.vertx.getOrCreateContext();
        h = ar -> {
            resultCtx.runOnContext((v) -> {
                resultHandler.handle(ar);
            });
        };
    } else {
        h = ar -> {
        };
    }
    HttpUtils.resolveFile(stream.vertx, filename, offset, length, ar -> {
        if (ar.succeeded()) {
            AsyncFile file = ar.result();
            long contentLength = Math.min(length, file.getReadLength());
            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);
            file.pipeTo(this, ar1 -> file.close(ar2 -> {
                Throwable failure = ar1.failed() ? ar1.cause() : ar2.failed() ? ar2.cause() : null;
                if (failure == null)
                    h.handle(ar1);
                else
                    h.handle(Future.failedFuture(failure));
            }));
        } else {
            h.handle(ar.mapEmpty());
        }
    });
    return this;
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AsyncFile(io.vertx.core.file.AsyncFile) MultiMap(io.vertx.core.MultiMap) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) Context(io.vertx.core.Context) Unpooled(io.netty.buffer.Unpooled) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Http2HeadersAdaptor(io.vertx.core.http.impl.headers.Http2HeadersAdaptor) ByteBuf(io.netty.buffer.ByteBuf) HttpStatusClass(io.netty.handler.codec.http.HttpStatusClass) ReadStream(io.vertx.core.streams.ReadStream) AsyncResult(io.vertx.core.AsyncResult) StreamResetException(io.vertx.core.http.StreamResetException) SET_COOKIE(io.vertx.core.http.HttpHeaders.SET_COOKIE) StreamPriority(io.vertx.core.http.StreamPriority) HttpResponse(io.vertx.core.spi.observability.HttpResponse) Promise(io.vertx.core.Promise) HttpHeaders(io.vertx.core.http.HttpHeaders) Set(java.util.Set) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Future(io.vertx.core.Future) Nullable(io.vertx.codegen.annotations.Nullable) 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) Handler(io.vertx.core.Handler) Cookie(io.vertx.core.http.Cookie) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) NetSocket(io.vertx.core.net.NetSocket) AsyncFile(io.vertx.core.file.AsyncFile) AsyncResult(io.vertx.core.AsyncResult)

Example 12 with AsyncFile

use of io.vertx.core.file.AsyncFile in project vertx-web by vert-x3.

the class WebClientTest method testAsyncFileResponseBodyStream.

@Test
public void testAsyncFileResponseBodyStream() throws Exception {
    server.requestHandler(req -> {
        HttpServerResponse resp = req.response();
        resp.end(TestUtils.randomBuffer(1024 * 1024));
    });
    startServer();
    AtomicLong received = new AtomicLong();
    AtomicBoolean closed = new AtomicBoolean();
    AsyncFile file = new AsyncFile() {

        public Future<Void> write(Buffer buffer, long position) {
            throw new UnsupportedOperationException();
        }

        public Future<Buffer> read(Buffer buffer, int offset, long position, int length) {
            throw new UnsupportedOperationException();
        }

        public AsyncFile handler(Handler<Buffer> handler) {
            throw new UnsupportedOperationException();
        }

        public AsyncFile pause() {
            throw new UnsupportedOperationException();
        }

        public AsyncFile resume() {
            throw new UnsupportedOperationException();
        }

        public AsyncFile endHandler(Handler<Void> handler) {
            throw new UnsupportedOperationException();
        }

        public AsyncFile setWriteQueueMaxSize(int i) {
            throw new UnsupportedOperationException();
        }

        public AsyncFile drainHandler(Handler<Void> handler) {
            throw new UnsupportedOperationException();
        }

        public AsyncFile fetch(long l) {
            throw new UnsupportedOperationException();
        }

        public Future<Void> end() {
            return close();
        }

        public void end(Handler<AsyncResult<Void>> handler) {
            close(handler);
        }

        public Future<Void> close() {
            throw new UnsupportedOperationException();
        }

        public void write(Buffer buffer, long l, Handler<AsyncResult<Void>> handler) {
            throw new UnsupportedOperationException();
        }

        public AsyncFile read(Buffer buffer, int i, long l, int i1, Handler<AsyncResult<Buffer>> handler) {
            throw new UnsupportedOperationException();
        }

        public Future<Void> flush() {
            throw new UnsupportedOperationException();
        }

        public AsyncFile flush(Handler<AsyncResult<Void>> handler) {
            throw new UnsupportedOperationException();
        }

        public AsyncFile setReadPos(long l) {
            throw new UnsupportedOperationException();
        }

        public AsyncFile setReadLength(long l) {
            throw new UnsupportedOperationException();
        }

        public long getReadLength() {
            throw new UnsupportedOperationException();
        }

        public AsyncFile setWritePos(long l) {
            throw new UnsupportedOperationException();
        }

        public AsyncFile setReadBufferSize(int i) {
            throw new UnsupportedOperationException();
        }

        public long sizeBlocking() {
            return 0;
        }

        public Future<Long> size() {
            return Future.succeededFuture(0L);
        }

        public AsyncFile exceptionHandler(Handler<Throwable> handler) {
            return this;
        }

        public boolean writeQueueFull() {
            return false;
        }

        public long getWritePos() {
            throw new UnsupportedOperationException();
        }

        public Future<Void> write(Buffer buffer) {
            Promise<Void> promise = Promise.promise();
            write(buffer, promise);
            return promise.future();
        }

        public void write(Buffer buffer, Handler<AsyncResult<Void>> handler) {
            received.addAndGet(buffer.length());
            if (handler != null) {
                handler.handle(Future.succeededFuture());
            }
        }

        public void close(Handler<AsyncResult<Void>> handler) {
            vertx.setTimer(500, id -> {
                closed.set(true);
                handler.handle(Future.succeededFuture());
            });
        }
    };
    HttpRequest<Buffer> get = webClient.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
    get.as(BodyCodec.pipe(file)).send(onSuccess(v -> {
        assertEquals(1024 * 1024, received.get());
        assertTrue(closed.get());
        testComplete();
    }));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) AsyncFile(io.vertx.core.file.AsyncFile) CoreMatchers(org.hamcrest.CoreMatchers) ResponsePredicate(io.vertx.ext.web.client.predicate.ResponsePredicate) java.util(java.util) ErrorConverter(io.vertx.ext.web.client.predicate.ErrorConverter) URLDecoder(java.net.URLDecoder) io.vertx.core(io.vertx.core) DecodeException(io.vertx.core.json.DecodeException) HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) BodyCodec(io.vertx.ext.web.codec.BodyCodec) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ResponsePredicateResult(io.vertx.ext.web.client.predicate.ResponsePredicateResult) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) MultipartForm(io.vertx.ext.web.multipart.MultipartForm) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WriteStream(io.vertx.core.streams.WriteStream) ReadStream(io.vertx.core.streams.ReadStream) BiConsumer(java.util.function.BiConsumer) JsonObject(io.vertx.core.json.JsonObject) ConnectException(java.net.ConnectException) SocketAddress(io.vertx.core.net.SocketAddress) ProxyOptions(io.vertx.core.net.ProxyOptions) UsernamePasswordCredentials(io.vertx.ext.auth.authentication.UsernamePasswordCredentials) OpenOptions(io.vertx.core.file.OpenOptions) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) Test(org.junit.Test) io.vertx.core.http(io.vertx.core.http) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) HtdigestCredentials(io.vertx.ext.auth.htdigest.HtdigestCredentials) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) TokenCredentials(io.vertx.ext.auth.authentication.TokenCredentials) Repeat(io.vertx.test.core.Repeat) URLEncoder(java.net.URLEncoder) Buffer(io.vertx.core.buffer.Buffer) ProxyType(io.vertx.core.net.ProxyType) NetServer(io.vertx.core.net.NetServer) WineAndCheese(io.vertx.ext.web.client.jackson.WineAndCheese) Cert(io.vertx.test.tls.Cert) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicLong(java.util.concurrent.atomic.AtomicLong) AsyncFile(io.vertx.core.file.AsyncFile) Test(org.junit.Test)

Example 13 with AsyncFile

use of io.vertx.core.file.AsyncFile in project vertx-openshift-it by cescoffier.

the class StreamingResultsTest method handle.

@Override
public void handle(RoutingContext rc) {
    jdbcClient.getConnection(ar -> {
        if (ar.failed()) {
            fail(rc, ar.cause());
            return;
        }
        SQLConnection connection = ar.result();
        rc.response().bodyEndHandler(v -> {
            connection.close();
        });
        FileSystem fileSystem = rc.vertx().fileSystem();
        fileSystem.open("db/migration/strings", new OpenOptions(), ores -> {
            if (ores.failed()) {
                fail(rc, ores.cause());
                return;
            }
            AsyncFile asyncFile = ores.result();
            List<String> values = new ArrayList<>();
            RecordParser parser = RecordParser.newDelimited("\n", out -> values.add(out.toString()));
            asyncFile.handler(parser);
            asyncFile.endHandler(v -> {
                asyncFile.close();
                List<String> statements = values.stream().map(value -> "insert into random_string (value) values ('" + value + "')").collect(toList());
                connection.batch(statements, ires -> {
                    if (ires.failed()) {
                        fail(rc, ires.cause());
                        return;
                    }
                    connection.queryStream("select value from random_string", sres -> {
                        if (sres.failed()) {
                            fail(rc, sres.cause());
                            return;
                        }
                        List<String> storedValues = new ArrayList<>(values.size());
                        SQLRowStream rowStream = sres.result();
                        rowStream.handler(row -> {
                            storedValues.add(row.getString(0));
                        }).endHandler(endRows -> {
                            if (!storedValues.equals(values)) {
                                fail(rc, storedValues.toString());
                            } else {
                                rc.response().setStatusCode(200).end();
                            }
                        });
                    });
                });
            });
        });
    });
}
Also used : OpenOptions(io.vertx.core.file.OpenOptions) AsyncFile(io.vertx.core.file.AsyncFile) OpenOptions(io.vertx.core.file.OpenOptions) SQLRowStream(io.vertx.ext.sql.SQLRowStream) RoutingContext(io.vertx.ext.web.RoutingContext) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) TestUtil(io.vertx.openshift.jdbc.TestUtil) List(java.util.List) JDBCClient(io.vertx.ext.jdbc.JDBCClient) FileSystem(io.vertx.core.file.FileSystem) SQLConnection(io.vertx.ext.sql.SQLConnection) RecordParser(io.vertx.core.parsetools.RecordParser) Handler(io.vertx.core.Handler) SQLConnection(io.vertx.ext.sql.SQLConnection) FileSystem(io.vertx.core.file.FileSystem) ArrayList(java.util.ArrayList) RecordParser(io.vertx.core.parsetools.RecordParser) AsyncFile(io.vertx.core.file.AsyncFile) SQLRowStream(io.vertx.ext.sql.SQLRowStream)

Example 14 with AsyncFile

use of io.vertx.core.file.AsyncFile in project vert.x by eclipse.

the class FileSystemExamples method asyncFilePump.

public void asyncFilePump() {
    Vertx vertx = Vertx.vertx();
    final AsyncFile output = vertx.fileSystem().openBlocking("target/classes/plagiary.txt", new OpenOptions());
    vertx.fileSystem().open("target/classes/les_miserables.txt", new OpenOptions(), result -> {
        if (result.succeeded()) {
            AsyncFile file = result.result();
            Pump.pump(file, output).start();
            file.endHandler((r) -> {
                System.out.println("Copy done");
            });
        } else {
            System.err.println("Cannot open file " + result.cause());
        }
    });
}
Also used : OpenOptions(io.vertx.core.file.OpenOptions) AsyncFile(io.vertx.core.file.AsyncFile) Vertx(io.vertx.core.Vertx)

Example 15 with AsyncFile

use of io.vertx.core.file.AsyncFile in project vert.x by eclipse.

the class FileSystemExamples method asyncFileRead.

public void asyncFileRead() {
    Vertx vertx = Vertx.vertx();
    vertx.fileSystem().open("target/classes/les_miserables.txt", new OpenOptions(), result -> {
        if (result.succeeded()) {
            AsyncFile file = result.result();
            Buffer buff = Buffer.buffer(1000);
            for (int i = 0; i < 10; i++) {
                file.read(buff, i * 100, i * 100, 100, ar -> {
                    if (ar.succeeded()) {
                        System.out.println("Read ok!");
                    } else {
                        System.err.println("Failed to write: " + ar.cause());
                    }
                });
            }
        } else {
            System.err.println("Cannot open file " + result.cause());
        }
    });
}
Also used : OpenOptions(io.vertx.core.file.OpenOptions) Buffer(io.vertx.core.buffer.Buffer) AsyncFile(io.vertx.core.file.AsyncFile) Vertx(io.vertx.core.Vertx)

Aggregations

AsyncFile (io.vertx.core.file.AsyncFile)31 OpenOptions (io.vertx.core.file.OpenOptions)26 Buffer (io.vertx.core.buffer.Buffer)19 Handler (io.vertx.core.Handler)10 Test (org.junit.Test)10 Vertx (io.vertx.core.Vertx)9 File (java.io.File)9 AsyncResult (io.vertx.core.AsyncResult)8 FileSystem (io.vertx.core.file.FileSystem)7 List (java.util.List)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 Future (io.vertx.core.Future)6 JsonObject (io.vertx.core.json.JsonObject)6 WriteStream (io.vertx.core.streams.WriteStream)6 IOException (java.io.IOException)6 ReadStream (io.vertx.core.streams.ReadStream)5 FileNotFoundException (java.io.FileNotFoundException)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 JsonArray (io.vertx.core.json.JsonArray)4 TestUtils (io.vertx.test.core.TestUtils)4