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();
}
});
});
});
}
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));
}
}
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());
}
});
}
}
}
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("-----------------------------------");
});
});
}
Aggregations