Search in sources :

Example 26 with AsyncFile

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

the class HttpUtils method resolveFile.

static void resolveFile(VertxInternal vertx, String filename, long offset, long length, Handler<AsyncResult<AsyncFile>> resultHandler) {
    File file_ = vertx.resolveFile(filename);
    if (!file_.exists()) {
        resultHandler.handle(Future.failedFuture(new FileNotFoundException()));
        return;
    }
    // i.e is not a directory
    try (RandomAccessFile raf = new RandomAccessFile(file_, "r")) {
        FileSystem fs = vertx.fileSystem();
        fs.open(filename, new OpenOptions().setCreate(false).setWrite(false), ar -> {
            if (ar.succeeded()) {
                AsyncFile file = ar.result();
                long contentLength = Math.min(length, file_.length() - offset);
                file.setReadPos(offset);
                file.setReadLength(contentLength);
            }
            resultHandler.handle(ar);
        });
    } catch (IOException e) {
        resultHandler.handle(Future.failedFuture(e));
    }
}
Also used : OpenOptions(io.vertx.core.file.OpenOptions) RandomAccessFile(java.io.RandomAccessFile) FileSystem(io.vertx.core.file.FileSystem) FileNotFoundException(java.io.FileNotFoundException) AsyncFile(io.vertx.core.file.AsyncFile) IOException(java.io.IOException) AsyncFile(io.vertx.core.file.AsyncFile) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 27 with AsyncFile

use of io.vertx.core.file.AsyncFile in project java-chassis by ServiceComb.

the class ReadStreamPart method onFileOpened.

protected void onFileOpened(File file, AsyncResult<AsyncFile> ar, CompletableFuture<File> future) {
    if (ar.failed()) {
        future.completeExceptionally(ar.cause());
        return;
    }
    AsyncFile asyncFile = ar.result();
    CompletableFuture<Void> saveFuture = saveToWriteStream(asyncFile);
    saveFuture.whenComplete((v, saveException) -> {
        asyncFile.close(closeAr -> {
            if (closeAr.failed()) {
                LOGGER.error("Failed to close file {}.", file);
            }
            // result just only related to write
            if (saveException == null) {
                future.complete(file);
                return;
            }
            future.completeExceptionally(saveException);
        });
    });
}
Also used : AsyncFile(io.vertx.core.file.AsyncFile)

Example 28 with AsyncFile

use of io.vertx.core.file.AsyncFile in project incubator-servicecomb-java-chassis by apache.

the class ReadStreamPart method onFileOpened.

protected void onFileOpened(File file, AsyncResult<AsyncFile> ar, CompletableFuture<File> future) {
    if (ar.failed()) {
        future.completeExceptionally(ar.cause());
        return;
    }
    AsyncFile asyncFile = ar.result();
    CompletableFuture<Void> saveFuture = saveToWriteStream(asyncFile);
    saveFuture.whenComplete((v, saveException) -> {
        asyncFile.close(closeAr -> {
            if (closeAr.failed()) {
                LOGGER.error("Failed to close file {}.", file);
            }
            // result just only related to write
            if (saveException == null) {
                future.complete(file);
                return;
            }
            future.completeExceptionally(saveException);
        });
    });
}
Also used : AsyncFile(io.vertx.core.file.AsyncFile)

Example 29 with AsyncFile

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

the class WebClientTest method testRequestWithBody.

private void testRequestWithBody(HttpMethod method, boolean chunked) throws Exception {
    String expected = TestUtils.randomAlphaString(1024 * 1024);
    File f = File.createTempFile("vertx", ".data");
    f.deleteOnExit();
    Files.write(f.toPath(), expected.getBytes(StandardCharsets.UTF_8));
    waitFor(2);
    server.requestHandler(req -> req.bodyHandler(buff -> {
        assertEquals(method, req.method());
        assertEquals(Buffer.buffer(expected), buff);
        complete();
        req.response().end();
    }));
    startServer();
    vertx.runOnContext(v -> {
        AsyncFile asyncFile = vertx.fileSystem().openBlocking(f.getAbsolutePath(), new OpenOptions());
        HttpRequest<Buffer> builder = null;
        switch(method.name()) {
            case "POST":
                builder = webClient.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
                break;
            case "PUT":
                builder = webClient.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
                break;
            case "PATCH":
                builder = webClient.patch(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
                break;
            default:
                fail("Invalid HTTP method");
        }
        if (!chunked) {
            builder = builder.putHeader("Content-Length", "" + expected.length());
        }
        builder.sendStream(asyncFile, onSuccess(resp -> {
            assertEquals(200, resp.statusCode());
            complete();
        }));
    });
    await();
}
Also used : 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) OpenOptions(io.vertx.core.file.OpenOptions) Buffer(io.vertx.core.buffer.Buffer) AsyncFile(io.vertx.core.file.AsyncFile) AsyncFile(io.vertx.core.file.AsyncFile) File(java.io.File)

