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

The following examples show how to use java.nio.file.Files#notExists() . These examples are extracted from open source projects. 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 Project: XACML   File: PolicyWorkspace.java    License: MIT License 6 votes vote down vote up
protected Path	getNextFilename(Path parent, String filename) {
	filename = FilenameUtils.removeExtension(filename);
	Path newFile = null;
	int i = 0;
	while (true) {
		newFile = Paths.get(parent.toString(), String.format("%s(%02d)", filename, i++) + ".xml");
		if (Files.notExists(newFile)) {
			return newFile;
		}
		if (i == 100) {
			logger.error("Could not construct a new name for cloned policy.");
			return null;
		}
	}
	
}
 
Example 2
Source Project: ha-bridge   File: GroupRepository.java    License: Apache License 2.0 6 votes vote down vote up
private String repositoryReader(Path filePath) {

		String content = null;
		if(Files.notExists(filePath)){
			log.debug("Error, the file: " + filePath + " - does not exist. continuing...");
			return null;
		}

		if(!Files.isReadable(filePath)){
			log.warn("Error, the file: " + filePath + " - is not readable. continuing...");
			return null;
		}
		
		try {
			content = new String(Files.readAllBytes(filePath));
		} catch (IOException e) {
			log.error("Error reading the file: " + filePath + " message: " + e.getMessage(), e);
		}
		
		return content;
	}
 
