Search in sources :

Example 41 with FileSystem

use of io.vertx.core.file.FileSystem in project vertx-examples by vert-x3.

the class Client method start.

@Override
public void start() throws Exception {
    String filename = "upload.txt";
    FileSystem fs = vertx.fileSystem();
    WebClient client = WebClient.create(vertx);
    fs.props(filename, ares -> {
        FileProps props = ares.result();
        System.out.println("props is " + props);
        long size = props.size();
        HttpRequest<Buffer> req = client.put(8080, "localhost", "/");
        req.putHeader("content-length", "" + size);
        fs.open(filename, new OpenOptions(), ares2 -> {
            req.sendStream(ares2.result(), ar -> {
                if (ar.succeeded()) {
                    HttpResponse<Buffer> response = ar.result();
                    System.out.println("Got HTTP response with status " + response.statusCode());
                } else {
                    ar.cause().printStackTrace();
                }
            });
        });
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) OpenOptions(io.vertx.core.file.OpenOptions) FileSystem(io.vertx.core.file.FileSystem) WebClient(io.vertx.ext.web.client.WebClient) FileProps(io.vertx.core.file.FileProps)

Example 42 with FileSystem

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

the class StaticHandlerImpl method handle.

@Override
public void handle(RoutingContext context) {
    HttpServerRequest request = context.request();
    if (request.method() != HttpMethod.GET && request.method() != HttpMethod.HEAD) {
        if (LOG.isTraceEnabled())
            LOG.trace("Not GET or HEAD so ignoring request");
        context.next();
    } else {
        // decode URL path
        String uriDecodedPath = URIDecoder.decodeURIComponent(context.normalizedPath(), false);
        // if the normalized path is null it cannot be resolved
        if (uriDecodedPath == null) {
            LOG.warn("Invalid path: " + context.request().path());
            context.next();
            return;
        }
        // will normalize and handle all paths as UNIX paths
        String path = HttpUtils.removeDots(uriDecodedPath.replace('\\', '/'));
        // Access fileSystem once here to be safe
        FileSystem fs = context.vertx().fileSystem();
        sendStatic(context, fs, path, // identified as such.
        !directoryListing && "/".equals(path));
    }
}
Also used : HttpServerRequest(io.vertx.core.http.HttpServerRequest) FileSystem(io.vertx.core.file.FileSystem)

Example 43 with FileSystem

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

the class StaticHandlerImpl method sendFile.

private void sendFile(RoutingContext context, FileSystem fileSystem, String file, FileProps fileProps) {
    final HttpServerRequest request = context.request();
    final HttpServerResponse response = context.response();
    Long offset = null;
    Long end = null;
    MultiMap headers = null;
    if (response.closed())
        return;
    if (rangeSupport) {
        // check if the client is making a range request
        String range = request.getHeader("Range");
        // end byte is length - 1
        end = fileProps.size() - 1;
        if (range != null) {
            Matcher m = RANGE.matcher(range);
            if (m.matches()) {
                try {
                    String part = m.group(1);
                    // offset cannot be empty
                    offset = Long.parseLong(part);
                    // offset must fall inside the limits of the file
                    if (offset < 0 || offset >= fileProps.size()) {
                        throw new IndexOutOfBoundsException();
                    }
                    // length can be empty
                    part = m.group(2);
                    if (part != null && part.length() > 0) {
                        // ranges are inclusive
                        end = Math.min(end, Long.parseLong(part));
                        // end offset must not be smaller than start offset
                        if (end < offset) {
                            throw new IndexOutOfBoundsException();
                        }
                    }
                } catch (NumberFormatException | IndexOutOfBoundsException e) {
                    context.response().putHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + fileProps.size());
                    context.fail(REQUESTED_RANGE_NOT_SATISFIABLE.code());
                    return;
                }
            }
        }
        // notify client we support range requests
        headers = response.headers();
        headers.set(HttpHeaders.ACCEPT_RANGES, "bytes");
        // send the content length even for HEAD requests
        headers.set(HttpHeaders.CONTENT_LENGTH, Long.toString(end + 1 - (offset == null ? 0 : offset)));
    }
    writeCacheHeaders(request, fileProps);
    if (request.method() == HttpMethod.HEAD) {
        response.end();
    } else {
        if (rangeSupport && offset != null) {
            // must return content range
            headers.set(HttpHeaders.CONTENT_RANGE, "bytes " + offset + "-" + end + "/" + fileProps.size());
            // return a partial response
            response.setStatusCode(PARTIAL_CONTENT.code());
            final long finalOffset = offset;
            final long finalLength = end + 1 - offset;
            // guess content type
            String contentType = MimeMapping.getMimeTypeForFilename(file);
            if (contentType != null) {
                if (contentType.startsWith("text")) {
                    response.putHeader(HttpHeaders.CONTENT_TYPE, contentType + ";charset=" + defaultContentEncoding);
                } else {
                    response.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
                }
            }
            response.sendFile(file, finalOffset, finalLength, res2 -> {
                if (res2.failed()) {
                    context.fail(res2.cause());
                }
            });
        } else {
            // guess content type
            String extension = getFileExtension(file);
            String contentType = MimeMapping.getMimeTypeForExtension(extension);
            if (compressedMediaTypes.contains(contentType) || compressedFileSuffixes.contains(extension)) {
                response.putHeader(HttpHeaders.CONTENT_ENCODING, HttpHeaders.IDENTITY);
            }
            if (contentType != null) {
                if (contentType.startsWith("text")) {
                    response.putHeader(HttpHeaders.CONTENT_TYPE, contentType + ";charset=" + defaultContentEncoding);
                } else {
                    response.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
                }
            }
            // http2 pushing support
            if (request.version() == HttpVersion.HTTP_2 && http2PushMappings != null) {
                for (Http2PushMapping dependency : http2PushMappings) {
                    if (!dependency.isNoPush()) {
                        final String dep = webRoot + "/" + dependency.getFilePath();
                        // get the file props
                        getFileProps(fileSystem, dep, filePropsAsyncResult -> {
                            if (filePropsAsyncResult.succeeded()) {
                                // push
                                writeCacheHeaders(request, filePropsAsyncResult.result());
                                response.push(HttpMethod.GET, "/" + dependency.getFilePath(), pushAsyncResult -> {
                                    if (pushAsyncResult.succeeded()) {
                                        HttpServerResponse res = pushAsyncResult.result();
                                        final String depContentType = MimeMapping.getMimeTypeForExtension(file);
                                        if (depContentType != null) {
                                            if (depContentType.startsWith("text")) {
                                                res.putHeader(HttpHeaders.CONTENT_TYPE, contentType + ";charset=" + defaultContentEncoding);
                                            } else {
                                                res.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
                                            }
                                        }
                                        res.sendFile(webRoot + "/" + dependency.getFilePath());
                                    }
                                });
                            }
                        });
                    }
                }
            } else if (http2PushMappings != null) {
                // Link preload when file push is not supported
                List<String> links = new ArrayList<>();
                for (Http2PushMapping dependency : http2PushMappings) {
                    final String dep = webRoot + "/" + dependency.getFilePath();
                    // get the file props
                    getFileProps(fileSystem, dep, filePropsAsyncResult -> {
                        if (filePropsAsyncResult.succeeded()) {
                            // push
                            writeCacheHeaders(request, filePropsAsyncResult.result());
                            links.add("<" + dependency.getFilePath() + ">; rel=preload; as=" + dependency.getExtensionTarget() + (dependency.isNoPush() ? "; nopush" : ""));
                        }
                    });
                }
                response.putHeader("Link", links);
            }
            response.sendFile(file, res2 -> {
                if (res2.failed()) {
                    context.fail(res2.cause());
                }
            });
        }
    }
}
Also used : URIDecoder(io.vertx.core.net.impl.URIDecoder) Arrays(java.util.Arrays) HttpServerRequest(io.vertx.core.http.HttpServerRequest) FORBIDDEN(io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) FileSystemAccess(io.vertx.ext.web.handler.FileSystemAccess) MultiMap(io.vertx.core.MultiMap) MIMEHeader(io.vertx.ext.web.MIMEHeader) RoutingContext(io.vertx.ext.web.RoutingContext) ArrayList(java.util.ArrayList) FileProps(io.vertx.core.file.FileProps) HashSet(java.util.HashSet) Matcher(java.util.regex.Matcher) Utils(io.vertx.ext.web.impl.Utils) Charset(java.nio.charset.Charset) HttpVersion(io.vertx.core.http.HttpVersion) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) LRUCache(io.vertx.ext.web.impl.LRUCache) Logger(io.vertx.core.impl.logging.Logger) StaticHandler(io.vertx.ext.web.handler.StaticHandler) PARTIAL_CONTENT(io.netty.handler.codec.http.HttpResponseStatus.PARTIAL_CONTENT) Collection(java.util.Collection) Set(java.util.Set) HttpHeaders(io.vertx.core.http.HttpHeaders) ParsableMIMEValue(io.vertx.ext.web.impl.ParsableMIMEValue) MimeMapping(io.vertx.core.http.impl.MimeMapping) Future(io.vertx.core.Future) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) JsonArray(io.vertx.core.json.JsonArray) NOT_MODIFIED(io.netty.handler.codec.http.HttpResponseStatus.NOT_MODIFIED) List(java.util.List) Http2PushMapping(io.vertx.ext.web.Http2PushMapping) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerResponse(io.vertx.core.http.HttpServerResponse) FileSystem(io.vertx.core.file.FileSystem) HttpUtils(io.vertx.core.http.impl.HttpUtils) REQUESTED_RANGE_NOT_SATISFIABLE(io.netty.handler.codec.http.HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE) Pattern(java.util.regex.Pattern) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Matcher(java.util.regex.Matcher) HttpServerRequest(io.vertx.core.http.HttpServerRequest) MultiMap(io.vertx.core.MultiMap) Http2PushMapping(io.vertx.ext.web.Http2PushMapping) HttpServerResponse(io.vertx.core.http.HttpServerResponse) ArrayList(java.util.ArrayList) List(java.util.List)

