[OOM-CMPv2] Create KeystoreCopier 61/112461/19
authorJan Malkiewicz <jan.malkiewicz@nokia.com>
Thu, 10 Sep 2020 06:58:30 +0000 (08:58 +0200)
committerJan Malkiewicz <jan.malkiewicz@nokia.com>
Thu, 10 Sep 2020 13:02:26 +0000 (15:02 +0200)
- implement logic to copy keystores
- moved logic of truststore merger to decicated class TruststoreMerger

Issue-ID: DCAEGEN2-2253
Signed-off-by: Jan Malkiewicz <jan.malkiewicz@nokia.com>
Change-Id: I730d10b9bb72da55d9e4641b79cf98e0e100a39d

18 files changed:
trustStoreMerger/pom.xml
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/AppExitHandler.java
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/CertificatePostProcessor.java
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/api/ExitStatus.java
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/common/FileTools.java [moved from trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/common/BackupCreator.java with 59% similarity]
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/AppConfigurationLoader.java [new file with mode: 0644]
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/AppConfigurationProvider.java [moved from trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/MergerConfigurationProvider.java with 90% similarity]
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/model/AppConfiguration.java [moved from trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/model/MergerConfiguration.java with 95% similarity]
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/copier/KeystoreCopier.java [new file with mode: 0644]
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/copier/exception/KeystoreFileCopyException.java [new file with mode: 0644]
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/copier/exception/KeystoreNotExistException.java [new file with mode: 0644]
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/merger/TruststoreMerger.java [new file with mode: 0644]
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/merger/model/JavaTruststore.java
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/merger/model/PemTruststore.java
trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/merger/model/Truststore.java
trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/common/FileToolsTest.java [moved from trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/common/BackupCreatorTest.java with 58% similarity]
trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/configuration/MergerConfigurationProviderTest.java
trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/copier/KeystoreCopierTest.java [new file with mode: 0644]

index eba40e1..545dab3 100644 (file)
 
 
     <dependencies>
+        <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+        </dependency>
         <dependency>
             <groupId>org.assertj</groupId>
             <artifactId>assertj-core</artifactId>