Example 3
Source Project: EagleFactions   File: HOCONFactionStorage.java    License: MIT License 5 votes vote down vote up
public HOCONFactionStorage(final Path configDir)
{
    this.configDir = configDir;
    this.factionsDir = configDir.resolve("factions");
    this.factionLoaders = new HashMap<>();

    if (Files.notExists(this.factionsDir))
    {
        try
        {
            Files.createDirectory(this.factionsDir);
            preCreate();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    // Backwards compatibility with 0.14.x
    // Convert old file format to the new one.
    // This code will be removed in future releases.
    if (Files.exists(this.configDir.resolve("data")) && Files.exists(this.configDir.resolve("data").resolve("factions.conf")))
    {
        migrateOldFactionsDataToNewFormat();
    }

    loadFactionsConfigurationLoaders();
}
 
Example 4
/**
 * Creates a new folder.
 *
 * @param folderPath The path where the folder gets created
 * @return Path
 * @throws Exception exception
 */
public static Path createFolder(String folderPath) throws Exception {
    Path path = Paths.get(folderPath);
    if (Files.notExists(path)) {
        return Files.createDirectories(path);
    }
    return path;
}
 
Example 5
Source Project: jimfs   File: PathSubject.java    License: Apache License 2.0 5 votes vote down vote up
/** Asserts that the path does not exist. */
public PathSubject doesNotExist() {
  if (!Files.notExists(actual, linkOptions)) {
    failWithActual(simpleFact("expected not to exist"));
  }
  if (Files.exists(actual, linkOptions)) {
    failWithActual(simpleFact("expected not to exist"));
  }
  return this;
}
 
Example 6
@Test
public void testNoLiveDataWhenNoGraph() throws Exception {
    String tempDir = holder.props.getProperty("data.folder");

    Path userReportFolder = Paths.get(tempDir, "data", getUserName());
    if (Files.notExists(userReportFolder)) {
        Files.createDirectories(userReportFolder);
    }

    clientPair.hardwareClient.send("hardware vw 88 111");
    verify(clientPair.appClient.responseMock, timeout(500)).channelRead(any(), eq(new HardwareMessage(1, b("1-0 vw 88 111"))));

    Superchart enhancedHistoryGraph = new Superchart();
    enhancedHistoryGraph.id = 432;
    enhancedHistoryGraph.width = 8;
    enhancedHistoryGraph.height = 4;
    DataStream dataStream = new DataStream((short) 88, PinType.VIRTUAL);
    GraphDataStream graphDataStream = new GraphDataStream(null, GraphType.LINE, 0, 0, dataStream, null, 0, null, null, null, 0, 0, false, null, false, false, false, null, 0, false, 0);
    enhancedHistoryGraph.dataStreams = new GraphDataStream[] {
            graphDataStream
    };

    clientPair.appClient.createWidget(1, enhancedHistoryGraph);
    clientPair.appClient.verifyResult(ok(1));

    clientPair.appClient.getEnhancedGraphData(1, 432, GraphPeriod.LIVE);
    verify(clientPair.appClient.responseMock, timeout(500)).channelRead(any(), eq(new ResponseMessage(2, NO_DATA)));
}
 
Example 7
Source Project: bundletool   File: BuildApksManager.java    License: Apache License 2.0 5 votes vote down vote up
public Path execute() {
  validateInput();

  Path outputDirectory =
      command.getCreateApkSetArchive()
          ? command.getOutputFile().getParent()
          : command.getOutputFile();
  if (outputDirectory != null && Files.notExists(outputDirectory)) {
    logger.info("Output directory '" + outputDirectory + "' does not exist, creating it.");
    FileUtils.createDirectories(outputDirectory);
  }

  // Fail fast with ADB before generating any APKs.
  Optional<DeviceSpec> deviceSpec = command.getDeviceSpec();
  if (command.getGenerateOnlyForConnectedDevice()) {
    deviceSpec = Optional.of(getDeviceSpecFromConnectedDevice());
  }

  try (ZipFile bundleZip = new ZipFile(command.getBundlePath().toFile())) {
    executeWithZip(bundleZip, deviceSpec, command.getSourceStamp());
  } catch (IOException e) {
    throw new UncheckedIOException(
        String.format(
            "An error occurred when processing the bundle '%s'.", command.getBundlePath()),
        e);
  } finally {
    if (command.isExecutorServiceCreatedByBundleTool()) {
      command.getExecutorService().shutdown();
    }
  }

  return command.getOutputFile();
}
 
Example 8
Source Project: twister2   File: Twister2Submitter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Delete the directory that has the Job package for the checkpointed job
 */
private static void deleteJobDir(String jobID, Config config) {
  // job package directory
  String jobDir = FsContext.uploaderJobDirectory(config) + File.separator + jobID;
  Path jobPackageFile = Paths.get(jobDir);
  if (Files.notExists(jobPackageFile)) {
    LOG.severe("Job Package directory does not exist: " + jobDir);
  } else {
    LOG.info("Cleaning job directory: " + jobDir);
    FileUtils.deleteDir(jobDir);
  }
}
 
Example 9
@Override
protected ModelNode buildRequestWithoutHeaders(CommandContext ctx) throws CommandFormatException {
    format = getFormat(ctx);
    targetPath = new File(targetFileArg.getValue(ctx.getParsedCommandLine(), true)).toPath();
    if (Files.notExists(targetPath.getParent()) || !Files.isDirectory(targetPath.getParent())) {
        throw new OperationFormatException("Incorrect destination directory " + targetPath.getParent());
    }
    DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
    builder.setOperationName("product-info");
    builder.getModelNode().get(FILE).set(true);
    builder.getModelNode().get("format").set(format);
    ModelNode request = builder.buildRequest();
    return request;
}
 
Example 10
Map<String,String> jdeps(List<String> args, Path dotfile) throws IOException {
    if (Files.exists(dotoutput)) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dotoutput)) {
            for (Path p : stream) {
                Files.delete(p);
            }
        }
        Files.delete(dotoutput);
    }
    // invoke jdeps
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    System.err.println("jdeps " + args.stream().collect(Collectors.joining(" ")));
    int rc = com.sun.tools.jdeps.Main.run(args.toArray(new String[0]), pw);
    pw.close();
    String out = sw.toString();
    if (!out.isEmpty())
        System.err.println(out);
    if (rc != 0)
        throw new Error("jdeps failed: rc=" + rc);

    // check output files
    if (Files.notExists(dotfile)) {
        throw new RuntimeException(dotfile + " doesn't exist");
    }
    return parse(dotfile);
}
 
Example 11
/**
 * Creates a new FileConfig with the chosen settings.
 *
 * @return the config
 */