Example 30 with AsyncFile

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

the class SessionAwareWebClientTest method testSendRequest.

@Test
public void testSendRequest(TestContext context) throws IOException {
    AtomicInteger count = new AtomicInteger(0);
    client = buildClient(plainWebClient, new CookieStoreImpl() {

        @Override
        public CookieStore put(Cookie cookie) {
            count.incrementAndGet();
            return super.put(cookie);
        }
    });
    String encodedCookie = ServerCookieEncoder.STRICT.encode(new DefaultCookie("a", "1"));
    prepareServer(context, req -> {
        req.response().headers().add("set-cookie", encodedCookie);
    });
    int expected = 7;
    Async async = context.async(expected);
    Handler<AsyncResult<HttpResponse<Buffer>>> handler = ar -> {
        async.countDown();
    };
    HttpRequest<Buffer> req = client.post("/");
    req.send(handler);
    req.sendBuffer(Buffer.buffer(), handler);
    req.sendForm(HttpHeaders.set("a", "b"), handler);
    req.sendJson("", handler);
    req.sendJsonObject(new JsonObject(), handler);
    req.sendMultipartForm(MultipartForm.create().attribute("a", "b"), handler);
    File f = File.createTempFile("vertx", ".tmp");
    f.deleteOnExit();
    AsyncFile asyncFile = vertx.fileSystem().openBlocking(f.getAbsolutePath(), new OpenOptions());
    req.sendStream(asyncFile, handler);
    async.await();
    asyncFile.close();
    context.assertEquals(expected, count.get());
}
Also used : Cookie(io.netty.handler.codec.http.cookie.Cookie) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) Buffer(io.vertx.core.buffer.Buffer) IntStream(java.util.stream.IntStream) TestContext(io.vertx.ext.unit.TestContext) AsyncFile(io.vertx.core.file.AsyncFile) Async(io.vertx.ext.unit.Async) RunWith(org.junit.runner.RunWith) ArrayList(java.util.ArrayList) MultipartForm(io.vertx.ext.web.multipart.MultipartForm) ServerCookieDecoder(io.netty.handler.codec.http.cookie.ServerCookieDecoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) CookieStore(io.vertx.ext.web.client.spi.CookieStore) Before(org.junit.Before) OpenOptions(io.vertx.core.file.OpenOptions) Vertx(io.vertx.core.Vertx) Set(java.util.Set) IOException(java.io.IOException) Test(org.junit.Test) Verticle(io.vertx.core.Verticle) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Cookie(io.netty.handler.codec.http.cookie.Cookie) File(java.io.File) io.vertx.core.http(io.vertx.core.http) Consumer(java.util.function.Consumer) List(java.util.List) Ignore(org.junit.Ignore) Buffer(io.vertx.core.buffer.Buffer) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) CookieStoreImpl(io.vertx.ext.web.client.impl.CookieStoreImpl) AbstractVerticle(io.vertx.core.AbstractVerticle) Handler(io.vertx.core.Handler) Assert.assertEquals(org.junit.Assert.assertEquals) ServerCookieEncoder(io.netty.handler.codec.http.cookie.ServerCookieEncoder) OpenOptions(io.vertx.core.file.OpenOptions) CookieStoreImpl(io.vertx.ext.web.client.impl.CookieStoreImpl) JsonObject(io.vertx.core.json.JsonObject) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Async(io.vertx.ext.unit.Async) AsyncFile(io.vertx.core.file.AsyncFile) AsyncResult(io.vertx.core.AsyncResult) AsyncFile(io.vertx.core.file.AsyncFile) File(java.io.File) Test(org.junit.Test)

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