下面列出了怎么用java.nio.file.FileAlreadyExistsException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public IndexOutput createTempOutput(String prefix, String suffix, IOContext context) throws IOException {
ensureOpen();
maybeDeletePendingFiles();
while (true) {
try {
String name = getTempFileName(prefix, suffix, nextTempFileCounter.getAndIncrement());
if (pendingDeletes.contains(name)) {
continue;
}
return new FSIndexOutput(name,
StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
} catch (FileAlreadyExistsException faee) {
// Retry with next incremented name
}
}
}
private boolean mkdirsInternal(File file) throws IOException {
if (file.isDirectory()) {
return true;
}
else if (file.exists() && !file.isDirectory()) {
// Important: The 'exists()' check above must come before the 'isDirectory()' check to
// be safe when multiple parallel instances try to create the directory
// exists and is not a directory -> is a regular file
throw new FileAlreadyExistsException(file.getAbsolutePath());
}
else {
File parent = file.getParentFile();
return (parent == null || mkdirsInternal(parent)) && (file.mkdir() || file.isDirectory());
}
}
@Override
public FSDataOutputStream create(final Path filePath, final WriteMode overwrite) throws IOException {
checkNotNull(filePath, "filePath");
if (exists(filePath) && overwrite == WriteMode.NO_OVERWRITE) {
throw new FileAlreadyExistsException("File already exists: " + filePath);
}
final Path parent = filePath.getParent();
if (parent != null && !mkdirs(parent)) {
throw new IOException("Mkdirs failed to create " + parent);
}
final File file = pathToFile(filePath);
return new LocalDataOutputStream(file);
}
private boolean mkdirsInternal(File file) throws IOException {
if (file.isDirectory()) {
return true;
}
else if (file.exists() && !file.isDirectory()) {
// Important: The 'exists()' check above must come before the 'isDirectory()' check to
// be safe when multiple parallel instances try to create the directory
// exists and is not a directory -> is a regular file
throw new FileAlreadyExistsException(file.getAbsolutePath());
}
else {
File parent = file.getParentFile();
return (parent == null || mkdirsInternal(parent)) && (file.mkdir() || file.isDirectory());
}
}
@Override
public FSDataOutputStream create(final Path filePath, final WriteMode overwrite) throws IOException {
checkNotNull(filePath, "filePath");
if (exists(filePath) && overwrite == WriteMode.NO_OVERWRITE) {
throw new FileAlreadyExistsException("File already exists: " + filePath);
}
final Path parent = filePath.getParent();
if (parent != null && !mkdirs(parent)) {
throw new IOException("Mkdirs failed to create " + parent);
}
final File file = pathToFile(filePath);
return new LocalDataOutputStream(file);
}
private <T> T throwException(String segmentName, Exception e) throws StreamSegmentException {
if (e instanceof NoSuchFileException || e instanceof FileNotFoundException) {
throw new StreamSegmentNotExistsException(segmentName);
}
if (e instanceof FileAlreadyExistsException) {
throw new StreamSegmentExistsException(segmentName);
}
if (e instanceof IndexOutOfBoundsException) {
throw new IllegalArgumentException(e.getMessage());
}
if (e instanceof AccessControlException
|| e instanceof AccessDeniedException
|| e instanceof NonWritableChannelException) {
throw new StreamSegmentSealedException(segmentName, e);
}
throw Exceptions.sneakyThrow(e);
}
@Override
protected void prepare() {
LOG.debug("在本地写一个pid文件记录当前进程id,提供给stop脚本读取");
try {
PlainFileUtil.newFile(PID_FILE_PATH, JavaPIDUtil.getPID() + "");
} catch (FileAlreadyExistsException e) {
LOG.warn(e.getMessage() + " 执行删除旧pid文件,然后新建pid文件。");
PlainFileUtil.deleteFile(PID_FILE_PATH);
try {
PlainFileUtil.newFile(PID_FILE_PATH, JavaPIDUtil.getPID() + "");
} catch (FileAlreadyExistsException ignored) {
LOG.error(ignored);
}
}
PlainFileUtil.deleteOnExit(PID_FILE_PATH);
}
@Test
public void passwordFileAlreadyExists() {
final Config config = mock(Config.class);
final Path pwdFile = mock(Path.class);
final String path = "somepath";
when(pwdFile.toString()).thenReturn(path);
when(filesDelegate.exists(pwdFile)).thenReturn(true);
final Throwable ex = catchThrowable(() -> writer.updateAndWrite(null, config, pwdFile));
assertThat(ex).isExactlyInstanceOf(FileAlreadyExistsException.class);
assertThat(ex.getMessage()).contains(path);
verify(filesDelegate).exists(pwdFile);
}
public static void unzip(Path zipFile, Path targetDir) throws IOException {
try {
if (!Files.exists(targetDir)) {
Files.createDirectories(targetDir);
}
} catch (FileAlreadyExistsException fae) {
throw new IOException("Could not create directory '" + targetDir + "' as a file already exists with the same name");
}
try (FileSystem zipfs = newFileSystem(zipFile)) {
for (Path zipRoot : zipfs.getRootDirectories()) {
copyFromZip(zipRoot, targetDir);
}
} catch (IOException | ZipError ioe) {
// TODO: (at a later date) Get rid of the ZipError catching (and instead only catch IOException)
// since it's a JDK bug which threw the undeclared ZipError instead of an IOException.
// Java 9 fixes it https://bugs.openjdk.java.net/browse/JDK-8062754
throw new IOException("Could not unzip " + zipFile + " to target dir " + targetDir, ioe);
}
}
@Override
protected Lock obtainFSLock(FSDirectory dir, String lockName) throws IOException {
Path lockDir = dir.getDirectory();
// Ensure that lockDir exists and is a directory.
// note: this will fail if lockDir is a symlink
Files.createDirectories(lockDir);
Path lockFile = lockDir.resolve(lockName);
// create the file: this will fail if it already exists
try {
Files.createFile(lockFile);
} catch (FileAlreadyExistsException | AccessDeniedException e) {
// convert optional specific exception to our optional specific exception
throw new LockObtainFailedException("Lock held elsewhere: " + lockFile, e);
}
// used as a best-effort check, to see if the underlying file has changed
final FileTime creationTime = Files.readAttributes(lockFile, BasicFileAttributes.class).creationTime();
return new SimpleFSLock(lockFile, creationTime);
}
/**
* Create password file to be written with access permissions to read
* and write by user only.
* <p/>
* @return Value of <code>true</code> if new file was created
* or <code>false</code> otherwise
*/
private boolean createFilePosix() {
final String METHOD = "createFilePosix";
boolean success = false;
try {
if (Files.notExists(file, new LinkOption[0])) {
Files.createFile(file, PosixFilePermissions
.asFileAttribute(CREATE_FILE_PERMISSIONS));
success = true;
} else {
Files.setPosixFilePermissions(file, CREATE_FILE_PERMISSIONS);
LOGGER.log(Level.INFO, METHOD, "exists", file.toString());
}
} catch (UnsupportedOperationException uoe) {
LOGGER.log(Level.INFO, METHOD, "unsupported", file.toString());
} catch (FileAlreadyExistsException faee) {
LOGGER.log(Level.INFO, METHOD, "exists", file.toString());
} catch (IOException ioe) {
LOGGER.log(Level.INFO, METHOD, "ioException", ioe);
}
return success;
}
@Test
void testAddFileAndDirectory() throws FileAlreadyExistsException, DirectoryNotWriteableException, NoSuchPathException, DirectoryNotReadableException, DirectoryAlreadyExistsException {
sh.changeDirectory("/");
sh.createDirectory("test");
assertThat(sh.listWorkingDirectory(), containsInAnyOrder(
"f_a.txt",
"f_b.txt",
"d_a",
"d_b",
"test"
));
sh.changeDirectory("test");
sh.createFile("bingo.txt", 5);
assertThat(sh.listWorkingDirectory(), containsInAnyOrder(
"bingo.txt"
));
}
/**
* Create brand new key store protected by a given password, and store it in a file.
*
* @param keyStoreFile The file where the key store should be.
* @param password Password to protect the key store.
* @return Freshly instantiated key store, in a newly created file.
* @throws IOException If file already exists or there is a problem writing the file.
* @throws KeyStoreException If something's happened to the key store.
*/
public static KeyStoreHandler create(final File keyStoreFile, final char... password)
throws IOException, KeyStoreException {
if (keyStoreFile == null) {
throw new FileNotFoundException(null);
} else if (keyStoreFile.exists()) {
throw new FileAlreadyExistsException(keyStoreFile.getAbsolutePath());
}
final KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
// get user password and file input stream
try {
ks.load(null, password);
} catch (final Exception ex) {
throw new IllegalStateException(ex);
}
// store the newly created key store
final SecretKeyFactory skf = getSecretKeyFactory();
final KeyStoreHandler ksh = new KeyStoreHandler(ks, password, keyStoreFile, skf);
LOGGER.debug("Creating keystore {}.", keyStoreFile);
ksh.save();
return ksh;
}
/**
* Ensures configured directory {@code path} exists.
* @throws IOException if {@code path} exists, but is not a directory, not accessible, or broken symbolic link.
*/
static void ensureDirectoryExists(Path path) throws IOException {
// this isn't atomic, but neither is createDirectories.
if (Files.isDirectory(path)) {
// verify access, following links (throws exception if something is wrong)
// we only check READ as a sanity test
path.getFileSystem().provider().checkAccess(path.toRealPath(), AccessMode.READ);
} else {
// doesn't exist, or not a directory
try {
Files.createDirectories(path);
} catch (FileAlreadyExistsException e) {
// convert optional specific exception so the context is clear
IOException e2 = new NotDirectoryException(path.toString());
e2.addSuppressed(e);
throw e2;
}
}
}
/**
* Create directories needed based on configuration.
*
* @param configuration
* @throws IOException
*/
public static void createDirectoriesOnWorker(SubProcessConfiguration configuration)
throws IOException {
try {
Path path = Paths.get(configuration.getWorkerPath());
if (!path.toFile().exists()) {
Files.createDirectories(path);
LOG.info(String.format("Created Folder %s ", path.toFile()));
}
} catch (FileAlreadyExistsException ex) {
LOG.warn(
String.format(
" Tried to create folder %s which already existsed, this should not happen!",
configuration.getWorkerPath()),
ex);
}
}
/**
* Returns whether the given file may be uploaded.
*
* @return Whether the given file may be uploaded.
*/
public void checkUploadAllowed(Path file, boolean checkFileExists) throws IOException {
if (!isInMusicFolder(file)) {
throw new AccessDeniedException(file.toString(), null, "Specified location is not in writable music folder");
}
if (checkFileExists && Files.exists(file)) {
throw new FileAlreadyExistsException(file.toString(), null, "File already exists");
}
}
public static Path getOrCreateDirectory(Path dirPath, String dirLabel) {
if (!Files.isDirectory(dirPath.getParent())) {
getOrCreateDirectory(dirPath.getParent(), "parent of " + dirLabel);
}
if (!Files.isDirectory(dirPath)) {
LOGGER.debug(CORE, "Making {} directory : {}", dirLabel, dirPath);
try {
Files.createDirectory(dirPath);
} catch (IOException e) {
if (e instanceof FileAlreadyExistsException) {
LOGGER.fatal(CORE, "Failed to create {} directory - there is a file in the way", dirLabel);
} else {
LOGGER.fatal(CORE, "Problem with creating {} directory (Permissions?)", dirLabel, e);
}
throw new RuntimeException("Problem creating directory", e);
}
LOGGER.debug(CORE, "Created {} directory : {}", dirLabel, dirPath);
} else {
LOGGER.debug(CORE, "Found existing {} directory : {}", dirLabel, dirPath);
}
return dirPath;
}
/**
* Creates and saves a service account key the App Engine default service account.
*
* @param credential credential to use to create a service account key
* @param projectId GCP project ID for {@code serviceAccountId}
* @param destination path of a key file to be saved
*/
public static void createAppEngineDefaultServiceAccountKey(IGoogleApiFactory apiFactory,
Credential credential, String projectId, Path destination)
throws FileAlreadyExistsException, IOException {
Preconditions.checkNotNull(credential, "credential not given");
Preconditions.checkState(!projectId.isEmpty(), "project ID empty");
Preconditions.checkArgument(destination.isAbsolute(), "destination not absolute");
if (!Files.exists(destination.getParent())) {
Files.createDirectories(destination.getParent());
}
Iam iam = apiFactory.newIamApi(credential);
Keys keys = iam.projects().serviceAccounts().keys();
String projectEmail = projectId;
// The appengine service account for google.com:gcloud-for-eclipse-testing
// would be [email protected]m.
if (projectId.contains(":")) {
String[] parts = projectId.split(":");
projectEmail = parts[1] + "." + parts[0];
}
String serviceAccountId = projectEmail + "@appspot.gserviceaccount.com";
String keyId = "projects/" + projectId + "/serviceAccounts/" + serviceAccountId;
CreateServiceAccountKeyRequest createRequest = new CreateServiceAccountKeyRequest();
ServiceAccountKey key = keys.create(keyId, createRequest).execute();
byte[] jsonKey = Base64.decodeBase64(key.getPrivateKeyData());
Files.write(destination, jsonKey);
}
private ModelArchive createModelArchive(
String modelName,
String url,
String handler,
Manifest.RuntimeType runtime,
String defaultModelName)
throws FileAlreadyExistsException, ModelException, IOException {
ModelArchive archive = ModelArchive.downloadModel(configManager.getModelStore(), url);
if (modelName == null || modelName.isEmpty()) {
if (archive.getModelName() == null || archive.getModelName().isEmpty()) {
archive.getManifest().getModel().setModelName(defaultModelName);
}
} else {
archive.getManifest().getModel().setModelName(modelName);
}
if (runtime != null) {
archive.getManifest().setRuntime(runtime);
}
if (handler != null) {
archive.getManifest().getModel().setHandler(handler);
} else if (archive.getHandler() == null || archive.getHandler().isEmpty()) {
archive.getManifest().getModel().setHandler(configManager.getTsDefaultServiceHandler());
}
archive.validate();
return archive;
}
@Override
public void getReport(List<ScenarioIdentityRo> identities, ZipOutputStream outputStream) throws Exception {
log.info("Scenario identities to generate report: {}", identities.size());
reportGenerator.clear();
identities.forEach(identity -> {
try {
List<StepResult> results = loadResults(identity);
if (results != null) {
String scenarioGroup = identity.getGroup();
String scenarioPath = (StringUtils.isEmpty(scenarioGroup) ? "" : scenarioGroup + "/") + identity.getCode();
Scenario scenario = scenarioRepository.findScenario(identity.getProjectCode(), scenarioPath);
reportGenerator.add(scenario, results);
}
} catch (IOException e) {
log.error("Error while loading scenario", e);
}
});
if (reportGenerator.isEmpty()) {
throw new ResourceNotFoundException();
}
File tmpDirectory = new File("tmp", UUID.randomUUID().toString());
if (tmpDirectory.mkdirs()) {
reportGenerator.generate(tmpDirectory);
ZipUtils.pack(tmpDirectory, outputStream);
} else {
throw new FileAlreadyExistsException(tmpDirectory.getAbsolutePath());
}
}
/**
* Saves the values of a formula for a group.
* @param formData the values to save
* @param groupId the id of the group
* @param formulaName the name of the formula
* @param org the user's org
* @throws IOException if an IOException occurs while saving the data
*/
public static void saveGroupFormulaData(Map<String, Object> formData, Long groupId, Org org,
String formulaName) throws IOException {
File file = new File(getGroupPillarDir() +
groupId + "_" + formulaName + "." + PILLAR_FILE_EXTENSION);
try {
file.getParentFile().mkdirs();
file.createNewFile();
}
catch (FileAlreadyExistsException e) {
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(GSON.toJson(formData));
}
if (PROMETHEUS_EXPORTERS.equals(formulaName)) {
Set<MinionServer> minions = getGroupMinions(groupId, org);
minions.forEach(minion -> {
if (!hasMonitoringDataEnabled(formData)) {
if (!serverHasMonitoringFormulaEnabled(minion)) {
systemEntitlementManager.removeServerEntitlement(minion, EntitlementManager.MONITORING);
}
}
else {
grantMonitoringEntitlement(minion);
}
});
}
}
/**
* Saves the values of a formula for a server.
* @param formData the values to save
* @param minionId the minionId
* @param formulaName the name of the formula
* @throws IOException if an IOException occurs while saving the data
*/
public static void saveServerFormulaData(Map<String, Object> formData, String minionId, String formulaName)
throws IOException {
// Add the monitoring entitlement if at least one of the exporters is enabled
if (PROMETHEUS_EXPORTERS.equals(formulaName)) {
MinionServerFactory.findByMinionId(minionId).ifPresent(s -> {
if (!hasMonitoringDataEnabled(formData)) {
if (isMemberOfGroupHavingMonitoring(s)) {
// nothing to do here, keep monitoring entitlement and disable formula
LOG.debug(String.format("Minion %s is member of group having monitoring enabled." +
" Not removing monitoring entitlement.", minionId));
}
else {
systemEntitlementManager.removeServerEntitlement(s, EntitlementManager.MONITORING);
}
}
else if (!SystemManager.hasEntitlement(s.getId(), EntitlementManager.MONITORING) &&
systemEntitlementManager.canEntitleServer(s, EntitlementManager.MONITORING)) {
systemEntitlementManager.addEntitlementToServer(s, EntitlementManager.MONITORING);
}
});
}
File file = new File(getPillarDir() + minionId +
"_" + formulaName + "." + PILLAR_FILE_EXTENSION);
try {
file.getParentFile().mkdirs();
file.createNewFile();
}
catch (FileAlreadyExistsException e) {
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(GSON.toJson(formData));
}
}
/**
* save the order of formulas
* @throws IOException an IOException occurs while saving the data
*/
public static void saveFormulaOrder() throws IOException {
List<String> orderedList = orderFormulas(listFormulaNames());
File file = new File(getOrderDataFile());
try {
file.getParentFile().mkdirs();
file.createNewFile();
}
catch (FileAlreadyExistsException e) {
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(GSON.toJson(orderedList));
}
}
/**
* Creates a new and empty file, if the file does not exist.
*
* @param file the path to the file to create
* @param attributes an optional list of file attributes to set atomically when creating the file
* @return the file
* @throws IOException if an I/O error occurs or the parent directory does not exist
* @see Files#createFile(Path, FileAttribute[])
*/
public static Path createIfNotExists(Path file, FileAttribute<?>... attributes) throws IOException {
Objects.requireNonNull(file, "'file' must not be null");
Objects.requireNonNull(attributes, "'attributes' must not be null");
try {
return Files.createFile(file, attributes);
}
catch (FileAlreadyExistsException ex) {
return file;
}
}
/**
* Create a file, if it does not already exist.
*
* @param path The path to the file to create.
* @param attrs An optional list of file attributes to set atomically when creating the file.
* @return {@code true} if the file was created.
* @throws IOException If an I/O error occurs or the parent directory does not exist.
*/
public static boolean createFileIfMissing(Path path, FileAttribute<?>... attrs) throws IOException {
requireNonNull(path);
try {
java.nio.file.Files.createFile(path, attrs);
} catch (FileAlreadyExistsException e) {
return false;
}
return true;
}
public static Path createDirectory(Path dir) throws IOException {
try {
return Files.createDirectories(dir);
} catch (FileAlreadyExistsException ignore) {
return dir;
}
}
public void init() {
try {
PlainFileUtil.newFile("ready", "File existence means node ready. ");
} catch (FileAlreadyExistsException e) {
LOG.error("ready 文件已存在?是不是有问题?", e);
}
}
public void updateAndWrite(List<char[]> newPasswords, Config config, Path pwdDest) throws IOException {
if (Optional.ofNullable(config).map(Config::getKeys).map(KeyConfiguration::getPasswords).isPresent()
&& !config.getKeys().getPasswords().isEmpty()) {
throw new ConfigException(new RuntimeException(passwordsMessage));
}
if (filesDelegate.exists(pwdDest)) {
throw new FileAlreadyExistsException(pwdDest.toString());
}
LOGGER.info("Writing updated passwords to {}", pwdDest);
final List<String> passwords;
if (Optional.ofNullable(config.getKeys()).map(KeyConfiguration::getPasswordFile).isPresent()) {
passwords = filesDelegate.readAllLines(config.getKeys().getPasswordFile());
} else {
LOGGER.info("No existing password file defined in config");
passwords = new ArrayList<>();
Optional.ofNullable(config.getKeys())
.map(KeyConfiguration::getKeyData)
.ifPresent(k -> k.forEach(kk -> passwords.add("")));
}
passwords.addAll(
newPasswords.stream().map(p -> Optional.ofNullable(p)
.map(String::valueOf)
.orElse(""))
.collect(Collectors.toList())
);
filesDelegate.createFile(pwdDest);
LOGGER.info("Created empty file at {}", pwdDest);
filesDelegate.setPosixFilePermissions(pwdDest, NEW_PASSWORD_FILE_PERMS);
filesDelegate.write(pwdDest, passwords, APPEND);
LOGGER.info("Updated passwords written to {}", pwdDest);
}
public void testCantOverrideFiles() throws IOException {
try (IndexOutput out = directory.createOutput("foo", IOContext.DEFAULT)) {
out.writeByte((byte) 42);
}
expectThrows(FileAlreadyExistsException.class,
() -> directory.createOutput("foo", IOContext.DEFAULT));
}
@Test
public void testCopyReplaceFileDifferentFileSystems() throws IOException {
addDirectory("/foo");
addFile("/foo/bar");
addFile("/baz");
CopyOption[] options = {};
FileAlreadyExistsException exception = assertThrows(FileAlreadyExistsException.class,
() -> fileSystem.copy(createPath("/baz"), createPath(fileSystem2, "/foo/bar"), options));
assertEquals("/foo/bar", exception.getFile());
assertTrue(Files.isDirectory(getPath("/foo")));
assertTrue(Files.isRegularFile(getPath("/foo/bar")));
assertTrue(Files.isRegularFile(getPath("/baz")));
}