public FileConfig build() {
	FileConfig fileConfig;
	if (sync) {
		fileConfig = new WriteSyncFileConfig<>(getConfig(), file, charset, writer, writingMode,
			parser, parsingMode, nefAction);
	} else {
		if (autoreload) {
			concurrent();
			// Autoreloading is done from a background thread, therefore we need thread-safety
			// This isn't needed with WriteSyncFileConfig because it synchronizes loads and writes.
		}
		fileConfig = new WriteAsyncFileConfig<>(getConfig(), file, charset, writer, writingMode,
			parser, parsingMode, nefAction);
	}
	if (autoreload) {
		if (Files.notExists(file)) {
			try {
				nefAction.run(file, format);
			} catch (IOException e) {
				throw new WritingException(
					"An exception occured while executing the FileNotFoundAction for file "
					+ file, e
				);
			}
		}
		fileConfig = new AutoreloadFileConfig(fileConfig);
	}
	if (autosave) {
		return buildAutosave(fileConfig);
	}
	return buildNormal(fileConfig);
}
 
Example 12
private FileMetaData readMetaDataByUnlock(Path metaPath) throws IOException {
    if (Files.notExists(metaPath)) {
        return null;
    }
    String metaString = new String(Files.readAllBytes(metaPath), "UTF-8");
    FileMetaData metaData = JSON.parseObject(metaString, FileMetaData.class);
    return metaData;
}
 
Example 13
Source Project: ofdrw   File: ResDir.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 向目录中加入资源
 * <p>
 * 加入的资源将会被复制到指定目录,与原有资源无关
 *
 * @param res 资源
 * @return this
 * @throws IOException 文件复制过程中发生的异常
 */
public ResDir add(Path res) throws IOException {
    if (res == null) {
        return this;
    }
    if (Files.notExists(res)) {
        throw new IllegalArgumentException("加入的资源不存在: " + res.toAbsolutePath().toString());
    }
    this.putFile(res);
    return this;
}
 
Example 14
Source Project: EagleFactions   File: BackupStorage.java    License: MIT License 5 votes vote down vote up
private void createFileIfNotExists(final Path path, final boolean directory) throws IOException
{
    if (Files.notExists(path))
    {
        if (directory)
        {
            Files.createDirectory(path);
        }
        else
        {
            Files.createFile(path);
        }
    }
}
 
Example 15
private static void checkOut(String path) throws FileNotFoundException {
    if (Files.notExists(FileSystems.getDefault().getPath(path)))
        throw new FileNotFoundException(path);
}
 
Example 16
@Test(dataProvider = "singleModule")
public void singleModule(String extraJmodArg,
                         List<String> addModsTokens,
                         Consumer<ToolResult> assertExitCode,
                         List<String> expectedOutput,
                         List<String> unexpectedOutput)
    throws Throwable
{
    if (Files.notExists(JDK_JMODS)) {
        System.out.println("JDK jmods not found test cannot run.");
        return;
    }

    FileUtils.deleteFileTreeUnchecked(JMODS_DIR);
    FileUtils.deleteFileTreeUnchecked(IMAGE);
    Files.createDirectories(JMODS_DIR);
    Path converterJmod = JMODS_DIR.resolve("converter.jmod");

    jmod("create",
         "--class-path", MODS_DIR.resolve("message.converter").toString(),
         extraJmodArg,
         converterJmod.toString())
        .assertSuccess();

    String mpath = JDK_JMODS.toString() + File.pathSeparator + JMODS_DIR.toString();
    jlink("--module-path", mpath,
          "--add-modules", JAVA_BASE + ",message.converter",
          "--output", IMAGE.toString())
         .assertSuccess();

    for (String addModsToken : addModsTokens) {
        String[] props = new String[] {"", "-Djdk.system.module.finder.disabledFastPath"};
        for (String systemProp : props)
            java(IMAGE,
                 systemProp,
                 "--add-modules", addModsToken,
                 "-cp", CP_DIR.toString(),
                 "test.ConvertToLowerCase", "HEllo WoRlD")
                .resultChecker(assertExitCode)
                .resultChecker(r -> {
                    expectedOutput.forEach(e -> r.assertContains(e));
                    unexpectedOutput.forEach(e -> r.assertDoesNotContains(e));
                });
    }
}
 