index c257756..e4c26b1 100644 (file)
@@ -27,7 +27,7 @@ public class AppExitHandler {
     private static final Logger LOGGER = LoggerFactory.getLogger(AppExitHandler.class);
 
     public void exit(ExitStatus exitStatus) {
-        LOGGER.info("Application exits with following exit code: {} and message: {}",
+        LOGGER.info("Application exits with code [{}] and message: {}",
                 exitStatus.getExitCodeValue(), exitStatus.getMessage());
         System.exit(exitStatus.getExitCodeValue());
     }
index 7eab640..0045b2f 100644 (file)
 
 package org.onap.oom.truststoremerger;
 
-import java.util.List;
 import org.onap.oom.truststoremerger.api.ExitableException;
-import org.onap.oom.truststoremerger.configuration.MergerConfigurationProvider;
-import org.onap.oom.truststoremerger.configuration.model.MergerConfiguration;
-import org.onap.oom.truststoremerger.configuration.path.DelimitedPathsReader;
-import org.onap.oom.truststoremerger.configuration.path.DelimitedPathsReaderFactory;
-import org.onap.oom.truststoremerger.configuration.path.env.EnvProvider;
-import org.onap.oom.truststoremerger.merger.TruststoreFilesProvider;
-import org.onap.oom.truststoremerger.merger.model.Truststore;
-import org.onap.oom.truststoremerger.merger.model.certificate.CertificateWithAlias;
+import org.onap.oom.truststoremerger.common.FileTools;
+import org.onap.oom.truststoremerger.configuration.AppConfigurationLoader;
+import org.onap.oom.truststoremerger.configuration.model.AppConfiguration;
+import org.onap.oom.truststoremerger.copier.KeystoreCopier;
+import org.onap.oom.truststoremerger.merger.TruststoreMerger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 class CertificatePostProcessor implements Runnable {
 
-    private static final int FIRST_TRUSTSTORE_INDEX = 0;
-    private static final int SECOND_TRUSTSTORE_INDEX = 1;
+    private static final Logger LOGGER = LoggerFactory.getLogger(CertificatePostProcessor.class);
 
-    public void run() throws ExitableException {
-        mergeTruststores();
-    }
-
-    private void mergeTruststores() throws ExitableException {
-        MergerConfiguration configuration = loadConfiguration();
-        List<Truststore> truststoreFilesList = getTruststoreFiles(configuration);
-
-        Truststore baseFile = truststoreFilesList.get(FIRST_TRUSTSTORE_INDEX);
-        baseFile.createBackup();
-
-        for (int i = SECOND_TRUSTSTORE_INDEX; i < truststoreFilesList.size(); i++) {
-            Truststore truststore = truststoreFilesList.get(i);
-            List<CertificateWithAlias> certificateWrappers = truststore.getCertificates();
-            baseFile.addCertificates(certificateWrappers);
-        }
+    private AppConfigurationLoader config = new AppConfigurationLoader();
+    private TruststoreMerger merger = new TruststoreMerger();
+    private KeystoreCopier copier = new KeystoreCopier(new FileTools());
 
-        baseFile.saveFile();
-    }
-
-    private MergerConfiguration loadConfiguration() throws ExitableException {
-        DelimitedPathsReaderFactory readerFactory = new DelimitedPathsReaderFactory(new EnvProvider());
-        DelimitedPathsReader certificatesPathsReader = readerFactory.createCertificatePathsReader();
-        DelimitedPathsReader passwordsPathsReader = readerFactory.createPasswordPathsReader();
-        DelimitedPathsReader copierPathsReader = readerFactory.createKeystoreCopierPathsReader();
-        MergerConfigurationProvider factory = new MergerConfigurationProvider(certificatesPathsReader,
-            passwordsPathsReader,
-            copierPathsReader);
-        return factory.createConfiguration();
-    }
-
-    private static List<Truststore> getTruststoreFiles(MergerConfiguration configuration) throws ExitableException {
-        return TruststoreFilesProvider
-            .getTruststoreFiles(
-                configuration.getTruststoreFilePaths(),
-                configuration.getTruststoreFilePasswordPaths()
-            );
+    public void run() throws ExitableException {
+        LOGGER.debug("Loading configuration...");
+        AppConfiguration configuration = config.loadConfiguration();
+        LOGGER.debug("Starting TruststoreMerger...");
+        merger.mergeTruststores(configuration);
+        LOGGER.debug("Starting KeystoreCopier...");
+        copier.copyKeystores(configuration);
+        LOGGER.debug("Certificate post processing finished successfully.");
     }
 }
index d3e246a..01f440c 100644 (file)
@@ -33,6 +33,8 @@ public enum ExitStatus {
     MISSING_TRUSTSTORE_EXCEPTION(9, "Missing truststore certificates in provided file"),
     ALIAS_CONFLICT_EXCEPTION(10, "Alias conflict detected"),
     WRITE_TRUSTSTORE_FILE_EXCEPTION(11, "Cannot save truststore file"),
+    KEYSTORE_FILE_COPY_EXCEPTION(12, "Cannot copy keystore file"),
+    KEYSTORE_NOT_EXIST_EXCEPTION(13, "Keystore file does not exist"),
     UNEXPECTED_EXCEPTION(99, "Application exited abnormally");
 
 
@@ -21,28 +21,34 @@ package org.onap.oom.truststoremerger.common;
 
 import java.io.File;
 import java.io.FileOutputStream;
+import java.io.IOException;
 import java.nio.file.Files;
+import org.apache.commons.io.FileUtils;
 import org.onap.oom.truststoremerger.merger.exception.CreateBackupException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public final class BackupCreator {
+public final class FileTools {
 
-    private static final Logger LOGGER = LoggerFactory.getLogger(BackupCreator.class);
+    private static final Logger LOGGER = LoggerFactory.getLogger(FileTools.class);
     private static final String BACKUP_EXTENSION = ".bak";
 
-    private BackupCreator() {
-    }
-
-    public static void createBackup(File file) throws CreateBackupException {
-        LOGGER.debug("Create backup of file: {}", file.getPath());
-        String backupFilePath = file.getAbsolutePath() + BACKUP_EXTENSION;
-        try (FileOutputStream fileOutputStream = new FileOutputStream(backupFilePath)) {
-            Files.copy(file.toPath(), fileOutputStream);
-        } catch (Exception e) {
-            LOGGER.error("Cannot create backup of file: {} ", file.getPath());
+    public void createBackup(File file) throws CreateBackupException {
+        LOGGER.debug("Try to create a backup of the file: {}", file.getPath());
+        File backupFile = new File(file.getAbsolutePath() + BACKUP_EXTENSION);
+        try  {
+            copy(file, backupFile);
+        } catch (IOException e) {
+            LOGGER.error("Could not create backup of the file: '{}'", file.getPath());
             throw new CreateBackupException(e);
         }
-        LOGGER.debug("Backup was successfully created in: {}", backupFilePath);
+        LOGGER.debug("Backup file created: '{}'", backupFile.getAbsolutePath());
+    }
+
+    public void copy(File source, File destination) throws IOException {
+        LOGGER.debug("Try to copy from '{}' to '{}'.", source.getAbsolutePath(), destination.getAbsolutePath());
+        FileUtils.copyFile(source, destination);
+        LOGGER.debug("File copied from '{}' to '{}'.", source.getAbsolutePath(),
+            destination.getAbsolutePath());
     }
 }
diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/AppConfigurationLoader.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/configuration/AppConfigurationLoader.java
new file mode 100644 (file)
index 0000000..7660ff7
--- /dev/null
@@ -0,0 +1,42 @@
+/*============LICENSE_START=======================================================
+ * oom-truststore-merger
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.oom.truststoremerger.configuration;
+
+import org.onap.oom.truststoremerger.api.ExitableException;
+import org.onap.oom.truststoremerger.configuration.model.AppConfiguration;
+import org.onap.oom.truststoremerger.configuration.path.DelimitedPathsReader;
+import org.onap.oom.truststoremerger.configuration.path.DelimitedPathsReaderFactory;
+import org.onap.oom.truststoremerger.configuration.path.env.EnvProvider;
+
+public class AppConfigurationLoader {
+
+    public AppConfiguration loadConfiguration() throws ExitableException {
+        DelimitedPathsReaderFactory readerFactory = new DelimitedPathsReaderFactory(new EnvProvider());
+        DelimitedPathsReader certificatesPathsReader = readerFactory.createCertificatePathsReader();
+        DelimitedPathsReader passwordsPathsReader = readerFactory.createPasswordPathsReader();
+        DelimitedPathsReader copierPathsReader = readerFactory.createKeystoreCopierPathsReader();
+        AppConfigurationProvider factory = new AppConfigurationProvider(certificatesPathsReader,
+            passwordsPathsReader,
+            copierPathsReader);
+        return factory.createConfiguration();
+    }
+
+
+}
@@ -27,23 +27,23 @@ import static org.onap.oom.truststoremerger.configuration.ConfigurationEnvs.TRUS
 import java.util.List;
 import org.onap.oom.truststoremerger.configuration.exception.MergerConfigurationException;
 import org.onap.oom.truststoremerger.configuration.exception.TruststoresPathsProviderException;
-import org.onap.oom.truststoremerger.configuration.model.MergerConfiguration;
+import org.onap.oom.truststoremerger.configuration.model.AppConfiguration;
 import org.onap.oom.truststoremerger.configuration.path.DelimitedPathsReader;
 
-public class MergerConfigurationProvider {
+public class AppConfigurationProvider {
 
     private final DelimitedPathsReader truststoresPathsReader;
     private final DelimitedPathsReader truststoresPasswordsPathsReader;
     private final DelimitedPathsReader copierPathsReader;
 
-    public MergerConfigurationProvider(DelimitedPathsReader truststoresPathsReader,
+    public AppConfigurationProvider(DelimitedPathsReader truststoresPathsReader,
         DelimitedPathsReader truststoresPasswordsPathsReader, DelimitedPathsReader copierPathsReader) {
         this.truststoresPathsReader = truststoresPathsReader;
         this.truststoresPasswordsPathsReader = truststoresPasswordsPathsReader;
         this.copierPathsReader = copierPathsReader;
     }
 
-    public MergerConfiguration createConfiguration()
+    public AppConfiguration createConfiguration()
         throws MergerConfigurationException, TruststoresPathsProviderException {
         List<String> truststoresPaths = truststoresPathsReader.get(TRUSTSTORES_PATHS_ENV);
         List<String> truststoresPasswordsPaths = truststoresPasswordsPathsReader.get(TRUSTSTORES_PASSWORDS_PATHS_ENV);
@@ -55,7 +55,7 @@ public class MergerConfigurationProvider {
         ensureSameSize(sourceKeystorePaths, destinationKeystorePaths, KEYSTORE_SOURCE_PATHS_ENV,
             KEYSTORE_DESTINATION_PATHS_ENV);
 
-        return new MergerConfiguration(truststoresPaths, truststoresPasswordsPaths, sourceKeystorePaths,
+        return new AppConfiguration(truststoresPaths, truststoresPasswordsPaths, sourceKeystorePaths,
             destinationKeystorePaths);
     }
 
@@ -22,13 +22,13 @@ package org.onap.oom.truststoremerger.configuration.model;
 import java.util.Collections;
 import java.util.List;
 
-public final class MergerConfiguration {
+public final class AppConfiguration {
     private final List<String> truststoreFilePaths;
     private final List<String> truststoreFilePasswordPaths;
     private final List<String> sourceKeystorePaths;
     private final List<String> destinationKeystorePaths;
 
-    public MergerConfiguration(List<String> truststoreFilePaths,
+    public AppConfiguration(List<String> truststoreFilePaths,
         List<String> truststoreFilePasswordPaths, List<String> sourceKeystorePaths,
         List<String> destinationKeystorePaths) {
         this.truststoreFilePaths = List.copyOf(truststoreFilePaths);
diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/copier/KeystoreCopier.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/copier/KeystoreCopier.java
new file mode 100644 (file)
index 0000000..822979c
--- /dev/null
@@ -0,0 +1,65 @@
+/*============LICENSE_START=======================================================
+ * oom-truststore-merger
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.oom.truststoremerger.copier;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import org.onap.oom.truststoremerger.common.FileTools;
+import org.onap.oom.truststoremerger.configuration.model.AppConfiguration;
+import org.onap.oom.truststoremerger.copier.exception.KeystoreFileCopyException;
+import org.onap.oom.truststoremerger.copier.exception.KeystoreNotExistException;
+
+public class KeystoreCopier {
+
+    final private FileTools fileTools;
+
+    public KeystoreCopier(FileTools fileTools) {
+        this.fileTools = fileTools;
+    }
+
+    public void copyKeystores(AppConfiguration configuration) {
+        try {
+            final List<String> sources = configuration.getSourceKeystorePaths();
+            final List<String> destinations = configuration.getDestinationKeystorePaths();
+
+            for (int i = 0; i < sources.size(); i++) {
+                copy(sources.get(i), destinations.get(i));
+            }
+        } catch (IOException e) {
+            throw new KeystoreFileCopyException(e);
+        }
+    }
+
+    private void copy(String sourcePath, String destinationPath) throws IOException {
+        final File source = new File(sourcePath);
+        final File destination = new File(destinationPath);
+
+        if (!source.exists()) {
+            throw new KeystoreNotExistException("Keystore file does not exist '" + source.getAbsolutePath() + "'!");
+        }
+
+        if (destination.exists()) {
+            fileTools.createBackup(destination);
+        }
+        fileTools.copy(source, destination);
+    }
+
+}
diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/copier/exception/KeystoreFileCopyException.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/copier/exception/KeystoreFileCopyException.java
new file mode 100644 (file)
index 0000000..80d3c67
--- /dev/null
@@ -0,0 +1,31 @@
+/*============LICENSE_START=======================================================
+ * oom-truststore-merger
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.oom.truststoremerger.copier.exception;
+
+import org.onap.oom.truststoremerger.api.ExitStatus;
+import org.onap.oom.truststoremerger.api.ExitableException;
+
+public class KeystoreFileCopyException extends ExitableException {
+
+    public KeystoreFileCopyException(Exception e) {
+        super(e, ExitStatus.KEYSTORE_FILE_COPY_EXCEPTION);
+    }
+
+}
diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/copier/exception/KeystoreNotExistException.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/copier/exception/KeystoreNotExistException.java
new file mode 100644 (file)
index 0000000..ef2d776
--- /dev/null
@@ -0,0 +1,31 @@
+/*============LICENSE_START=======================================================
+ * oom-truststore-merger
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.oom.truststoremerger.copier.exception;
+
+import org.onap.oom.truststoremerger.api.ExitStatus;
+import org.onap.oom.truststoremerger.api.ExitableException;
+
+public class KeystoreNotExistException extends ExitableException {
+
+    public KeystoreNotExistException(String message) {
+        super(message, ExitStatus.KEYSTORE_NOT_EXIST_EXCEPTION);
+    }
+
+}
diff --git a/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/merger/TruststoreMerger.java b/trustStoreMerger/src/main/java/org/onap/oom/truststoremerger/merger/TruststoreMerger.java
new file mode 100644 (file)
index 0000000..ad8cff9
--- /dev/null
@@ -0,0 +1,55 @@
+/*============LICENSE_START=======================================================
+ * oom-truststore-merger
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.oom.truststoremerger.merger;
+
+import java.util.List;
+import org.onap.oom.truststoremerger.api.ExitableException;
+import org.onap.oom.truststoremerger.configuration.model.AppConfiguration;
+import org.onap.oom.truststoremerger.merger.model.Truststore;
+import org.onap.oom.truststoremerger.merger.model.certificate.CertificateWithAlias;
+
+public class TruststoreMerger {
+
+    private static final int FIRST_TRUSTSTORE_INDEX = 0;
+    private static final int SECOND_TRUSTSTORE_INDEX = 1;
+
+    public void mergeTruststores(AppConfiguration configuration) throws ExitableException {
+        List<Truststore> truststoreFilesList = getTruststoreFiles(configuration);
+
+        Truststore baseFile = truststoreFilesList.get(FIRST_TRUSTSTORE_INDEX);
+        baseFile.createBackup();
+
+        for (int i = SECOND_TRUSTSTORE_INDEX; i < truststoreFilesList.size(); i++) {
+            Truststore truststore = truststoreFilesList.get(i);
+            List<CertificateWithAlias> certificateWrappers = truststore.getCertificates();
+            baseFile.addCertificates(certificateWrappers);
+        }
+
+        baseFile.saveFile();
+    }
+
+    private List<Truststore> getTruststoreFiles(AppConfiguration configuration) throws ExitableException {
+        return TruststoreFilesProvider
+            .getTruststoreFiles(
+                configuration.getTruststoreFilePaths(),
+                configuration.getTruststoreFilePasswordPaths()
+            );
+    }
+}
index e3a0399..6aa8b56 100644 (file)
@@ -28,6 +28,7 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import org.onap.oom.truststoremerger.api.ExitableException;
+import org.onap.oom.truststoremerger.common.FileTools;
 import org.onap.oom.truststoremerger.merger.exception.AliasConflictException;
 import org.onap.oom.truststoremerger.merger.exception.LoadTruststoreException;
 import org.onap.oom.truststoremerger.merger.exception.MissingTruststoreException;
@@ -48,7 +49,7 @@ public final class JavaTruststore extends Truststore {
 
 
     private JavaTruststore(KeyStore keyStore, File storeFile, String password) {
-        super(storeFile);
+        super(storeFile, new FileTools());
         this.keyStore = keyStore;
         this.password = password;
     }
index d04a01b..4617142 100644 (file)
@@ -37,6 +37,7 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider;
 import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator;
 import org.bouncycastle.util.io.pem.PemObjectGenerator;
 import org.bouncycastle.util.io.pem.PemWriter;
+import org.onap.oom.truststoremerger.common.FileTools;
 import org.onap.oom.truststoremerger.merger.exception.MissingTruststoreException;
 import org.onap.oom.truststoremerger.merger.exception.TruststoreDataOperationException;
 import org.onap.oom.truststoremerger.merger.exception.WriteTruststoreFileException;
@@ -55,7 +56,7 @@ public class PemTruststore extends Truststore {
     private final List<CertificateWithAlias> certificatesToBeSaved = new ArrayList<>();
 
     public PemTruststore(File storeFile) {
-        super(storeFile);
+        super(storeFile, new FileTools());
     }
 
     public List<CertificateWithAlias> getCertificates()
index 2c3acf4..8423987 100644 (file)
@@ -22,20 +22,23 @@ package org.onap.oom.truststoremerger.merger.model;
 import java.io.File;
 import java.util.List;
 import org.onap.oom.truststoremerger.api.ExitableException;
+import org.onap.oom.truststoremerger.common.FileTools;
 import org.onap.oom.truststoremerger.merger.exception.CreateBackupException;
 import org.onap.oom.truststoremerger.merger.model.certificate.CertificateWithAlias;
-import org.onap.oom.truststoremerger.common.BackupCreator;
 
 public abstract class Truststore {
 
     final File storeFile;
 
-    public Truststore(File storeFile) {
+    private final FileTools fileTools;
+
+    public Truststore(File storeFile, FileTools fileTools) {
         this.storeFile = storeFile;
+        this.fileTools = fileTools;
     }
 
     public void createBackup() throws CreateBackupException {
-        BackupCreator.createBackup(storeFile);
+        fileTools.createBackup(storeFile);
     }
 
     public abstract List<CertificateWithAlias> getCertificates() throws ExitableException;
@@ -23,29 +23,52 @@ import static org.assertj.core.api.Assertions.assertThat;
 
 import java.io.File;
 import java.io.IOException;
+import java.nio.charset.Charset;
+import org.apache.commons.io.FileUtils;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.onap.oom.truststoremerger.merger.exception.CreateBackupException;
 import org.onap.oom.truststoremerger.merger.model.TestCertificateProvider;
 
-public class BackupCreatorTest {
+public class FileToolsTest {
 
     public static final String BAK_EXTENSION = ".bak";
 
+    @TempDir
+    File dir;
+
     @Test
-    void shouldCreateBackupProvidedFile() throws CreateBackupException {
+    void shouldCreateBackupProvidedFile() throws Exception {
         //given
-        File fileToBackup = new File(TestCertificateProvider.PEM_FILE_PATH);
+        File fileToBackup = createFile("truststore.pem", "arbitrary content");
         String backupFilePath = fileToBackup.getPath() + BAK_EXTENSION;
         //when
-        BackupCreator.createBackup(fileToBackup);
+        new FileTools().createBackup(fileToBackup);
         //then
         assertThat(fileToBackup.equals(new File(backupFilePath)));
     }
 
-    @AfterEach
-    void removeTemporaryFiles() throws IOException {
-        TestCertificateProvider.removeTemporaryFiles();
+    @Test
+    void shouldCopyFile() throws IOException {
+        //given
+        File sourceFile = createFile("source.p12", "any content");
+        File destinationFile = new File(dir.getAbsolutePath() + "destination.p12");
+        //when
+        new FileTools().copy(sourceFile, destinationFile);
+        //then
+        assertThat(sourceFile.equals(destinationFile));
+    }
+
+
+    private File createFile(String name, String content) throws IOException {
+        File file = new File(dir.getAbsolutePath() + File.pathSeparator + name);
+        if (file.createNewFile()) {
+            FileUtils.write(file, content, Charset.defaultCharset());
+        } else {
+            throw new IllegalStateException("File could not be created: " + file.getAbsolutePath());
+        }
+        return file;
     }
 
 }
index 3df9bfd..026199f 100644 (file)
@@ -36,7 +36,7 @@ import org.mockito.Mock;
 import org.mockito.junit.jupiter.MockitoExtension;
 import org.onap.oom.truststoremerger.configuration.exception.MergerConfigurationException;
 import org.onap.oom.truststoremerger.configuration.exception.TruststoresPathsProviderException;
-import org.onap.oom.truststoremerger.configuration.model.MergerConfiguration;
+import org.onap.oom.truststoremerger.configuration.model.AppConfiguration;
 import org.onap.oom.truststoremerger.configuration.path.DelimitedPathsReader;
 
 @ExtendWith(MockitoExtension.class)
@@ -55,11 +55,11 @@ class MergerConfigurationProviderTest {
     private DelimitedPathsReader passwordsPathsProvider;
     @Mock
     private DelimitedPathsReader copierPathsReader;
-    private MergerConfigurationProvider factory;
+    private AppConfigurationProvider factory;
 
     @BeforeEach
     void setUp() {
-        factory = new MergerConfigurationProvider(certificatesPathsProvider, passwordsPathsProvider, copierPathsReader);
+        factory = new AppConfigurationProvider(certificatesPathsProvider, passwordsPathsProvider, copierPathsReader);
     }
 
     @Test
@@ -76,7 +76,7 @@ class MergerConfigurationProviderTest {
             numberOfPaths, PEM_EXTENSION);
         mockKeystorePaths(sourceKeystoresPairPaths, destKeystoresPairPaths);
 
-        MergerConfiguration configuration = factory.createConfiguration();
+        AppConfiguration configuration = factory.createConfiguration();
 
         assertThat(configuration.getTruststoreFilePaths()).containsAll(truststoresPaths);
         assertThat(configuration.getTruststoreFilePasswordPaths()).containsAll(truststorePasswordPaths);
diff --git a/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/copier/KeystoreCopierTest.java b/trustStoreMerger/src/test/java/org/onap/oom/truststoremerger/copier/KeystoreCopierTest.java
new file mode 100644 (file)
index 0000000..ca456bc
--- /dev/null
@@ -0,0 +1,147 @@
+/*============LICENSE_START=======================================================
+ * oom-truststore-merger
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.oom.truststoremerger.copier;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.Collections;
+import org.apache.commons.io.FileUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.onap.oom.truststoremerger.common.FileTools;
+import org.onap.oom.truststoremerger.configuration.model.AppConfiguration;
+import org.onap.oom.truststoremerger.copier.exception.KeystoreFileCopyException;
+import org.onap.oom.truststoremerger.copier.exception.KeystoreNotExistException;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+
+public class KeystoreCopierTest {
+
+    private static final String SOURCE_CONTENT = "source content";
+    private static final String DESTINATION_CONTENT = "destination content";
+
+    @TempDir
+    File dir;
+
+    private KeystoreCopier copier = new KeystoreCopier(new FileTools());
+
+    @Test
+    void shouldDoNothingForEmptySourceFileList() {
+        AppConfiguration configuration = createEmptyConfiguration();
+
+        copier.copyKeystores(configuration);
+
+        assertThat(dir.listFiles()).isEmpty();
+    }
+
+
+    @Test
+    void shouldCopyFileAndCreateBackup() throws IOException {
+        File source = createFile("source.p12", SOURCE_CONTENT);
+        File destination = createFile("destination.p12", DESTINATION_CONTENT);
+        File backup = declareFile("destination.p12.bak");
+        AppConfiguration configuration = createConfiguration(source, destination);
+
+        copier.copyKeystores(configuration);
+
+        assertThat(readFile(destination)).isEqualTo(readFile(source));
+        assertThat(backup.exists()).isTrue();
+        assertThat(readFile(backup)).isEqualTo(DESTINATION_CONTENT);
+    }
+
+    @Test
+    void shouldCopyFileWithoutCreatingBackup() throws IOException {
+        File source = createFile("source.p12", SOURCE_CONTENT);
+        File destination = declareFile("destination.p12");
+        File backup = declareFile("destination.p12.bak");
+        AppConfiguration configuration = createConfiguration(source, destination);
+
+        copier.copyKeystores(configuration);
+
+        assertThat(destination.exists()).isTrue();
+        assertThat(readFile(destination)).isEqualTo(readFile(source));
+        assertThat(backup.exists()).isFalse();
+    }
+
+    @Test
+    void shouldThrowKeystoreNotExistException() throws IOException {
+        File source = declareFile("source.p12");
+        File destination = declareFile("destination.p12");
+        File backup = declareFile("destination.p12.bak");
+        AppConfiguration configuration = createConfiguration(source, destination);
+
+        assertThatExceptionOfType(KeystoreNotExistException.class).isThrownBy( () ->
+            copier.copyKeystores(configuration)
+        );
+
+        assertThat(source.exists()).isFalse();
+        assertThat(destination.exists()).isFalse();
+        assertThat(backup.exists()).isFalse();
+    }
+
+    @Test
+    void shouldThrowKeystoreFileCopyException() throws IOException {
+        File source = createFile("source.p12", SOURCE_CONTENT);
+        source.setReadable(false);
+        File destination = declareFile("destination.p12");
+        File backup = declareFile("destination.p12.bak");
+        AppConfiguration configuration = createConfiguration(source, destination);
+
+        assertThatExceptionOfType(KeystoreFileCopyException.class).isThrownBy( () ->
+            copier.copyKeystores(configuration)
+        );
+
+        assertThat(source.exists()).isTrue();
+        assertThat(destination.exists()).isFalse();
+        assertThat(backup.exists()).isFalse();
+    }
+
+    private AppConfiguration createConfiguration(File source, File destination) {
+        return new AppConfiguration(Collections.emptyList(), Collections.emptyList(),
+            Collections.singletonList(source.getAbsolutePath()),
+            Collections.singletonList(destination.getAbsolutePath()));
+    }
+
+    private AppConfiguration createEmptyConfiguration() {
+        return new AppConfiguration(Collections.emptyList(), Collections.emptyList(),
+            Collections.emptyList(),
+            Collections.emptyList());
+    }
+
+    private String readFile(File file) throws IOException {
+        return FileUtils.readFileToString(file, Charset.defaultCharset());
+    }
+
+    private File declareFile(String name) {
+        return new File(dir.getAbsolutePath() + File.pathSeparator + name);
+    }
+
+    private File createFile(String name, String content) throws IOException {
+        File file = new File(dir.getAbsolutePath() + File.pathSeparator + name);
+        if (file.createNewFile()) {
+            FileUtils.write(file, content, Charset.defaultCharset());
+        } else {
+            throw new IllegalStateException("File could not be created: " + file.getAbsolutePath());
+        }
+        return file;
+    }
+}