Fix sonar issues 33/123933/1
authorSamuel Liard <samuel.liard@gmail.com>
Tue, 7 Sep 2021 16:40:11 +0000 (18:40 +0200)
committerSamuel Liard <samuel.liard@gmail.com>
Tue, 7 Sep 2021 16:40:52 +0000 (18:40 +0200)
Issue-ID: AAI-3362
Signed-off-by: sliard <samuel.liard@gmail.com>
Change-Id: I42e20a29a35eba600d18c2e4c85daed183c4d829

17 files changed:
src/main/java/org/onap/aai/auth/FileWatcher.java
src/main/java/org/onap/aai/babel/BabelApplication.java
src/main/java/org/onap/aai/babel/config/PropertyPasswordConfiguration.java
src/main/java/org/onap/aai/babel/csar/CsarToXmlConverter.java
src/main/java/org/onap/aai/babel/xml/generator/ModelGenerator.java
src/main/java/org/onap/aai/babel/xml/generator/api/AaiModelGenerator.java
src/test/java/org/onap/aai/babel/TestApplication.java
src/test/java/org/onap/aai/babel/TestAuthFileWatcher.java
src/test/java/org/onap/aai/babel/TestMicroServiceAuth.java
src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java
src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java
src/test/java/org/onap/aai/babel/parser/TestArtifactGeneratorToscaParser.java
src/test/java/org/onap/aai/babel/service/TestCsarToXmlConverter.java
src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java
src/test/java/org/onap/aai/babel/xml/generator/TestModelGenerator.java
src/test/java/org/onap/aai/babel/xml/generator/model/TestModel.java
src/test/java/org/onap/aai/babel/xml/generator/model/TestWidget.java