Example 17
@Test
public void cleanNotUsedPinDataWorksAsExpectedForSuperChart() throws Exception {
    HistoryGraphUnusedPinDataCleanerWorker cleaner = new HistoryGraphUnusedPinDataCleanerWorker(holder.userDao, holder.reportingDiskDao);

    Superchart enhancedHistoryGraph = new Superchart();
    enhancedHistoryGraph.id = 432;
    enhancedHistoryGraph.width = 8;
    enhancedHistoryGraph.height = 4;
    DataStream dataStream1 = new DataStream((short) 8, PinType.DIGITAL);
    DataStream dataStream2 = new DataStream((short) 9, PinType.DIGITAL);
    DataStream dataStream3 = new DataStream((short) 10, PinType.DIGITAL);
    GraphDataStream graphDataStream1 = new GraphDataStream(null, GraphType.LINE, 0, 0, dataStream1, AggregationFunctionType.MAX, 0, null, null, null, 0, 0, false, null, false, false, false, null, 0, false, 0);
    GraphDataStream graphDataStream2 = new GraphDataStream(null, GraphType.LINE, 0, 0, dataStream2, AggregationFunctionType.MAX, 0, null, null, null, 0, 0, false, null, false, false, false, null, 0, false, 0);
    GraphDataStream graphDataStream3 = new GraphDataStream(null, GraphType.LINE, 0, 0, dataStream3, AggregationFunctionType.MAX, 0, null, null, null, 0, 0, false, null, false, false, false, null, 0, false, 0);
    enhancedHistoryGraph.dataStreams = new GraphDataStream[] {
            graphDataStream1,
            graphDataStream2,
            graphDataStream3,
    };

    clientPair.appClient.createWidget(1, enhancedHistoryGraph);
    clientPair.appClient.verifyResult(ok(1));

    String tempDir = holder.props.getProperty("data.folder");

    Path userReportFolder = Paths.get(tempDir, "data", getUserName());
    if (Files.notExists(userReportFolder)) {
        Files.createDirectories(userReportFolder);
    }

    //this file has corresponding history graph
    Path pinReportingDataPath1 = Paths.get(tempDir, "data", getUserName(),
            ReportingDiskDao.generateFilename(1, 0, PinType.DIGITAL, (short) 8, GraphGranularityType.HOURLY));
    FileUtils.write(pinReportingDataPath1, 1.11D, 1111111);

    Path pinReportingDataPath2 = Paths.get(tempDir, "data", getUserName(),
            ReportingDiskDao.generateFilename(1, 0, PinType.DIGITAL, (short) 9, GraphGranularityType.HOURLY));
    FileUtils.write(pinReportingDataPath2, 1.11D, 1111111);

    Path pinReportingDataPath3 = Paths.get(tempDir, "data", getUserName(),
            ReportingDiskDao.generateFilename(1, 0, PinType.DIGITAL, (short) 10, GraphGranularityType.HOURLY));
    FileUtils.write(pinReportingDataPath3, 1.11D, 1111111);

    //those are not
    Path pinReportingDataPath4 = Paths.get(tempDir, "data", getUserName(),
            ReportingDiskDao.generateFilename(1, 0, PinType.DIGITAL, (short) 11, GraphGranularityType.HOURLY));
    FileUtils.write(pinReportingDataPath4, 1.11D, 1111111);

    assertTrue(Files.exists(pinReportingDataPath1));
    assertTrue(Files.exists(pinReportingDataPath2));
    assertTrue(Files.exists(pinReportingDataPath3));
    assertTrue(Files.exists(pinReportingDataPath4));

    cleaner.run();

    assertTrue(Files.exists(pinReportingDataPath1));
    assertTrue(Files.exists(pinReportingDataPath2));
    assertTrue(Files.exists(pinReportingDataPath3));
    assertTrue(Files.notExists(pinReportingDataPath4));
}
 
