Java 类com.google.common.io.MoreFiles 实例源码

项目:ios-device-control    文件:IosAppInfo.java   
/** Returns the application info read from either an app folder or ipa archive */
public static IosAppInfo readFromPath(Path ipaOrAppPath) throws IOException {
  NSObject plistDict;
  if (Files.isDirectory(ipaOrAppPath)) {
    plistDict = PlistParser.fromPath(ipaOrAppPath.resolve("Info.plist"));
  } else {
    try (FileSystem ipaFs = FileSystems.newFileSystem(ipaOrAppPath, null)) {
      Path appPath =
          MoreFiles.listFiles(ipaFs.getPath("Payload"))
              .stream()
              // Can't use Files.isDirectory, because no entry is a "directory" in a zip.
              .filter(e -> e.toString().endsWith(".app/"))
              .collect(MoreCollectors.onlyElement());
      plistDict = PlistParser.fromPath(appPath.resolve("Info.plist"));
    }
  }
  return readFromPlistDictionary((NSDictionary) plistDict);
}
项目:ios-device-control    文件:SimulatorDeviceHost.java   
static ImmutableSet<IosAppInfo> listSystemApps(String productVersion) throws IOException {
  try {
    return runtime2SystemApps.computeIfAbsent(
        productVersion,
        r ->
            tunnel(
                () -> {
                  Path appsDir = runtimeRootPath(productVersion).resolve("Applications");
                  return MoreFiles.listFiles(appsDir)
                      .stream()
                      .filter(p -> Files.exists(p.resolve("Info.plist")))
                      .map(a -> tunnel(() -> IosAppInfo.readFromPath(a)))
                      .collect(toImmutableSet());
                }));
  } catch (TunnelException e) {
    throw e.getCauseAs(IOException.class);
  }
}
项目:ios-device-control    文件:SimulatorDeviceImpl.java   
@Override
public void installApplication(Path ipaOrAppPath) throws IosDeviceException {
  try {
    if (Files.isDirectory(ipaOrAppPath)) {
      await(simctl.install(ipaOrAppPath.toString()));
    } else {
      Path tmpDir = Files.createTempDirectory("app");
      try {
        unzipFile(ipaOrAppPath, tmpDir);
        Path appPath =
            tmpDir
                .resolve("Payload")
                .resolve(MoreFiles.getNameWithoutExtension(ipaOrAppPath) + ".app");
        await(simctl.install(appPath.toString()));
      } finally {
        MoreFiles.deleteRecursively(tmpDir, RecursiveDeleteOption.ALLOW_INSECURE);
      }
    }
  } catch (IOException e) {
    throw new IosDeviceException(this, e);
  }
}
项目:buckaroo    文件:CommonTasks.java   
public static Single<WriteFileEvent> writeFile(final String content, final Path path, final boolean overwrite) {
    Preconditions.checkNotNull(content);
    Preconditions.checkNotNull(path);
    return Single.fromCallable(() -> {
        if (path.getParent() != null && !Files.exists(path.getParent())) {
            Files.createDirectories(path.getParent());
        }
        if (overwrite) {
            Files.deleteIfExists(path);
        } else if (Files.isDirectory(path)) {
            throw new IOException("There is already a directory at " + path);
        } else if (Files.exists(path)) {
            throw new IOException("There is already a file at " + path);
        }
        final ByteSink sink = MoreFiles.asByteSink(path);
        sink.write(content.getBytes());
        return WriteFileEvent.of(path);
    }).subscribeOn(Schedulers.io());
}
项目:closure-compiler    文件:SourceFileTest.java   
public void testCachingFile() throws IOException {
  // Setup environment.
  String expectedContent = "// content content content";
  String newExpectedContent = "// new content new content new content";
  Path jsFile = Files.createTempFile("test", ".js");
  MoreFiles.asCharSink(jsFile, StandardCharsets.UTF_8).write(expectedContent);
  SourceFile sourceFile = SourceFile.fromFile(jsFile.toFile());

  // Verify initial state.
  assertEquals(expectedContent, sourceFile.getCode());

  // Perform a change.
  MoreFiles.asCharSink(jsFile, StandardCharsets.UTF_8).write(newExpectedContent);
  sourceFile.clearCachedSource();

  // Verify final state.
  assertEquals(newExpectedContent, sourceFile.getCode());
}
项目:lsql    文件:Main.java   
private List<StatementFileExporter> createStatements(LSql lSql, JavaExporter javaExporter, CliArgs cliArgs) {
    List<StatementFileExporter> list = newLinkedList();

    if (cliArgs.getSqlStatements() != null) {
        Path statementRootDir = new File(cliArgs.getSqlStatements()).toPath();
        Iterable<Path> children = MoreFiles.directoryTreeTraverser().preOrderTraversal(statementRootDir);
        for (Path child : children) {
            File file = child.toFile();
            if (file.isFile() && file.getName().endsWith(".sql")) {
                StatementFileExporter statementFileExporter =
                        new StatementFileExporter(lSql, javaExporter, file, cliArgs.getSqlStatements());

                list.add(statementFileExporter);
            }
        }
    }

    return list;
}
项目:burpextender-proxyhistory-webui    文件:AppContextTest.java   
@After
public void cleanUp() throws Exception {
    appContext.stopLogging();
    DataStore.closeConnection(dbconn);
    try {
        MoreFiles
            .deleteRecursively(Paths.get(DataStore.getDbDir(testDbName)), RecursiveDeleteOption.ALLOW_INSECURE);
    } catch (IOException e) {
        // DONT make test failure.
        System.err.println("test db clean-up failure, remove manually later :P");
        e.printStackTrace();
    }
}
项目:lttng-scope    文件:StubProject.java   
@Override
public void close() {
    try {
        MoreFiles.deleteRecursively(fProjectPath);
    } catch (IOException e) {
    }
}
项目:embedded-jms-junit    文件:EmbeddedJmsRuleImpl.java   
private void stopService() {
    try {
        brokerService.stop();
        MoreFiles.deleteRecursively(tempDir.toPath(), RecursiveDeleteOption.ALLOW_INSECURE);
        brokerService = null;
    } catch (Exception e) {
        throw new IllegalStateException("Could not stop broker", e);
    }
}
项目:ios-device-control    文件:RealDeviceImpl.java   
@Override
public void clearCrashLogs() throws IosDeviceException {
  try {
    Path tempDir = Files.createTempDirectory("artifacts");
    try {
      idevice.crashreport(tempDir.toString());
    } finally {
      MoreFiles.deleteRecursively(tempDir, RecursiveDeleteOption.ALLOW_INSECURE);
    }
  } catch (IOException e) {
    throw new IosDeviceException(this, e);
  }
}
项目:ios-device-control    文件:SimulatorDeviceHost.java   
private static IosModel toModel(String deviceType) throws IOException {
  checkArgument(deviceType.matches("[-\\w]*"));
  Path profileInfoBasePath =
      Paths.get(
          "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/"
              + "Developer/Library/CoreSimulator/Profiles/DeviceTypes");
  Path deviceTypePath =
      MoreFiles.listFiles(profileInfoBasePath)
          .stream()
          // The directory name that matches a given device type is the same as the name from the
          // device.plist file, with the hyphens replaced with spaces, hyphens, parentheses or
          // periods
          .filter(
              p -> MoreFiles.getNameWithoutExtension(p).replaceAll("\\W", "-").equals(deviceType))
          .collect(MoreCollectors.onlyElement());
  String rawProductName = MoreFiles.getNameWithoutExtension(deviceTypePath);
  String productName = GENERATION_PATTERN.matcher(rawProductName).replaceFirst("$1");

  Path profilePath = deviceTypePath.resolve("Contents/Resources/profile.plist");
  NSDictionary profileDict = (NSDictionary) PlistParser.fromPath(profilePath);
  String identifier = profileDict.get("modelIdentifier").toString();

  NSArray supportedArchs = (NSArray) profileDict.get("supportedArchs");
  // The supported architecture can either be just i386 or i386 and x86_64. The
  // actual architecture will be x86_64 if its supported, or i386 otherwise.
  Architecture architecture =
      supportedArchs.containsObject(Architecture.X86_64.toString())
          ? Architecture.X86_64
          : Architecture.I386;
  return IosModel.builder()
      .identifier(identifier)
      .productName(productName)
      .architecture(architecture)
      .build();
}
项目:ios-device-control    文件:SimulatorDeviceImpl.java   
private ImmutableSet<IosAppInfo> userApps() throws IOException {
  Path appPath =
      Paths.get(
          System.getProperty("user.home"),
          "Library/Developer/CoreSimulator/Devices",
          udid,
          "data/Containers/Bundle/Application");
  if (!Files.exists(appPath)) {
    return ImmutableSet.of();
  }
  try {
    return MoreFiles.listFiles(appPath)
        .stream()
        .map(
            p ->
                tunnel(
                    () ->
                        MoreFiles.listFiles(p)
                            .stream()
                            .filter(a -> MoreFiles.getFileExtension(a).equals("app"))
                            .collect(MoreCollectors.onlyElement())))
        .map(a -> tunnel(() -> IosAppInfo.readFromPath(a)))
        .collect(toImmutableSet());
  } catch (TunnelException e) {
    throw e.getCauseAs(IOException.class);
  }
}
项目:buckaroo    文件:ResolveTasksTest.java   
@Test
public void emptyProject() throws Exception {

    final FileSystem fs = Jimfs.newFileSystem();

    // Workaround: JimFs does not implement .toFile;
    // We clone and fail buckaroo-recipes if it does not exist, so we create it.
    MoreFiles.createParentDirectories(fs.getPath(
        System.getProperty("user.home"),
        ".buckaroo",
        "buckaroo-recipes",
        ".git"));

    final Project project = Project.of();

    EvenMoreFiles.writeFile(
        fs.getPath("buckaroo.json"),
        Serializers.serialize(project));

    final Observable<Event> task = ResolveTasks.resolveDependenciesInWorkingDirectory(fs);

    task.toList().blockingGet();

    assertEquals(
        right(DependencyLocks.of()),
        Serializers.parseDependencyLocks(EvenMoreFiles.read(fs.getPath("buckaroo.lock.json"))));
}
项目:buckaroo    文件:InstallTasksTest.java   
@Test
public void installDirectlyFromGitHub1() throws Exception {

    final FileSystem fs = Jimfs.newFileSystem();

    // Workaround: JimFs does not implement .toFile;
    // We clone and fail buckaroo-recipes if it does not exist, so we create it.
    MoreFiles.createParentDirectories(fs.getPath(
        System.getProperty("user.home"),
        ".buckaroo",
        "buckaroo-recipes",
        ".git"));

    final ImmutableList<PartialDependency> partialDependencies = ImmutableList.of(
        PartialDependency.of(
            Identifier.of("github"),
            Identifier.of("njlr"),
            Identifier.of("test-lib-a"),
            AnySemanticVersion.of()));

    InitTasks.initWorkingDirectory(fs).toList().blockingGet();

    final List<Event> events = InstallTasks.installDependencyInWorkingDirectory(fs, partialDependencies).toList().blockingGet();

    assertTrue(Files.exists(fs.getPath("BUCKAROO_DEPS")));

    final Path dependencyFolder = fs.getPath(
        "buckaroo", "github", "njlr", "test-lib-a");

    assertTrue(Files.exists(dependencyFolder.resolve("BUCK")));
    assertTrue(Files.exists(dependencyFolder.resolve("BUCKAROO_DEPS")));
}
项目:buckaroo    文件:InstallTasksTest.java   
@Test
public void installDirectlyFromGitHub2() throws Exception {

    final FileSystem fs = Jimfs.newFileSystem();

    // Workaround: JimFs does not implement .toFile;
    // We clone and fail buckaroo-recipes if it does not exist, so we create it.
    MoreFiles.createParentDirectories(fs.getPath(
        System.getProperty("user.home"),
        ".buckaroo",
        "buckaroo-recipes",
        ".git"));

    final ImmutableList<PartialDependency> partialDependencies = ImmutableList.of(
        PartialDependency.of(
            Identifier.of("github"),
            Identifier.of("njlr"),
            Identifier.of("test-lib-d"),
            AnySemanticVersion.of()));

    InitTasks.initWorkingDirectory(fs).toList().blockingGet();

    InstallTasks.installDependencyInWorkingDirectory(fs, partialDependencies).toList().blockingGet();

    assertTrue(Files.exists(fs.getPath("BUCKAROO_DEPS")));

    final Path dependencyFolder = fs.getPath(
        "buckaroo", "github", "njlr", "test-lib-d");

    assertTrue(Files.exists(dependencyFolder.resolve("BUCK")));
    assertTrue(Files.exists(dependencyFolder.resolve("BUCKAROO_DEPS")));
}
项目:buckaroo    文件:UninstallTasksTests.java   
@Test
public void uninstallRemovesTheDependencyFromTheProjectFile() throws Exception {

    final FileSystem fs = Jimfs.newFileSystem();

    final Project project = Project.of(
        "My Project",
        DependencyGroup.of(ImmutableMap.of(
            RecipeIdentifier.of("org", "example"), AnySemanticVersion.of()
        )));

    Files.write(fs.getPath("buckaroo.json"), Serializers.serialize(project).getBytes(Charsets.UTF_8));

    // Workaround: JimFs does not implement .toFile;
    // We clone and fail buckaroo-recipes if it does not exist, so we create it.
    MoreFiles.createParentDirectories(fs.getPath(
        System.getProperty("user.home"),
        ".buckaroo",
        "buckaroo-recipes",
        ".git"));

    UninstallTasks.uninstallInWorkingDirectory(
        fs,
        ImmutableList.of(PartialRecipeIdentifier.of(Identifier.of("example")))).toList().blockingGet();

    final Project newProject = Serializers.parseProject(EvenMoreFiles.read(fs.getPath("buckaroo.json")))
        .right().get();

    assertTrue(!newProject.dependencies.requires(RecipeIdentifier.of("org", "example")));
}
项目:buckaroo    文件:InstallTasksUnitTest.java   
@Test
public void completeDependenciesFailsGracefully() throws Exception {

    final FileSystem fs = Jimfs.newFileSystem();

    // Workaround: JimFs does not implement .toFile;
    // We clone and fail buckaroo-recipes if it does not exist, so we create it.
    MoreFiles.createParentDirectories(fs.getPath(
        System.getProperty("user.home"),
        ".buckaroo",
        "buckaroo-recipes",
        ".git"));

    final RecipeSource recipeSource = LazyCookbookRecipeSource.of(fs.getPath("nocookbookhere"));

    final ImmutableList<PartialDependency> partialDependencies = ImmutableList.of(
        PartialDependency.of(Identifier.of("org"), Identifier.of("example")));

    final CountDownLatch latch = new CountDownLatch(1);

    InstallTasks.completeDependencies(recipeSource, partialDependencies).result().subscribe(
        x -> {

        },
        error -> {
            latch.countDown();
        });

    latch.await(5000L, TimeUnit.MILLISECONDS);
}
项目:copybara    文件:FileUtil.java   
/**
 * Delete all the contents of a path recursively.
 *
 * <p>First we try to delete securely. In case the FileSystem doesn't support it,
 * delete it insecurely.
 */
