Search in sources :

Example 66 with FileAlreadyExistsException

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);
}
Also used : Path(java.nio.file.Path) Appender(org.apache.logging.log4j.core.Appender) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) LineageLogger(org.apache.hadoop.hive.ql.hooks.LineageLogger) Logger(org.apache.logging.log4j.Logger) LoggerConfig(org.apache.logging.log4j.core.config.LoggerConfig) Test(org.junit.Test)

Example 67 with FileAlreadyExistsException

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;
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) Set(java.util.Set) HashSet(java.util.HashSet) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) HashSet(java.util.HashSet)

Example 68 with FileAlreadyExistsException

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++;
        }
    }
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException)

Example 69 with FileAlreadyExistsException

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);
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) AbstractMap(java.util.AbstractMap)

Example 70 with FileAlreadyExistsException

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;
}
Also used : FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileNotFoundException(java.io.FileNotFoundException) KeyStore(java.security.KeyStore) SecretKeyFactory(javax.crypto.SecretKeyFactory) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableEntryException(java.security.UnrecoverableEntryException)

Aggregations

FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)104 Path (java.nio.file.Path)49 IOException (java.io.IOException)44 File (java.io.File)24 NoSuchFileException (java.nio.file.NoSuchFileException)22 Test (org.junit.Test)15 FileNotFoundException (java.io.FileNotFoundException)10 FileSystemException (java.nio.file.FileSystemException)9 AccessDeniedException (java.nio.file.AccessDeniedException)8 DirectoryNotEmptyException (java.nio.file.DirectoryNotEmptyException)8 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)8 NotDirectoryException (java.nio.file.NotDirectoryException)7 AtomicMoveNotSupportedException (java.nio.file.AtomicMoveNotSupportedException)5 CopyOption (java.nio.file.CopyOption)5 FileSystem (java.nio.file.FileSystem)5 FileVisitResult (java.nio.file.FileVisitResult)5 MCRPath (org.mycore.datamodel.niofs.MCRPath)5 FileOutputStream (java.io.FileOutputStream)4 InputStream (java.io.InputStream)4 FileSystemLoopException (java.nio.file.FileSystemLoopException)4