Example 44 with FileSystem

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

the class AuthenticatorStore method testServerForFIDO2TCK.

@Test(timeout = 300_000)
@Ignore("This test needs to be executed manually against the Conformance Tools")
public void testServerForFIDO2TCK(TestContext should) {
    final Async test = should.async();
    final Vertx vertx = rule.vertx();
    final FileSystem fs = vertx.fileSystem();
    // clear the DB at each run to avoid previous state
    database.clear();
    final WebAuthnOptions config = new WebAuthnOptions().setRelyingParty(new RelyingParty().setName("Vert.x Conformance Test 4.2.0")).putRootCertificate("mds", MDS3_ROOT_CERTIFICATE).addRootCrl(MDS3_MDSCA_1_CRL);
    // create the webauthn security object
    WebAuthn webAuthN = WebAuthn.create(vertx, config).authenticatorFetcher(database::fetcher).authenticatorUpdater(database::updater);
    // do we want to load custom metadata statements?
    if (fs.existsBlocking("metadataStatements")) {
        for (String f : fs.readDirBlocking("metadataStatements")) {
            System.out.println("Loading metadata statement: " + f);
            webAuthN.metaDataService().addStatement(new JsonObject(fs.readFileBlocking(f)));
        }
    } else {
        should.fail("test metadata statements are not in the filesystem!");
        return;
    }
    List<Future> futures = new ArrayList<>();
    // do we want to load custom MDS3 servers?
    for (String el : MDS3) {
        System.out.println("Loading toc: " + el);
        futures.add(webAuthN.metaDataService().fetchTOC(el));
    }
    CompositeFuture.all(futures).onFailure(should::fail).onSuccess(done -> {
        final Router app = Router.router(vertx);
        // parse the BODY
        app.post().handler(BodyHandler.create());
        // add a session handler
        app.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
        app.post("/attestation/options").handler(ctx -> {
            JsonObject json = ctx.getBodyAsJson();
            // vert.x doesn't work with "username" but "name"
            if (json.containsKey("username")) {
                String username = json.getString("username");
                json.remove("username");
                json.put("name", username);
                // patch the request
                ctx.setBody(json.toBuffer());
            }
            // register, we need to listen to the request and change the config
            JsonObject authenticatorSelection = json.getJsonObject("authenticatorSelection");
            if (authenticatorSelection != null) {
                if (authenticatorSelection.containsKey("requireResidentKey")) {
                    config.setRequireResidentKey(authenticatorSelection.getBoolean("requireResidentKey"));
                }
                if (authenticatorSelection.containsKey("authenticatorAttachment")) {
                    config.setAuthenticatorAttachment(AuthenticatorAttachment.of(authenticatorSelection.getString("authenticatorAttachment")));
                }
                if (authenticatorSelection.containsKey("userVerification")) {
                    config.setUserVerification(UserVerification.of(authenticatorSelection.getString("userVerification")));
                }
            }
            config.setAttestation(Attestation.of(json.getString("attestation")));
            config.setExtensions(json.getJsonObject("extensions"));
            ctx.next();
        });
        app.post("/attestation/result").handler(ctx -> {
            ctx.reroute("/callback");
        });
        app.post("/assertion/options").handler(ctx -> {
            JsonObject json = ctx.getBodyAsJson();
            // vert.x doesn't work with "username" but "name"
            if (json.containsKey("username")) {
                String username = json.getString("username");
                json.remove("username");
                json.put("name", username);
                // patch the request
                ctx.setBody(json.toBuffer());
            }
            config.setUserVerification(UserVerification.of(json.getString("userVerification", "discouraged")));
            config.setExtensions(json.getJsonObject("extensions"));
            ctx.next();
        });
        app.post("/assertion/result").handler(ctx -> {
            ctx.reroute("/callback");
        });
        // security handler
        WebAuthnHandler webAuthnHandler = WebAuthnHandler.create(webAuthN).setOrigin(ORIGIN).setupCallback(app.post("/callback")).setupCredentialsCreateCallback(app.post("/attestation/options")).setupCredentialsGetCallback(app.post("/assertion/options"));
        // secure the remaining routes
        app.route().handler(webAuthnHandler);
        // failure handler to comply to conformance test requirements
        app.route().failureHandler(ctx -> {
            ctx.failure().printStackTrace();
            ctx.response().setStatusCode(500);
            ctx.json(new JsonObject().put("status", "failed").put("errorMessage", ctx.failure().getMessage()));
        });
        vertx.createHttpServer().requestHandler(app).listen(8080, "0.0.0.0").onFailure(should::fail).onSuccess(v -> {
            System.out.printf("Server listening at: %s%n", ORIGIN);
            System.out.println("-----------------------------------");
            System.out.println("Run the FIDO2 Conformance tool now!");
            System.out.println("-----------------------------------");
        });
    });
}
Also used : ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Router(io.vertx.ext.web.Router) Vertx(io.vertx.core.Vertx) WebAuthnHandler(io.vertx.ext.web.handler.WebAuthnHandler) Async(io.vertx.ext.unit.Async) FileSystem(io.vertx.core.file.FileSystem) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

FileSystem (io.vertx.core.file.FileSystem)44 Buffer (io.vertx.core.buffer.Buffer)22 Vertx (io.vertx.core.Vertx)21 JsonObject (io.vertx.core.json.JsonObject)21 Future (io.vertx.core.Future)19 Handler (io.vertx.core.Handler)19 Context (io.vertx.core.Context)18 EventBus (io.vertx.core.eventbus.EventBus)18 TestContext (io.vertx.ext.unit.TestContext)18 Before (org.junit.Before)18 Test (org.junit.Test)17 Async (io.vertx.ext.unit.Async)16 StandardCharsets (java.nio.charset.StandardCharsets)16 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)15 HttpURLConnection (java.net.HttpURLConnection)15 Constants (org.eclipse.hono.util.Constants)15 CoreMatchers.is (org.hamcrest.CoreMatchers.is)15 Assert.assertThat (org.junit.Assert.assertThat)15 RunWith (org.junit.runner.RunWith)15 Mockito (org.mockito.Mockito)15