public static void deleteRecursively(Path path) throws IOException {
  try {
    MoreFiles.deleteRecursively(path);
  } catch (InsecureRecursiveDeleteException ignore) {
    logger.warning(String.format("Secure delete not supported. Deleting '%s' insecurely.",
        path));
    MoreFiles.deleteRecursively(path, RecursiveDeleteOption.ALLOW_INSECURE);
  }
}
项目:java-smt    文件:Mathsat5SolverContext.java   
long createEnvironment(long cfg) {
  if (USE_GHOST_FILTER) {
    msat_set_option_checked(cfg, "dpll.ghost_filtering", "true");
  }

  msat_set_option_checked(cfg, "theory.la.split_rat_eq", "false");
  msat_set_option_checked(cfg, "random_seed", Long.toString(randomSeed));

  for (Entry<String, String> option : settings.furtherOptionsMap.entrySet()) {
    msat_set_option_checked(cfg, option.getKey(), option.getValue());
  }

  if (settings.logfile != null) {
    Path filename = settings.logfile.getFreshPath();
    try {
      MoreFiles.createParentDirectories(filename);
    } catch (IOException e) {
      logger.logUserException(Level.WARNING, e, "Cannot create directory for MathSAT logfile");
    }

    msat_set_option_checked(cfg, "debug.api_call_trace", "1");
    msat_set_option_checked(
        cfg, "debug.api_call_trace_filename", filename.toAbsolutePath().toString());
  }

  final long env;
  if (USE_SHARED_ENV) {
    env = msat_create_shared_env(cfg, creator.getEnv());
  } else {
    env = msat_create_env(cfg);
  }

  return env;
}
项目:gerrit    文件:ReindexIT.java   
@Test
public void reindexFromScratch() throws Exception {
  setUpChange();

  MoreFiles.deleteRecursively(sitePaths.index_dir, RecursiveDeleteOption.ALLOW_INSECURE);
  Files.createDirectory(sitePaths.index_dir);
  assertServerStartupFails();

  runGerrit("reindex", "-d", sitePaths.site_path.toString(), "--show-stack-trace");
  assertReady(ChangeSchemaDefinitions.INSTANCE.getLatest().getVersion());

  try (ServerContext ctx = startServer()) {
    GerritApi gApi = ctx.getInjector().getInstance(GerritApi.class);
    // Query change index
    assertThat(gApi.changes().query("message:Test").get().stream().map(c -> c.changeId))
        .containsExactly(changeId);
    // Query account index
    assertThat(gApi.accounts().query("admin").get().stream().map(a -> a._accountId))
        .containsExactly(adminId.get());
    // Query group index
    assertThat(
            gApi.groups()
                .query("Group")
                .withOption(MEMBERS)
                .get()
                .stream()
                .flatMap(g -> g.members.stream())
                .map(a -> a._accountId))
        .containsExactly(adminId.get());
  }
}
项目:lsql    文件:DtoDeclarationFinder.java   
public List<DataClassExporter> getDataClassExporters() {
    List<DataClassExporter> dataClassExporters = newLinkedList();

    Path rootDir = new File(this.dtoDeclarationLocation).toPath();
    Iterable<Path> children = MoreFiles.directoryTreeTraverser().preOrderTraversal(rootDir);
    for (Path child : children) {
        File file = child.toFile();
        if (file.isFile() && file.getName().endsWith(".java")) {
            dataClassExporters.addAll(this.checkFileForDtoDeclarations(file));
        }
    }

    return dataClassExporters;
}
项目:lsql    文件:TestCliProjectGenerationTest.java   
@Test
public void createTestFiles() throws SQLException, ClassNotFoundException, IOException {
    File genJavaDir = pathRelativeToProjectRoot("pom.xml", "../lsql-cli-tests/src/generated/java");
    if (genJavaDir.exists()) {
        MoreFiles.deleteRecursively(genJavaDir.toPath());
    }

    File genTSDir = pathRelativeToProjectRoot("pom.xml", "../lsql-cli-tests/src/generated/ts");
    if (genTSDir.exists()) {
        MoreFiles.deleteRecursively(genTSDir.toPath());
    }

    String url = "jdbc:h2:mem:" + UUID.randomUUID() + ";mode=postgresql";

    BasicDataSource ds = new BasicDataSource();
    ds.setUrl(url);
    ds.setDefaultAutoCommit(false);
    Connection connection = ds.getConnection();
    LSql lSql = new LSql(TestCliConfig.class, ConnectionProviders.fromInstance(connection));
    createTables(lSql);
    connection.close();

    String[] args = {
            "config:" + TestCliConfig.class.getCanonicalName(),
            "url:" + url,
            "user:",
            "password:",
            "sqlStatements:" + pathRelativeToProjectRoot("pom.xml", "./src/test/java/com/w11k/lsql/cli/tests"),
            "dto:" + pathRelativeToProjectRoot("pom.xml", "./src/test/java/com/w11k/lsql/cli/tests"),
            "package:" + TestCliConfig.class.getPackage().getName(),
            "di:guice",
            "outDirJava:" + genJavaDir.getAbsolutePath(),
            "outDirTypeScript:" + genTSDir.getAbsolutePath()
    };
    Main.main(args);
}
项目:bazel-tools    文件:PathUtils.java   
public static HashCode sha256(final Path file) throws IOException {
  return MoreFiles.asByteSource(file).hash(Hashing.sha256());
}
项目:buckaroo    文件:CommonTasks.java   
public static Single<TouchFileEvent> touchFile(final Path path) {
    return Single.fromCallable(() -> {
        MoreFiles.touch(path);
        return TouchFileEvent.of(path);
    });
}
项目:buckaroo    文件:EvenMoreFiles.java   
public static HashCode hashFile(final Path path) throws IOException {

        Preconditions.checkNotNull(path);

        final HashFunction hashFunction = Hashing.sha256();

        return hashFunction.newHasher()
            .putBytes(MoreFiles.asByteSource(path).read())
            .hash();
    }
项目:Strata    文件:CharSources.java   
/**
 * Obtains an instance of {@link CharSource} from a file path, specified as a {@link Path}.
 *
 * @param path  the path to create a {@link CharSource} from
 * @return  a new instance of {@link CharSource} with UTF-8 for charset.
 */
public static CharSource ofPath(Path path) {
  return MoreFiles.asCharSource(path, Charsets.UTF_8);
}
项目:Strata    文件:CharSources.java   
/**
 * Obtains an instance of {@link CharSource} from a file path, specified as a {@link Path}.
 * This also takes in a specific character set, as a {@link Charset}.
 *
 * @param path  the path to create a {@link CharSource} from
 * @param charset  the charset to build the new CharSource based on
 * @return  a new instance of {@link CharSource}
 */
public static CharSource ofPath(Path path, Charset charset) {
  return MoreFiles.asCharSource(path, charset);
}