io.vertx.core.file.FileProps Java Examples

The following examples show how to use io.vertx.core.file.FileProps. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RemoteFileSyncerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createShouldCreateDirWithWritePermissionIfItsNotDir() {
    // given
    final FileProps fileProps = mock(FileProps.class);
    reset(fileSystem);
    when(fileSystem.existsBlocking(eq(DIR_PATH))).thenReturn(true);
    when(fileSystem.propsBlocking(eq(DIR_PATH))).thenReturn(fileProps);
    when(fileProps.isDirectory()).thenReturn(false);

    // when
    RemoteFileSyncer.create(SOURCE_URL, FILE_PATH, TMP_FILE_PATH, RETRY_COUNT, RETRY_INTERVAL, TIMEOUT,
            UPDATE_INTERVAL, httpClient, vertx, fileSystem);

    // then
    verify(fileSystem).mkdirsBlocking(eq(DIR_PATH));
}
 
Example #2
Source File: FsHelper.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: ReportingTest.java    From vertx-unit with Apache License 2.0 6 votes vote down vote up
@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();
      }
    }
  }
}
 
Example #4
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Create all required header so content can be cache by Caching servers or Browsers
 *
 * @param request base HttpServerRequest
 * @param props   file properties
 */
private void writeCacheHeaders(HttpServerRequest request, FileProps props) {

  MultiMap headers = request.response().headers();

  if (cache.enabled()) {
    // We use cache-control and last-modified
    // We *do not use* etags and expires (since they do the same thing - redundant)
    Utils.addToMapIfAbsent(headers, HttpHeaders.CACHE_CONTROL, "public, max-age=" + maxAgeSeconds);
    Utils.addToMapIfAbsent(headers, HttpHeaders.LAST_MODIFIED, Utils.formatRFC1123DateTime(props.lastModifiedTime()));
    // We send the vary header (for intermediate caches)
    // (assumes that most will turn on compression when using static handler)
    if (sendVaryHeader && request.headers().contains(HttpHeaders.ACCEPT_ENCODING)) {
      Utils.addToMapIfAbsent(headers, "Vary", "accept-encoding");
    }
  }
  // date header is mandatory
  headers.set("date", Utils.formatRFC1123DateTime(System.currentTimeMillis()));
}
 
Example #5
Source File: StartupContext.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Override
public InputStream getResourceAsStream(String path) {
    String relativePath = path;
    if (relativePath.startsWith("/")) {
        relativePath = relativePath.substring(1);
    }
    FileSystem fileSystem = startupContext.vertx.fileSystem();
    FileProps props = fileSystem.propsBlocking(relativePath);
    if (props != null && !props.isDirectory()) {
        Buffer buffer = fileSystem.readFileBlocking(relativePath);
        return new ByteArrayInputStream(buffer.getBytes());
    }
    return null;

}
 
Example #6
Source File: RemoteFileSyncer.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates if doesn't exists and checks write permissions for the given directory.
 */
private static void createAndCheckWritePermissionsFor(FileSystem fileSystem, String filePath) {
    try {
        final String dirPath = Paths.get(filePath).getParent().toString();
        final FileProps props = fileSystem.existsBlocking(dirPath) ? fileSystem.propsBlocking(dirPath) : null;
        if (props == null || !props.isDirectory()) {
            fileSystem.mkdirsBlocking(dirPath);
        } else if (!Files.isWritable(Paths.get(dirPath))) {
            throw new PreBidException(String.format("No write permissions for directory: %s", dirPath));
        }
    } catch (FileSystemException | InvalidPathException e) {
        throw new PreBidException(String.format("Cannot create directory for file: %s", filePath), e);
    }
}
 
Example #7
Source File: VendorListService.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates if doesn't exists and checks write permissions for the given directory.
 */
private static void createAndCheckWritePermissionsFor(FileSystem fileSystem, String dir) {
    final FileProps props = fileSystem.existsBlocking(dir) ? fileSystem.propsBlocking(dir) : null;
    if (props == null || !props.isDirectory()) {
        try {
            fileSystem.mkdirsBlocking(dir);
        } catch (FileSystemException e) {
            throw new PreBidException(String.format("Cannot create directory: %s", dir), e);
        }
    } else if (!Files.isWritable(Paths.get(dir))) {
        throw new PreBidException(String.format("No write permissions for directory: %s", dir));
    }
}
 
