/** * Persist the keystore on the file system. * * During the flush the steps are * 1. Delete the _NEW file if it exists, it will exist only if something had failed in the last run. * 2. Try to write the current keystore in a _NEW file. * 3. If something fails then revert the key store to the old state and throw IOException. * 4. If everything is OK then rename the _NEW to the main file. * */ private void flush() throws IOException { Path newPath = constructNewPath(path); writeLock.lock(); try { // Might exist if a backup has been restored etc. Files.deleteIfExists(newPath); // Flush the keystore, write the _NEW file first writeToKeyStore(newPath); // Do Atomic rename _NEW to CURRENT Files.move(newPath, path, ATOMIC_MOVE, REPLACE_EXISTING); } finally { writeLock.unlock(); } }
/** * Initialize the keyStore. * * @throws IOException If there is a problem reading or creating the keystore. */ private static KeyStore locateKeystore(Path path, final char[] password) throws IOException { Path newPath = constructNewPath(path); KeyStore ks; try { ks = KeyStore.getInstance(SCHEME_NAME); Files.deleteIfExists(newPath); if (Files.exists(path)) { loadFromPath(ks, path, password); } else { Path parent = path.getParent(); if (!Files.exists(parent)) { Files.createDirectories(parent); } // We were not able to load an existing key store. Create a new one. ks.load(null, password); LOG.info("New Secure Store initialized successfully."); } } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException e) { throw new IOException("Can't create Secure Store. ", e); } return ks; }