use of java.nio.file.FileAlreadyExistsException in project hive by apache.
the class TestSlidingFilenameRolloverStrategy method testSlidingLogFiles.
@Test
public void testSlidingLogFiles() throws Exception {
assertEquals("bad props file", PROPERTIES_FILE, System.getProperty("log4j.configurationFile"));
// Where the log files wll be written
Path logTemplate = FileSystems.getDefault().getPath(FILE_PATTERN);
String fileName = logTemplate.getFileName().toString();
Path parent = logTemplate.getParent();
try {
Files.createDirectory(parent);
} catch (FileAlreadyExistsException e) {
// OK, fall through.
}
// Delete any stale log files left around from previous failed tests
deleteLogFiles(parent, fileName);
Logger logger = LogManager.getLogger(LineageLogger.class);
// Does the logger config look correct?
org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) logger;
LoggerConfig loggerConfig = coreLogger.get();
Map<String, Appender> appenders = loggerConfig.getAppenders();
assertNotNull("sliding appender is missing", appenders.get("sliding"));
// Do some logging and force log rollover
int NUM_LOGS = 7;
logger.debug("Debug Message Logged !!!");
logger.info("Info Message Logged !!!");
String errorString = "Error Message Logged ";
for (int i = 0; i < NUM_LOGS; i++) {
TimeUnit.MILLISECONDS.sleep(100);
// log an exception - this produces enough text to force a new logfile
// (as appender.sliding.policies.size.size=1KB)
logger.error(errorString + i, new RuntimeException("part of a test"));
}
// Check log files look OK
DirectoryStream<Path> stream = Files.newDirectoryStream(parent, fileName + ".*");
int count = 0;
for (Path path : stream) {
count++;
String contents = new String(Files.readAllBytes(path), "UTF-8");
// There should be one exception message per file
assertTrue("File " + path + " did not have expected content", contents.contains(errorString));
String suffix = StringUtils.substringAfterLast(path.toString(), ".");
// suffix should be a timestamp
try {
long timestamp = Long.parseLong(suffix);
} catch (NumberFormatException e) {
fail("Suffix " + suffix + " is not a long");
}
}
assertEquals("bad count of log files", NUM_LOGS, count);
// Check there is no log file without the suffix
assertFalse("file should not exist:" + logTemplate, Files.exists(logTemplate));
// Clean up
deleteLogFiles(parent, fileName);
}
use of java.nio.file.FileAlreadyExistsException in project nifi by apache.
the class RunNiFi method createSensitiveKeyFile.
private Path createSensitiveKeyFile(File confDir) {
Path sensitiveKeyFile = Paths.get(confDir + "/sensitive.key");
final boolean isPosixSupported = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
try {
if (isPosixSupported) {
// Initially create file with the empty permission set (so nobody can get a file descriptor on it):
Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
sensitiveKeyFile = Files.createFile(sensitiveKeyFile, attr);
// Then, once created, add owner-only rights:
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OWNER_READ);
attr = PosixFilePermissions.asFileAttribute(perms);
Files.setPosixFilePermissions(sensitiveKeyFile, perms);
} else {
// If Posix is not supported (e.g. Windows) then create the key file without permission settings.
cmdLogger.info("Current file system does not support Posix, using default permission settings.");
sensitiveKeyFile = Files.createFile(sensitiveKeyFile);
}
} catch (final FileAlreadyExistsException faee) {
cmdLogger.error("The sensitive.key file {} already exists. That shouldn't have been. Aborting.", sensitiveKeyFile);
System.exit(1);
} catch (final Exception e) {
cmdLogger.error("Other failure relating to setting permissions on {}. " + "(so that only the owner can read it). " + "This is fatal to the bootstrap process for security reasons. Exception was: {}", sensitiveKeyFile, e);
System.exit(1);
}
return sensitiveKeyFile;
}
use of java.nio.file.FileAlreadyExistsException in project graal by oracle.
the class PathUtilities method createUnique.
static Path createUnique(OptionValues options, OptionKey<String> baseNameOption, String id, String label, String ext, boolean createDirectory) throws IOException {
String uniqueTag = "";
int dumpCounter = 1;
String prefix;
if (id == null) {
prefix = baseNameOption.getValue(options);
int slash = prefix.lastIndexOf(File.separatorChar);
prefix = prefix.substring(slash + 1);
} else {
prefix = id;
}
for (; ; ) {
int fileNameLengthWithoutLabel = uniqueTag.length() + ext.length() + prefix.length() + "[]".length();
int labelLengthLimit = MAX_FILE_NAME_LENGTH - fileNameLengthWithoutLabel;
String fileName;
if (labelLengthLimit < ELLIPSIS.length()) {
// This means `id` is very long
String suffix = uniqueTag + ext;
int idLengthLimit = Math.min(MAX_FILE_NAME_LENGTH - suffix.length(), prefix.length());
fileName = sanitizeFileName(prefix.substring(0, idLengthLimit) + suffix);
} else {
if (label == null) {
fileName = sanitizeFileName(prefix + uniqueTag + ext);
} else {
String adjustedLabel = label;
if (label.length() > labelLengthLimit) {
adjustedLabel = label.substring(0, labelLengthLimit - ELLIPSIS.length()) + ELLIPSIS;
}
fileName = sanitizeFileName(prefix + '[' + adjustedLabel + ']' + uniqueTag + ext);
}
}
Path dumpDir = DebugOptions.getDumpDirectory(options);
Path result = Paths.get(dumpDir.toString(), fileName);
try {
if (createDirectory) {
return Files.createDirectory(result);
} else {
return Files.createFile(result);
}
} catch (FileAlreadyExistsException e) {
uniqueTag = "_" + dumpCounter++;
}
}
}
use of java.nio.file.FileAlreadyExistsException in project graal by oracle.
the class MemoryFileSystem method createDirectory.
@Override
public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
final Path absolutePath = toAbsolutePath(dir);
final Path parentPath = absolutePath.getParent();
if (parentPath == null) {
throw new IOException("Cannot create root.");
}
Map.Entry<Long, Map<String, Long>> e = readDir(parentPath);
final long inode = e.getKey();
final Map<String, Long> dirents = e.getValue();
final String fileName = absolutePath.getFileName().toString();
if (dirents.get(fileName) != null) {
throw new FileAlreadyExistsException(dir.toString());
}
dirents.put(fileName, createDirectoryImpl(attrs));
writeDir(inode, dirents);
}
use of java.nio.file.FileAlreadyExistsException in project robozonky by RoboZonky.
the class KeyStoreHandler method create.
/**
* 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(KeyStoreHandler.KEYSTORE_TYPE);
// get user password and file input stream
try {
ks.load(null, password);
} catch (final Exception ex) {
throw new IllegalStateException("Should not happen.", ex);
}
// store the newly created key store
final SecretKeyFactory skf = KeyStoreHandler.getSecretKeyFactory();
final KeyStoreHandler ksh = new KeyStoreHandler(ks, password, keyStoreFile, skf);
ksh.save();
return ksh;
}
Aggregations