Example #8
Source File: FsHelper.java    From vertx-shell with Apache License 2.0 4 votes vote down vote up
void complete(Vertx vertx, String currentPath, String _prefix, Handler<AsyncResult<Map<String, Boolean>>> handler) {
  vertx.executeBlocking(fut -> {

    FileSystem fs = vertx.fileSystem();
    Path base = (currentPath != null ? new File(currentPath).toPath() : rootDir);

    int index = _prefix.lastIndexOf('/');
    String prefix;
    if (index == 0) {
      handler.handle(Future.failedFuture("todo"));
      return;
    } else if (index > 0) {
      base = base.resolve(_prefix.substring(0, index));
      prefix = _prefix.substring(index + 1);
    } else {
      prefix = _prefix;
    }

    LinkedHashMap<String, Boolean> matches = new LinkedHashMap<>();
    for (String path : fs.readDirBlocking(base.toAbsolutePath().normalize().toString())) {
      String name = path.substring(path.lastIndexOf('/') + 1);
      if (name.startsWith(prefix)) {
        FileProps props = fs.propsBlocking(path);
        matches.put(name.substring(prefix.length()) + (props.isDirectory() ? "/" : ""), props.isRegularFile());
      }
    }

    if (matches.size() > 1) {
      String common = Completion.findLongestCommonPrefix(matches.keySet());
      if (common.length() > 0) {
        matches.clear();
        matches.put(common, false);
      } else {
        LinkedHashMap<String, Boolean> tmp = new LinkedHashMap<>();
        matches.forEach((suffix, terminal) -> {
          tmp.put(prefix + suffix, terminal);
        });
        matches = tmp;
      }
    }

    fut.complete(matches);
  }, handler);


}
 
Example #9
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private void sendStatic(RoutingContext context, String path) {

    String file = null;

    if (!includeHidden) {
      file = getFile(path, context);
      int idx = file.lastIndexOf('/');
      String name = file.substring(idx + 1);
      if (name.length() > 0 && name.charAt(0) == '.') {
        // skip
        context.next();
        return;
      }
    }

    // Look in cache
    final CacheEntry entry = cache.get(path);

    if (entry != null) {
      if ((filesReadOnly || !entry.isOutOfDate())) {
        // a cache entry can mean 2 things:
        // 1. a miss
        // 2. a hit

        // a miss signals that we should continue the chain
        if (entry.isMissing()) {
          context.next();
          return;
        }

        // a hit needs to be verified for freshness
        final long lastModified = Utils.secondsFactor(entry.props.lastModifiedTime());

        if (Utils.fresh(context, lastModified)) {
          context.response()
            .setStatusCode(NOT_MODIFIED.code())
            .end();
          return;
        }
      }
    }

    final boolean dirty = cache.enabled() && entry != null;
    final String sfile = file == null ? getFile(path, context) : file;

    // verify if the file exists
    context.vertx()
      .fileSystem()
      .exists(sfile, exists -> {
        if (exists.failed()) {
          context.fail(exists.cause());
          return;
        }

        // file does not exist, continue...
        if (!exists.result()) {
          if (cache.enabled()) {
            cache.put(path, null);
          }
          context.next();
          return;
        }

        // Need to read the props from the filesystem
        getFileProps(context, sfile, res -> {
          if (res.succeeded()) {
            FileProps fprops = res.result();
            if (fprops == null) {
              // File does not exist
              if (dirty) {
                cache.remove(path);
              }
              context.next();
            } else if (fprops.isDirectory()) {
              if (dirty) {
                cache.remove(path);
              }
              sendDirectory(context, path, sfile);
            } else {
              if (cache.enabled()) {
                cache.put(path, fprops);

                if (Utils.fresh(context, Utils.secondsFactor(fprops.lastModifiedTime()))) {
                  context.response().setStatusCode(NOT_MODIFIED.code()).end();
                  return;
                }
              }
              sendFile(context, sfile, fprops);
            }
          } else {
            context.fail(res.cause());
          }
        });
      });
  }
 
Example #10
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
private CacheEntry(FileProps props, long cacheEntryTimeout) {
  this.props = props;
  this.cacheEntryTimeout = cacheEntryTimeout;
}
 
Example #11
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
void put(String path, FileProps props) {
  if (propsCache != null) {
    CacheEntry now = new CacheEntry(props, cacheEntryTimeout);
    propsCache.put(path, now);
  }
}