index 9c4e04e..1edad1d 100644 (file)
@@ -33,7 +33,7 @@ public abstract class FileWatcher extends TimerTask {
      *
      * @param file the file
      */
-    public FileWatcher(File file) {
+    protected FileWatcher(File file) {
         this.file = file;
         this.timeStamp = file.lastModified();
     }
index 71fe7e0..4f67b21 100644 (file)
@@ -50,17 +50,11 @@ public class BabelApplication extends SpringBootServletInitializer {
         if (keyStorePassword == null || keyStorePassword.isEmpty()) {
             throw new IllegalArgumentException("Mandatory property KEY_STORE_PASSWORD not set");
         }
-        try {
-            SpringApplication app = new SpringApplication(BabelApplication.class);
-            app.setLogStartupInfo(false);
-            app.setRegisterShutdownHook(true);
-            app.addInitializers(new PropertyPasswordConfiguration());
-            context = app.run(args);
-        }
-        catch(Exception ex){
-            ex.printStackTrace();
-            throw ex;
-        }
+        SpringApplication app = new SpringApplication(BabelApplication.class);
+        app.setLogStartupInfo(false);
+        app.setRegisterShutdownHook(true);
+        app.addInitializers(new PropertyPasswordConfiguration());
+        context = app.run(args);
     }
 
     public static void exit() {
index c8efa01..7539d41 100644 (file)
  */
 package org.onap.aai.babel.config;
 
-import org.apache.commons.io.IOUtils;
+import java.nio.charset.StandardCharsets;
 import org.eclipse.jetty.util.security.Password;
-import org.onap.aai.babel.logging.LogHelper;
 import org.springframework.context.ApplicationContextInitializer;
 import org.springframework.context.ConfigurableApplicationContext;
 import org.springframework.core.env.ConfigurableEnvironment;
 import org.springframework.core.env.MapPropertySource;
 import org.springframework.core.env.PropertySource;
 
-import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -38,79 +36,50 @@ import java.util.Properties;
 
 public class PropertyPasswordConfiguration implements ApplicationContextInitializer<ConfigurableApplicationContext> {
 
+    private static final String PROP_KEY_STORE_PASS = "server.ssl.key-store-password";
+
     @Override
     public void initialize(ConfigurableApplicationContext applicationContext) {
 
         Map<String, Object> sslProps = new LinkedHashMap<>();
         ConfigurableEnvironment environment = applicationContext.getEnvironment();
         String certPath = environment.getProperty("server.certs.location");
-        File passwordFile = null;
-        File passphrasesFile = null;
-        InputStream passwordStream = null;
-        InputStream passphrasesStream = null;
         String keystorePassword = null;
         String truststorePassword = null;
 
         if (certPath != null) {
-            try {
-                passwordFile = new File(certPath + ".password");
-                passwordStream = new FileInputStream(passwordFile);
-
-                if (passwordStream != null) {
-                    keystorePassword = IOUtils.toString(passwordStream);
-                    if (keystorePassword != null) {
-                        keystorePassword = keystorePassword.trim();
-                    }
-                    sslProps.put("server.ssl.key-store-password", keystorePassword);
-                }
+            try (InputStream passwordStream = new FileInputStream(certPath + ".password")) {
+                keystorePassword = new String(passwordStream.readAllBytes(), StandardCharsets.UTF_8);
+                keystorePassword = keystorePassword.trim();
+                sslProps.put(PROP_KEY_STORE_PASS, keystorePassword);
             } catch (IOException e) {
-            } finally {
-                if (passwordStream != null) {
-                    try {
-                        passwordStream.close();
-                    } catch (Exception e) {
-                    }
-                }
+                keystorePassword = null;
             }
-            try {
-                passphrasesFile = new File(certPath + ".passphrases");
-                passphrasesStream = new FileInputStream(passphrasesFile);
-
-                if (passphrasesStream != null) {
-                    Properties passphrasesProps = new Properties();
-                    passphrasesProps.load(passphrasesStream);
-                    truststorePassword = passphrasesProps.getProperty("cadi_truststore_password");
-                    if (truststorePassword != null) {
-                        truststorePassword = truststorePassword.trim();
-                    }
-                    sslProps.put("server.ssl.trust-store-password", truststorePassword);
-                } else {
+            try (InputStream passphrasesStream = new FileInputStream(certPath + ".passphrases");) {
+                Properties passphrasesProps = new Properties();
+                passphrasesProps.load(passphrasesStream);
+                truststorePassword = passphrasesProps.getProperty("cadi_truststore_password");
+                if (truststorePassword != null) {
+                    truststorePassword = truststorePassword.trim();
                 }
+                sslProps.put("server.ssl.trust-store-password", truststorePassword);
             } catch (IOException e) {
-            } finally {
-                if (passphrasesStream != null) {
-                    try {
-                        passphrasesStream.close();
-                    } catch (Exception e) {
-                    }
-                }
+                truststorePassword = null;
             }
         }
         if (keystorePassword == null || keystorePassword.isEmpty()) {
             keystorePassword = System.getProperty("KEY_STORE_PASSWORD");
             if (keystorePassword != null && (!keystorePassword.isEmpty()) ) {
-                System.setProperty("server.ssl.key-store-password", new Password(keystorePassword).toString());
+                System.setProperty(PROP_KEY_STORE_PASS, new Password(keystorePassword).toString());
             }
             if (keystorePassword == null || keystorePassword.isEmpty()) {
                 throw new IllegalArgumentException("Mandatory property KEY_STORE_PASSWORD not set");
             }
         }
         else {
-            sslProps.put("server.ssl.key-store-password", keystorePassword);
+            sslProps.put(PROP_KEY_STORE_PASS, keystorePassword);
         }
-        if (truststorePassword == null || truststorePassword.isEmpty()) {
-        }
-        else {
+        if (truststorePassword != null && !truststorePassword.isEmpty()) {
             sslProps.put("server.ssl.trust-store-password", truststorePassword);
         }
         if (!sslProps.isEmpty()) {
index 18d294e..c38e730 100644 (file)
@@ -79,8 +79,6 @@ public class CsarToXmlConverter {
         } catch (XmlArtifactGenerationException e) {
             throw new CsarConverterException(
                     "An error occurred trying to generate XML files from a collection of YAML files : " + e);
-        } finally {
-
         }
 
         return xmlArtifacts;
index f94da4a..ecc81fd 100644 (file)
@@ -45,8 +45,6 @@ public class ModelGenerator implements ArtifactGenerator {
 
     private static final LogHelper logger = LogHelper.INSTANCE;
 
-    private static final String VERSION_DELIMITER = ".";
-    private static final String VERSION_DELIMITER_REGEXP = "\\" + VERSION_DELIMITER;
     private static final String DEFAULT_SERVICE_VERSION = "1.0";
 
     /**
index 50c5d5b..69bbb80 100644 (file)
@@ -80,8 +80,8 @@ public class AaiModelGenerator {
         org.onap.aai.babel.xml.generator.xsd.Model aaiModel = new org.onap.aai.babel.xml.generator.xsd.Model();
         aaiModel.setModelInvariantId(model.getModelId());
         aaiModel.setModelType(model.getModelTypeName());
-        if (model.getModelTypeName() == "service"){
-                       aaiModel.setModelRole(model.getCategory());
+        if ("service".equals(model.getModelTypeName())){
+            aaiModel.setModelRole(model.getCategory());
         }
         aaiModel.setModelVers(new ModelVers());
         aaiModel.getModelVers().getModelVer().add(createModelVersion(model));
index bb43b40..200b0e2 100644 (file)
@@ -47,14 +47,14 @@ public class TestApplication {
         System.setProperty("server.ssl.key-store", "src/test/resources/auth/keystore.jks");
     }
 
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void testApplicationStarts() {
         System.setProperty("KEY_STORE_PASSWORD", "password");
         BabelApplication.main(new String[] {});
         BabelApplication.exit();
     }
 
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void testApplicationStartsWithObfuscatedPassword() {
         System.setProperty("KEY_STORE_PASSWORD", Password.obfuscate("password"));
         BabelApplication.main(new String[] {});
index 4efb03e..15278e5 100644 (file)
@@ -50,12 +50,12 @@ public class TestAuthFileWatcher {
         task = new AuthFileWatcher(mockFile);
     }
 
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void testOnChangeDoesNotRun() {
         task.run();
     }
 
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void testOnChangeDoesRun() throws IOException, AAIAuthException {
         System.setProperty("CONFIG_HOME", "src/test/resources");
         BabelAuthConfig babelServiceAuthConfig = new BabelAuthConfig();
index 431d01f..7375d29 100644 (file)
@@ -23,6 +23,7 @@ package org.onap.aai.babel;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
 
 import java.io.File;
 import java.io.FileWriter;
@@ -31,6 +32,7 @@ import java.util.concurrent.TimeUnit;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
+import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.onap.aai.auth.AAIAuthException;
@@ -117,12 +119,17 @@ public class TestMicroServiceAuth {
      * @throws IOException
      *             for I/O failures, e.g. when creating the temporary auth policy file
      */
-    @Test(expected = AAIAuthException.class)
+    @Test
     public void testReloadDeletedFile() throws AAIAuthException, JSONException, IOException {
         File file = createTestPolicyFile();
         AAIMicroServiceAuthCore.init(file.getAbsolutePath());
         assertThat(file.delete(), is(true));
-        AAIMicroServiceAuthCore.reloadUsers();
+        try {
+            AAIMicroServiceAuthCore.reloadUsers();
+            Assert.fail("Expected an AAIAuthException to be thrown");
+        } catch (AAIAuthException e) {
+            assertTrue(true);
+        }
     }
 
     /**
@@ -172,7 +179,7 @@ public class TestMicroServiceAuth {
      * @throws InterruptedException
      *             if interrupted while sleeping
      */
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void createLocalAuthFileOnChange()
             throws JSONException, AAIAuthException, IOException, InterruptedException {
         File file = createTestPolicyFile();
@@ -212,7 +219,7 @@ public class TestMicroServiceAuth {
      * @throws AAIAuthException
      *             if the Auth Policy cannot be loaded
      */
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void createAuthFromDefaultFileAppHome() throws AAIAuthException {
         System.clearProperty("CONFIG_HOME");
         System.setProperty("APP_HOME", "src/test/resources");
index 20c3434..8e9fb3d 100644 (file)
@@ -107,7 +107,7 @@ public class YamlExtractorTest {
         }
     }
 
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void testArchiveContainsOnlyTheExpectedYmlFilesFromSdWanService()
             throws IOException, InvalidArchiveException {
         final List<Artifact> ymlFiles = CsarTest.SD_WAN_CSAR_FILE.extractArtifacts();
index 9b4375d..127b77d 100644 (file)
@@ -120,7 +120,7 @@ public class TestApplicationLogger {
     /**
      * Call logAuditError() for code coverage stats.
      */
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void logAuditError() {
         LogHelper.INSTANCE.logAuditError(new Exception("test"));
         EELFManager.getInstance().getAuditLogger().setLevel(Level.OFF);
@@ -198,7 +198,7 @@ public class TestApplicationLogger {
         assertThat("audit message content", str, containsString("foo"));
     }
 
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void setDefaultContextValue() {
         LogHelper logger = LogHelper.INSTANCE;
         logger.setDefaultContextValue("key", "value");
@@ -271,12 +271,8 @@ public class TestApplicationLogger {
      */
     private void callUnsupportedOperationMethod(TriConsumer<Enum<?>, LogFields, String[]> logMethod,
             ApplicationMsgs dummyMsg) {
-        try {
-            logMethod.accept(dummyMsg, new LogFields(), new String[] {""});
-            org.junit.Assert.fail("method should have thrown execption"); // NOSONAR as code not reached
-        } catch (UnsupportedOperationException e) {
-            // Expected to reach here
-        }
+        logMethod.accept(dummyMsg, new LogFields(), new String[] {""});
+        org.junit.Assert.fail("method should have thrown execption"); // NOSONAR as code not reached
     }
 
     /**
index 65ec4c3..3fac6cb 100644 (file)
@@ -171,7 +171,7 @@ public class TestArtifactGeneratorToscaParser {
      * @throws XmlArtifactGenerationException
      *             if there is no configuration defined for the test resource's widget type
      */
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void testAddWidgetToService() throws IOException, XmlArtifactGenerationException {
         ArtifactTestUtils testUtils = new ArtifactTestUtils();
         testUtils.loadWidgetMappings();
index ef3fb28..19eeb22 100644 (file)
@@ -120,9 +120,9 @@ public class TestCsarToXmlConverter {
                 SERVICE_VERSION);
     }
 
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void testServiceMetadataMissing()
-            throws IOException, XmlArtifactGenerationException, CsarConverterException {
+            throws IOException, CsarConverterException {
         converter.generateXmlFromCsar(CsarTest.MISSING_METADATA_CSAR.getContent(),
                 CsarTest.MISSING_METADATA_CSAR.getName(), SERVICE_VERSION);
     }
index 66db20a..a76b296 100644 (file)
@@ -44,6 +44,7 @@ import org.junit.BeforeClass;
 import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
 import org.mockito.Mockito;
 import org.onap.aai.auth.AAIAuthException;
 import org.onap.aai.auth.AAIMicroServiceAuth;
index 168f237..43f49a0 100644 (file)
@@ -48,7 +48,7 @@ public class TestModelGenerator {
         new ArtifactTestUtils().setGeneratorSystemProperties();
     }
 
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void testDefaultServiceVersion() throws XmlArtifactGenerationException, IOException {
         Artifact ymlFile = new Artifact(null, null, null, null);
         new ModelGenerator().generateArtifacts(CsarTest.SD_WAN_CSAR_FILE.getContent(),
index 9fc5928..700cf38 100644 (file)
@@ -74,7 +74,7 @@ public class TestModel {
     /**
      * Test that there is no exception if processing a Model that has no metadata properties.
      */
-    @Test
+    @Test(expected = Test.None.class /* no exception expected */)
     public void testNullIdentProperties() {
         createTestModel().populateModelIdentificationInformation(null);
     }
index ebefa9f..35319d6 100644 (file)
@@ -190,19 +190,19 @@ public class TestWidget {
     @Test(expected = org.onap.aai.babel.xml.generator.error.IllegalAccessException.class)
     public void testGetModelNameVersionIdIsUnsupported() throws XmlArtifactGenerationException {
         Widget widgetModel = Widget.createWidget("OAM_NETWORK");
-        assertThat(widgetModel.getModelNameVersionId(), is(nullValue()));
+        widgetModel.getModelNameVersionId();
     }
 
     @Test(expected = org.onap.aai.babel.xml.generator.error.IllegalAccessException.class)
     public void testGetModelTypeNameIsUnsupported() throws XmlArtifactGenerationException {
         Widget widgetModel = Widget.createWidget("OAM_NETWORK");
-        assertThat(widgetModel.getModelTypeName(), is(nullValue()));
+        widgetModel.getModelTypeName();
     }
 
     @Test(expected = org.onap.aai.babel.xml.generator.error.IllegalAccessException.class)
     public void testGetModelIdIsUnsupported() throws XmlArtifactGenerationException {
         Widget widgetModel = Widget.createWidget("OAM_NETWORK");
-        assertThat(widgetModel.getModelId(), is(nullValue()));
+        widgetModel.getModelId();
     }
 
 }