Java Code Examples for java.nio.file.Files#exists()

The following examples show how to use java.nio.file.Files#exists() . 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: OSGiLibDeployerToolTest.java    From carbon-kernel with Apache License 2.0 8 votes vote down vote up
private static void createOtherProfiles() throws IOException {
    profileNames.add("MSS");
    profileNames.add("AS");

    for (String profileName : profileNames) {
        Path profile = Paths.
                get(carbonHome.toString(), Constants.PROFILE_REPOSITORY, profileName,
                        "configuration", "org.eclipse.equinox.simpleconfigurator");
        createDirectories(profile);
        if (Files.exists(profile)) {
            Path bundlesInfo = Paths.get(profile.toString(), Constants.BUNDLES_INFO);
            if (!Files.exists(bundlesInfo)) {
                Files.createFile(bundlesInfo);
            }
        }
    }
}
 
Example 2
Source File: JarSettingsProperties.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
public static JarSettingsProperties readFromFile(Path path) {
	JarSettingsProperties jarSettingsProperties = new JarSettingsProperties();
	Properties properties = new Properties();
	try {
		if (Files.exists(path)) {
			try (InputStream inputStream = Files.newInputStream(path)) {
				properties.load(inputStream);
			}
			jarSettingsProperties.setJvm(properties.getProperty("jvm"));
			jarSettingsProperties.setHomedir(properties.getProperty("homedir"));
			jarSettingsProperties.setAddress(properties.getProperty("address"));
			jarSettingsProperties.setUseProxy(Boolean.valueOf(properties.getProperty("useProxy")));
			jarSettingsProperties.setProxyHost(properties.getProperty("proxyHost"));
			jarSettingsProperties.setProxyPort(Integer.parseInt(properties.getProperty("proxyPort")));
			jarSettingsProperties.setPort(Integer.parseInt(properties.getProperty("port")));
			jarSettingsProperties.setHeapsize(properties.getProperty("heapsize"));
			jarSettingsProperties.setStacksize(properties.getProperty("stacksize"));
			jarSettingsProperties.setForceipv4(Boolean.valueOf(properties.getProperty("forceipv4")));
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
	return jarSettingsProperties;
}
 
Example 3
Source File: EmbeddedSolrServerTestBase.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public Collection<ContentStream> download(final String collection, final String... names) {
  final Path base = Paths.get(getSolrClient().getCoreContainer().getSolrHome(), collection);
  final List<ContentStream> result = new ArrayList<>();

  if (Files.exists(base)) {
    for (final String name : names) {
      final File file = new File(base.toFile(), name);
      if (file.exists() && file.canRead()) {
        try {
          final ByteArrayOutputStream os = new ByteArrayOutputStream();
          ByteStreams.copy(new FileInputStream(file), os);
          final ByteArrayStream stream = new ContentStreamBase.ByteArrayStream(os.toByteArray(), name);
          result.add(stream);
        } catch (final IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }

  return result;
}
 
Example 4
Source File: CommandLine.java    From testcontainers-java with MIT License 6 votes vote down vote up
/**
 * Check whether an executable exists, either at a specific path (if a full path is given) or
 * on the PATH.
 *
 * @param executable the name of an executable on the PATH or a complete path to an executable that may/may not exist
 * @return  whether the executable exists and is executable
 */
public static boolean executableExists(String executable) {

    // First check if we've been given the full path already
    File directFile = new File(executable);
    if (directFile.exists() && directFile.canExecute()) {
        return true;
    }

    for (String pathString : getSystemPath()) {
        Path path = Paths.get(pathString);
        if (Files.exists(path.resolve(executable)) && Files.isExecutable(path.resolve(executable))) {
            return true;
        }
    }

    return false;
}
 
Example 5
Source File: PackageDatabase.java    From TerasologyLauncher with Apache License 2.0 5 votes vote down vote up
private List<Package> loadDatabase() {
    if (Files.exists(databaseFile)) {
        try (ObjectInputStream in = new ObjectInputStream(
                Files.newInputStream(databaseFile)
        )) {
            return (List<Package>) in.readObject();
        } catch (IOException | ClassNotFoundException e) {
            logger.error("Failed to load database file: {}", databaseFile);
        }
    }
    logger.info("Using empty database");
    return new LinkedList<>();
}
 
Example 6
Source File: SimpleJavaLibraryBuilder.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static void cleanupDirectory(@Nullable Path directory) throws IOException {
  if (directory == null) {
    return;
  }

  if (Files.exists(directory)) {
    try {
      MoreFiles.deleteRecursively(directory, RecursiveDeleteOption.ALLOW_INSECURE);
    } catch (IOException e) {
      throw new IOException("Cannot clean '" + directory + "'", e);
    }
  }

  Files.createDirectories(directory);
}
 
Example 7
Source File: MoreFiles.java    From LuckPerms with MIT License 5 votes vote down vote up
public static Path createDirectoriesIfNotExists(Path path) throws IOException {
    if (Files.exists(path) && (Files.isDirectory(path) || Files.isSymbolicLink(path))) {
        return path;
    }

    Files.createDirectories(path);
    return path;
}
 
Example 8
Source File: WordDictionary.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Attempt to load dictionary from provided directory, first trying coredict.mem, failing back on coredict.dct
 * 
 * @param dctFileRoot path to dictionary directory
 */
public void load(String dctFileRoot) {
  String dctFilePath = dctFileRoot + "/coredict.dct";
  Path serialObj = Paths.get(dctFileRoot + "/coredict.mem");

  if (Files.exists(serialObj) && loadFromObj(serialObj)) {

  } else {
    try {
      wordIndexTable = new short[PRIME_INDEX_LENGTH];
      charIndexTable = new char[PRIME_INDEX_LENGTH];
      for (int i = 0; i < PRIME_INDEX_LENGTH; i++) {
        charIndexTable[i] = 0;
        wordIndexTable[i] = -1;
      }
      wordItem_charArrayTable = new char[GB2312_CHAR_NUM][][];
      wordItem_frequencyTable = new int[GB2312_CHAR_NUM][];
      // int total =
      loadMainDataFromFile(dctFilePath);
      expandDelimiterData();
      mergeSameWords();
      sortEachItems();
      // log.info("load dictionary: " + dctFilePath + " total:" + total);
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage());
    }

    saveToObj(serialObj);
  }

}
 
Example 9
Source File: IsofoxConfig.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
public static boolean configPathValid(final CommandLine cmd, final String configItem)
{
    if(!cmd.hasOption(configItem))
        return true;

    final String filePath = cmd.getOptionValue(configItem);
    if(!Files.exists(Paths.get(filePath)))
    {
        ISF_LOGGER.error("invalid config path: {} = {}", configItem, filePath);
        return false;
    }

    return true;
}
 
Example 10
Source File: PidFileLocker.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
public void lock() throws IOException {
    if (PIDFILE.isEmpty()) {
        return;
    }
    System.out.println("Creating and locking file " + file.toAbsolutePath());
    if (Files.exists(file)) {
        throw new IOException("file " + file.toAbsolutePath() + " already exists");
    }
    Files.write(file, pid, StandardOpenOption.CREATE_NEW);
}
 
Example 11
Source File: ConfigFileStartupBuilder.java    From terracotta-platform with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
private Path convertToConfigFile() {
  Path generatedConfigFileDir = getServerWorkingDir().getParent().getParent().resolve("generated-configs");

  if (Files.exists(generatedConfigFileDir)) {
    // this builder is called for each server, but the CLI will generate the config directories for all.
    return generatedConfigFileDir;
  }

  List<String> command = new ArrayList<>();
  String scriptPath = getAbsolutePath(Paths.get("tools", "upgrade", "bin", "config-converter"));
  command.add(scriptPath);
  command.add("convert");

  for (Path tcConfig : getTcConfigs()) {
    command.add("-c");
    command.add(tcConfig.toString());
  }

  command.add("-t");
  command.add("properties");

  command.add("-d");
  command.add(getServerWorkingDir().relativize(generatedConfigFileDir).toString());

  command.add("-f"); //Do not fail for relative paths

  executeCommand(command, getServerWorkingDir());
  return generatedConfigFileDir;
}
 
Example 12
Source File: EncryptedFileSystemProvider.java    From encfs4j with Apache License 2.0 5 votes vote down vote up
@Override
public void checkAccess(Path file, AccessMode... modes) throws IOException {
	if (modes.length == 0) {
		if (Files.exists(EncryptedFileSystem.dismantle(file)))
			return;
		else
			throw new NoSuchFileException(file.toString());
	}

	// see
	// https://docs.oracle.com/javase/7/docs/api/java/nio/file/spi/FileSystemProvider.html#checkAccess%28java.nio.file.Path,%20java.nio.file.AccessMode...%29
	throw new UnsupportedOperationException("not implemented");
}
 
Example 13
Source File: GeneImpact.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
private final List<String> loadGenePanel(final String geneFile)
{
    final List<String> genePanelIds = Lists.newArrayList();

    if (!Files.exists(Paths.get(geneFile)))
        return genePanelIds;

    try
    {
        List<String> fileContents = Files.readAllLines(new File(geneFile).toPath());

        for(final String geneData : fileContents)
        {
            if(geneData.contains("GeneId"))
                continue;

            String[] items = geneData.split(",");
            if(items.length != 2)
            {
                LOGGER.error("invalid geneData({}) - expected 'GeneId,GeneName'");
                return genePanelIds;
            }

            genePanelIds.add(items[0]);
        }

        LOGGER.info("loaded genePanelFile({}) with {} genes", geneFile, fileContents.size());
    }
    catch(IOException e)
    {
        LOGGER.error("failed to load gene panel file({}): {}", geneFile, e.toString());
    }

    return genePanelIds;
}
 
Example 14
Source File: ParallelCallbackTest.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
/**
 * Tests sync where a directory exists with a matching name to an existing file in depot
 *
 * @throws Exception
 */
@Test
public void syncWithDirectoryMatchingDepotFile() throws Exception {
	String clientName = "test-client-duplicate-dir";
	String clientRoot = p4d.getPathToRoot() + "/" + clientName;

	String[] paths = {"//depot/basic/... //" + clientName + "/..."};

	FileUtils.deleteDirectory(new File(clientRoot));

	IClient testClient = Client.newClient(server, clientName, "testing parallel sync", clientRoot, paths);
	server.createClient(testClient);

	IClient testClientFromServer = server.getClient(clientName);
	Assert.assertNotNull(testClientFromServer);

	server.setCurrentClient(testClientFromServer);

	boolean pathExists = Files.exists(Paths.get(clientRoot));
	Assert.assertEquals(false, pathExists);

	// creates client workspace
	Files.createDirectories(Paths.get(clientRoot));

	//Create directory with a matching name to a depot file and the it should fail.
	createDirectory(clientRoot, "/readonly/sync/p4cmd/src/gnu/getopt/Getopt.java/foo");

	ParallelSyncOptions poptions = new ParallelSyncOptions(0, 0, 1, 1, 4, null);
	SyncOptions syncOptions = new SyncOptions();
	List<IFileSpec> fileSpec = FileSpecBuilder.makeFileSpecList("//depot/basic/...");
	List<IFileSpec> resultSpec = testClientFromServer.syncParallel(fileSpec, syncOptions, poptions);
	Assert.assertNotNull(resultSpec);
	Assert.assertTrue(resultSpec.size() > 10);
	new Helper().assertFileSpecError(resultSpec);
}
 
Example 15
Source File: RegionFolder.java    From BlockMap with MIT License 5 votes vote down vote up
public static CachedRegionFolder create(RegionFolder cached, boolean lazy, Path folder) throws IOException {
	if (!Files.exists(folder))
		Files.createDirectories(folder);
	Path file = folder.resolve("rendered.json.gz");
	if (!Files.exists(file))
		try (Writer writer = new OutputStreamWriter(new GZIPOutputStream(Files.newOutputStream(file, StandardOpenOption.CREATE,
				StandardOpenOption.WRITE), 8192, true))) {
			writer.write("{regions:[]}");
			writer.flush();
		}
	return new CachedRegionFolder(cached, lazy, file);
}
 
Example 16
Source File: MigrationService.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public String getM3modelFromJar(String jarPath) throws Exception {
	// TODO CHECK HERE
	String libM3 = jarPath + ".m3";
	if (!Files.exists(Paths.get(libM3), new LinkOption[] { LinkOption.NOFOLLOW_LINKS })) {
		String libJar = jarPath;
		boolean bLib1 = maracas.storeM3(libJar, libM3);
		logger.info("Lib1 store: " + bLib1);
		if (!bLib1) {
			logger.error("error computing {} m3 model", jarPath);
			throw new Exception();
		}
	}
	return libM3;
}
 
Example 17
Source File: JkCommandSet.java    From jeka with Apache License 2.0 5 votes vote down vote up
/**
 * Cleans the output directory.
 */
@JkDoc("Cleans the output directory.")
public void clean() {
    JkLog.info("Clean output directory " + getOutputDir());
    if (Files.exists(getOutputDir())) {
        JkPathTree.of(getOutputDir()).deleteContent();
    }
}
 
Example 18
Source File: SerializeVersionedXmlResourceIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@After
public void tearDown() throws Exception {
    if (Files.exists(DATABASE_PATH))
        Databases.removeDatabase(DATABASE_PATH);
}
 
Example 19
Source File: SwaggerGenMojo.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * The main execution method for this Mojo.
 *
 * @throws MojoExecutionException if any errors were encountered.
 */
@Override
public void execute() throws MojoExecutionException
{
    // Create the output directory if it doesn't already exist.
    getLog().debug("Creating output directory \"" + outputDirectory + "\".");
    java.nio.file.Path outputDirectoryPath = Paths.get(outputDirectory.toURI());
    if (!Files.exists(outputDirectoryPath))
    {
        try
        {
            Files.createDirectories(outputDirectoryPath);
        }
        catch (IOException e)
        {
            throw new MojoExecutionException("Unable to create directory for output path \"" + outputDirectoryPath + "\".", e);
        }
    }

    // Get a new Swagger metadata object.
    Swagger swagger = getSwagger();

    // Find all the model classes.
    // Note: this needs to be done before we process the REST controllers below because it finds the modelErrorClass.
    ModelClassFinder modelClassFinder = new ModelClassFinder(getLog(), modelJavaPackage, modelErrorClassName);

    // Find and process all the REST controllers and add them to the Swagger metadata.
    RestControllerProcessor restControllerProcessor =
        new RestControllerProcessor(getLog(), swagger, restJavaPackage, tagPatternParameter, modelClassFinder.getModelErrorClass());

    XsdParser xsdParser = null;
    if (xsdName != null)
    {
        xsdParser = new XsdParser(xsdName);
    }

    // Generate the definitions into Swagger based on the model classes collected.
    new DefinitionGenerator(getLog(), swagger, restControllerProcessor.getExampleClassNames(), modelClassFinder.getModelClasses(), xsdParser);

    if (applyOperationsFilter != null && applyOperationsFilter.equals(Boolean.TRUE))
    {
        OperationsFilter specFilter = new OperationsFilter(includeOperations);
        swagger = new SpecFilter().filter(swagger, specFilter, null, null, null);
    }

    // Write to Swagger information to a YAML file.
    createYamlFile(swagger);
}
 
Example 20
Source File: AbsStorageProvider.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
private void waitUntilNonSpdkCreated(String devicePath, long waitTimeoutAfterCreateMillis)
    throws StorageException
{
    final Object syncObj = new Object();
    FileObserver fileObserver = new FileObserver()
    {
        @Override
        public void fileEvent(FileEntry watchEntry)
        {
            synchronized (syncObj)
            {
                syncObj.notify();
            }
        }
    };
    try
    {
        synchronized (syncObj)
        {
            long start = System.currentTimeMillis();
            fsWatch.addFileEntry(
                new FileEntry(
                    Paths.get(devicePath),
                    Event.CREATE,
                    fileObserver
                )
            );
            try
            {
                errorReporter.logTrace(
                    "Waiting until device [%s] appears (up to %dms)",
                    devicePath,
                    waitTimeoutAfterCreateMillis
                );

                syncObj.wait(waitTimeoutAfterCreateMillis);
            }
            catch (InterruptedException interruptedExc)
            {
                throw new StorageException(
                    "Interrupted exception while waiting for device '" + devicePath + "' to show up",
                    interruptedExc
                );
            }
            if (!Files.exists(Paths.get(devicePath)))
            {
                throw new StorageException(
                    "Device '" + devicePath + "' did not show up in " +
                        waitTimeoutAfterCreateMillis + "ms"
                );
            }
            errorReporter.logTrace(
                "Device [%s] appeared after %sms",
                devicePath,
                System.currentTimeMillis() - start
            );
        }
    }
    catch (IOException exc)
    {
        throw new StorageException(
            "Unable to register file watch event for device '" + devicePath + "' being created",
            exc
        );
    }
}