Example 18
Source Project: GriefDefender   File: GDClaim.java    License: MIT License 4 votes vote down vote up
public ClaimResult changeType(ClaimType type, Optional<UUID> ownerUniqueId, CommandSource src) {
    if (type == this.type) {
        return new GDClaimResult(ClaimResultType.SUCCESS);
    }

    final Player sourcePlayer = src instanceof Player ? (Player) src : null;
    GDChangeClaimEvent.Type event = new GDChangeClaimEvent.Type(this, type);
    GriefDefender.getEventManager().post(event);
    if (event.cancelled()) {
        return new GDClaimResult(ClaimResultType.CLAIM_EVENT_CANCELLED, event.getMessage().orElse(null));
    }

    final GDClaimManager claimWorldManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(this.world.getUniqueId());
    final GDPlayerData sourcePlayerData = src != null && src instanceof Player ? claimWorldManager.getOrCreatePlayerData(((Player) src).getUniqueId()) : null;
    UUID newOwnerUUID = ownerUniqueId.orElse(this.ownerUniqueId);
    final ClaimResult result = this.validateClaimType(type, newOwnerUUID, sourcePlayerData);
    if (!result.successful()) {
        return result;
    }

    if (type == ClaimTypes.ADMIN) {
        newOwnerUUID = GriefDefenderPlugin.ADMIN_USER_UUID;
    }

    final String fileName = this.getClaimStorage().filePath.getFileName().toString();
    final Path newPath = this.getClaimStorage().folderPath.getParent().resolve(type.getName().toLowerCase()).resolve(fileName);
    try {
        if (Files.notExists(newPath.getParent())) {
            Files.createDirectories(newPath.getParent());
        }
        Files.move(this.getClaimStorage().filePath, newPath);
        if (type == ClaimTypes.TOWN) {
            this.setClaimStorage(new TownStorageData(newPath, this.getWorldUniqueId(), newOwnerUUID, this.cuboid));
        } else {
            this.setClaimStorage(new ClaimStorageData(newPath, this.getWorldUniqueId(), (ClaimDataConfig) this.getInternalClaimData()));
        }
        this.claimData = this.claimStorage.getConfig();
        this.getClaimStorage().save();
    } catch (IOException e) {
        e.printStackTrace();
        return new GDClaimResult(ClaimResultType.CLAIM_NOT_FOUND, TextComponent.of(e.getMessage()));
    }

    // If switched to admin or new owner, remove from player claim list
    if (type == ClaimTypes.ADMIN || (this.ownerUniqueId != null && !this.ownerUniqueId.equals(newOwnerUUID))) {
        final Set<Claim> currentPlayerClaims = claimWorldManager.getInternalPlayerClaims(this.ownerUniqueId);
        if (currentPlayerClaims != null) {
            currentPlayerClaims.remove(this);
        }
    }
    if (type != ClaimTypes.ADMIN) {
        final Set<Claim> newPlayerClaims = claimWorldManager.getInternalPlayerClaims(newOwnerUUID);
        if (newPlayerClaims != null && !newPlayerClaims.contains(this)) {
            newPlayerClaims.add(this);
        }
    }

    if (!this.isAdminClaim() && this.ownerPlayerData != null) {
        final Player player = Sponge.getServer().getPlayer(this.ownerUniqueId).orElse(null);
        if (player != null) {
            this.ownerPlayerData.revertClaimVisual(this);
        }
    }

    // revert visuals for all players watching this claim
    List<UUID> playersWatching = new ArrayList<>(this.playersWatching);
    for (UUID playerUniqueId : playersWatching) {
        final Player spongePlayer = Sponge.getServer().getPlayer(playerUniqueId).orElse(null);
        final GDPlayerData playerData = claimWorldManager.getOrCreatePlayerData(playerUniqueId);
        if (spongePlayer != null) {
            playerData.revertClaimVisual(this);
        }
    }

    if (!newOwnerUUID.equals(GriefDefenderPlugin.ADMIN_USER_UUID)) {
        this.setOwnerUniqueId(newOwnerUUID);
    }
    this.setType(type);
    this.claimVisual = null;
    this.getInternalClaimData().setRequiresSave(true);
    this.getClaimStorage().save();
    return new GDClaimResult(ClaimResultType.SUCCESS);
}
 
Example 19
private void checkExistingScenariosFolder(String projectCode) throws IOException {
    Path scenariosPath = Paths.get(projectsPath, projectCode, SCENARIOS_FOLDER_NAME);
    if (Files.notExists(scenariosPath)) {
        Files.createDirectory(scenariosPath);
    }
}
 
Example 20
private static void checkOut(String path) throws FileNotFoundException {
    if (Files.notExists(FileSystems.getDefault().getPath(path)))
        throw new FileNotFoundException(path);
}