private void deleteFileUploads() { for (FileUpload fileUpload : context.fileUploads()) { FileSystem fileSystem = context.vertx().fileSystem(); String uploadedFileName = fileUpload.uploadedFileName(); fileSystem.exists(uploadedFileName, existResult -> { if (existResult.failed()) { LOGGER.warn("Could not detect if uploaded file exists, not deleting: " + uploadedFileName, existResult.cause()); } else if (existResult.result()) { fileSystem.delete(uploadedFileName, deleteResult -> { if (deleteResult.failed()) { LOGGER.warn("Delete of uploaded file failed: " + uploadedFileName, deleteResult.cause()); } }); } }); } }
public static Future<LocalFile> readFile(FileSystem fs, String filefullPathName) { LocalFile localFile = new LocalFile(); return Future.<FileProps>future(future -> { fs.props(filefullPathName, future); }).compose(props -> { localFile.setSize(props.size()); return Future.<AsyncFile>future(future -> { fs.open(filefullPathName, new OpenOptions().setRead(true).setWrite(false).setCreate(false), future); }); }).compose(fileStream -> { localFile.setFile(fileStream); return Future.succeededFuture(localFile); }); }
public void initCache() { if(!initialized.getAndSet(true)) { logger.info("init cache"); FileSystem fileSystem = vertx.fileSystem(); String target = TARGET_DIR + TARGET_FILE; fileSystem.exists(target, result -> { if (!result.result()) { logger.info("downloading wordnet dictionary..."); downloadService.download(target).compose(e -> { compressionService.uncompress(target); loadDictionary(); }, Future.future()); } else { logger.info("wordnet dictionary found."); loadDictionary(); } });; } }
@Override public void start(Future<Void> startFuture) throws Exception { Json.mapper.registerModule(new JavaTimeModule()); FileSystem vertxFileSystem = vertx.fileSystem(); vertxFileSystem.readFile("swagger.json", readFile -> { if (readFile.succeeded()) { Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8"))); Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver()); deployVerticles(startFuture); vertx.createHttpServer() .requestHandler(swaggerRouter::accept) .listen(8080); startFuture.complete(); } else { startFuture.fail(readFile.cause()); } }); }
@BeforeClass public static void startUp() { system = new SystemContext(); PatchContext context = new PatchContext(system) { @Override public String directory() { return testDirectory(); } @Override public FileSystem fileSystem() { return new FileSystemMock(vertx); } }; handler = new PatchHandler(context); }
/** * Creates a file system backed Pairtree object. * * @param aFileSystem A file system * @param aPairtree The object's Pairtree * @param aID The object's ID */ public FsPairtreeObject(final FileSystem aFileSystem, final FsPairtree aPairtree, final String aID) { super(Constants.BUNDLE_NAME); Objects.requireNonNull(aFileSystem); Objects.requireNonNull(aPairtree); Objects.requireNonNull(aID); myPairtreePath = aPairtree.toString(); myPrefix = aPairtree.getPrefix(); myFileSystem = aFileSystem; if (myPrefix == null) { myID = aID; } else { myID = PairtreeUtils.removePrefix(myPrefix, aID); } }
@AfterClass public static void afterClass(TestContext context) { Async after = context.async(); httpServer.close(completionHandler -> { if (completionHandler.succeeded()) { FileSystem vertxFileSystem = vertx.fileSystem(); vertxFileSystem.deleteRecursive(".vertx", true, vertxDir -> { if (vertxDir.succeeded()) { after.complete(); } else { context.fail(vertxDir.cause()); } }); } }); }
@AfterClass public static void afterClass(TestContext context) { Async after = context.async(); httpServer.close(completionHandler -> { if (completionHandler.succeeded()) { FileSystem vertxFileSystem = vertx.fileSystem(); vertxFileSystem.deleteRecursive("file-uploads", true, deletedDir -> { if (deletedDir.succeeded()) { vertxFileSystem.deleteRecursive(".vertx", true, vertxDir -> { if (vertxDir.succeeded()) { after.complete(); } else { context.fail(vertxDir.cause()); } }); } else { context.fail(deletedDir.cause()); } }); } }); }
@Override public void start(Future<Void> startFuture) throws Exception { Json.mapper.registerModule(new JavaTimeModule()); FileSystem vertxFileSystem = vertx.fileSystem(); vertxFileSystem.readFile("swagger.json", readFile -> { if (readFile.succeeded()) { Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8"))); SwaggerManager.getInstance().setSwagger(swagger); Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver()); deployVerticles(startFuture); vertx.createHttpServer() .requestHandler(swaggerRouter::accept) .listen(config().getInteger("http.port", 8080)); startFuture.complete(); } else { startFuture.fail(readFile.cause()); } }); }
/** * Sets up the fixture. */ @Before public void setUp() { fileSystem = mock(FileSystem.class); Context ctx = mock(Context.class); eventBus = mock(EventBus.class); vertx = mock(Vertx.class); when(vertx.eventBus()).thenReturn(eventBus); when(vertx.fileSystem()).thenReturn(fileSystem); props = new FileBasedRegistrationConfigProperties(); props.setFilename(FILE_NAME); registrationService = new FileBasedRegistrationService(); registrationService.setConfig(props); registrationService.init(vertx, ctx); }
public void handshake(HttpClient hc, FileSystem fs) { HttpClientRequest request = hc.put(AgentConstant.SERVER_PORT, AgentConstant.SERVER_ADDR, "", resp -> { System.out.println("Response: Hand Shake Status Code - " + resp.statusCode()); System.out.println("Response: Hand Shake Status Message - " + resp.statusMessage()); if (resp.statusCode() == AgentConstant.RES_SUCCESS) { System.out.println("Response: Hand Shake Status - SUCCESSFUL!"); //check if it is file/folder processing if(Files.isDirectory(Paths.get(AgentConstant.FILE_NAME))) { streamFilesDir(hc, fs); } else streamFile(hc, fs); } else System.out.println("Response: Hand Shake Status - FAILED!"); }); request.headers().add("DF_PROTOCOL","REGISTER"); request.headers().add("DF_MODE", AgentConstant.TRANS_MODE); request.headers().add("DF_TYPE", "META"); request.headers().add("DF_TOPIC", AgentConstant.META_TOPIC); request.headers().add("DF_FILENAME", AgentConstant.FILE_NAME); request.headers().add("DF_FILTER", AgentConstant.FILTER_TYPE); request.headers().add("DF_DATA_TRANS", AgentConstant.DATA_TRANS); request.end(setMetaData(AgentConstant.FILE_NAME)); }
void ls(Vertx vertx, String currentFile, String pathArg, Handler<AsyncResult<Map<String, FileProps>>> filesHandler) { Path base = currentFile != null ? new File(currentFile).toPath() : rootDir; String path = base.resolve(pathArg).toAbsolutePath().normalize().toString(); vertx.executeBlocking(fut -> { FileSystem fs = vertx.fileSystem(); if (fs.propsBlocking(path).isDirectory()) { LinkedHashMap<String, FileProps> result = new LinkedHashMap<>(); for (String file : fs.readDirBlocking(path)) { result.put(file, fs.propsBlocking(file)); } fut.complete(result); } else { throw new RuntimeException(path + ": No such file or directory"); } }, filesHandler); }
@org.junit.Test public void testReportToFile() { FileSystem fs = vertx.fileSystem(); String file = "target"; assertTrue(fs.existsBlocking(file)); assertTrue(fs.propsBlocking(file).isDirectory()); suite.run(vertx, new TestOptions().addReporter(new ReportOptions().setTo("file:" + file))); String path = file + File.separator + "my_suite.txt"; assertTrue(fs.existsBlocking(path)); int count = 1000; while (true) { FileProps props = fs.propsBlocking(path); if (props.isRegularFile() && props.size() > 0) { break; } else { if (count-- > 0) { try { Thread.sleep(1); } catch (InterruptedException ignore) { } } else { fail(); } } } }
public void sendStream(WebClient client, FileSystem fs) { fs.open("content.txt", new OpenOptions(), fileRes -> { if (fileRes.succeeded()) { ReadStream<Buffer> fileStream = fileRes.result(); String fileLen = "1024"; // Send the file to the server using POST client .post(8080, "myserver.mycompany.com", "/some-uri") .putHeader("content-length", fileLen) .sendStream(fileStream, ar -> { if (ar.succeeded()) { // Ok } }); } }); }
private void deleteFileUploads() { if (cleanup.compareAndSet(false, true)) { for (FileUpload fileUpload : context.fileUploads()) { FileSystem fileSystem = context.vertx().fileSystem(); String uploadedFileName = fileUpload.uploadedFileName(); fileSystem.exists(uploadedFileName, existResult -> { if (existResult.failed()) { log.warn("Could not detect if uploaded file exists, not deleting: " + uploadedFileName, existResult.cause()); } else if (existResult.result()) { fileSystem.delete(uploadedFileName, deleteResult -> { if (deleteResult.failed()) { log.warn("Delete of uploaded file failed: " + uploadedFileName, deleteResult.cause()); } }); } }); } } }
private void makeUploadDir(FileSystem fileSystem) { // *** cse begin *** if (uploadsDir == null) { return; } // *** cse end *** if (!fileSystem.existsBlocking(uploadsDir)) { fileSystem.mkdirsBlocking(uploadsDir); } }
/** * @return a Mustache template compiled */ private Mustache getMustache() { if (this.mustache == null) { final FileSystem fs = this.getVertx().fileSystem(); final Buffer templateBuffer = fs.readFileBlocking(this.getTemplateName()); final MustacheFactory mf = new DefaultMustacheFactory(); final ByteArrayInputStream bi = new ByteArrayInputStream(templateBuffer.getBytes()); this.mustache = mf.compile(new InputStreamReader(bi), "Transform"); } return this.mustache; }
private Mustache getTemplate() { final Vertx vertx = Vertx.vertx(); final FileSystem fs = vertx.fileSystem(); final Buffer b = fs.readFileBlocking("sample.mustache"); final MustacheFactory mf = new DefaultMustacheFactory(); final ByteArrayInputStream bi = new ByteArrayInputStream(b.getBytes()); final Mustache mustache = mf.compile(new InputStreamReader(bi), "Test"); return mustache; }
@Test() public void testOkFormDataSimpleFile(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/file"); req.handler(response -> { response.bodyHandler(body -> { context.assertEquals(response.statusCode(), 200); context.assertEquals("{\"test\":\"This is a test file.\"}", body.toString()); async.complete(); }); }); // Construct multipart data req.putHeader(HttpHeaders.CONTENT_TYPE, "multipart/form-data; boundary=MyBoundary"); Buffer buffer = Buffer.factory.buffer(); FileSystem vertxFileSystem = vertx.fileSystem(); vertxFileSystem.readFile(TEST_FILENAME, readFile -> { if (readFile.succeeded()) { buffer.appendString("\r\n"); buffer.appendString("--MyBoundary\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"formDataRequired\"; filename=\"" + TEST_FILENAME + "\"\r\n"); buffer.appendString("Content-Type: text/plain\r\n"); buffer.appendString("\r\n"); buffer.appendString(readFile.result().toString(Charset.forName("utf-8"))); buffer.appendString("\r\n"); buffer.appendString("--MyBoundary--"); req.end(buffer); } else { context.fail(readFile.cause()); } }); }
@AfterClass public static void afterClass(TestContext context) { Async after = context.async(); FileSystem vertxFileSystem = vertx.fileSystem(); vertxFileSystem.deleteRecursive(".vertx", true, vertxDir -> { if (vertxDir.succeeded()) { after.complete(); } else { context.fail(vertxDir.cause()); } }); }
/** * Sets up fixture. */ @Before public void setUp() { fileSystem = mock(FileSystem.class); Context ctx = mock(Context.class); eventBus = mock(EventBus.class); vertx = mock(Vertx.class); when(vertx.eventBus()).thenReturn(eventBus); when(vertx.fileSystem()).thenReturn(fileSystem); props = new FileBasedCredentialsConfigProperties(); svc = new FileBasedCredentialsService(); svc.setConfig(props); svc.init(vertx, ctx); }
private void getContent(FileSystem fileSystem, String path, StringBuilder result) { fileSystem.readDirBlocking(path).forEach(file -> { File jfile = new File(file); if (jfile.isDirectory()) { getContent(fileSystem, jfile.getAbsolutePath(), result); } else { result.append(jfile.getAbsolutePath()); result.append(jfile.lastModified()); } }); }
private static void addFromStaticHandler(FileSystem fileSystem, String sourcePath, String url, String rootroot) { fileSystem.readDir(sourcePath, files -> { if (files.result() == null) { return; } for (String item : files.result()) { File file = new File(item); if (file.isFile()) { watchables.add(new Watchable(url + file.getName(), item)); } else { addFromStaticHandler(fileSystem, item, url + file.getName() + "/", rootroot); } } }); }
@Override public void getOne(String path, Handler<AsyncResult<ChunkReadStream>> handler) { String absolutePath = Paths.get(root, path).toString(); // check if chunk exists FileSystem fs = vertx.fileSystem(); ObservableFuture<Boolean> observable = RxHelper.observableFuture(); fs.exists(absolutePath, observable.toHandler()); observable .flatMap(exists -> { if (!exists) { return Observable.error(new FileNotFoundException("Could not find chunk: " + path)); } return Observable.just(exists); }) .flatMap(exists -> { // get chunk's size ObservableFuture<FileProps> propsObservable = RxHelper.observableFuture(); fs.props(absolutePath, propsObservable.toHandler()); return propsObservable; }) .map(props -> props.size()) .flatMap(size -> { // open chunk ObservableFuture<AsyncFile> openObservable = RxHelper.observableFuture(); OpenOptions openOptions = new OpenOptions().setCreate(false).setWrite(false); fs.open(absolutePath, openOptions, openObservable.toHandler()); return openObservable.map(f -> new FileChunkReadStream(size, f)); }) .subscribe(readStream -> { // send chunk to peer handler.handle(Future.succeededFuture(readStream)); }, err -> { handler.handle(Future.failedFuture(err)); }); }
@Override protected void doDeleteChunks(Queue<String> paths, Handler<AsyncResult<Void>> handler) { if (paths.isEmpty()) { handler.handle(Future.succeededFuture()); return; } String path = paths.poll(); FileSystem fs = vertx.fileSystem(); String absolutePath = Paths.get(root, path).toString(); fs.exists(absolutePath, existAr -> { if (existAr.failed()) { handler.handle(Future.failedFuture(existAr.cause())); } else { if (existAr.result()) { fs.delete(absolutePath, deleteAr -> { if (deleteAr.failed()) { handler.handle(Future.failedFuture(deleteAr.cause())); } else { doDeleteChunks(paths, handler); } }); } else { doDeleteChunks(paths, handler); } } }); }
public void bindInterfaces(Vertx vertx){ Environment.registry(Bind.bind(Vertx.class), vertx); Environment.registry(Bind.bind(Context.class), vertx.getOrCreateContext()); Environment.registry(Bind.bind(EventBus.class), vertx.eventBus()); Environment.registry(Bind.bind(FileSystem.class), vertx.fileSystem()); Environment.registry(Bind.bind(SharedData.class), vertx.sharedData()); }