Fix sonar violations 69/48469/8
authorWojciech Sliwka <wojciech.sliwka@nokia.com>
Tue, 22 May 2018 06:36:40 +0000 (08:36 +0200)
committerTal Gitelman <tg851x@intl.att.com>
Tue, 24 Jul 2018 14:21:26 +0000 (14:21 +0000)
Fix major sonar violations in ConfigurationUtils,ConfigurationImpl, PropertyType
Issue-ID: SDC-1353

Change-Id: Ic3959ba174f0a9fcd3976c9d12c6425dc4353e72
Signed-off-by: Wojciech Sliwka <wojciech.sliwka@nokia.com>
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/ConfigurationUtils.java
common/onap-common-configuration-management/onap-configuration-management-core/src/main/java/org/onap/config/impl/ConfigurationImpl.java
common/onap-sdc-artifact-generator-lib/onap-sdc-artifact-generator-api/src/main/java/org/onap/sdc/generator/aai/model/Model.java
common/onap-sdc-artifact-generator-lib/onap-sdc-artifact-generator-test/src/main/java/org/onap/sdc/generator/SampleJUnitTest.java
common/onap-tosca-datatype/src/main/java/org/onap/sdc/tosca/datatypes/model/PropertyType.java
common/onap-tosca-datatype/src/main/java/org/onap/sdc/tosca/datatypes/model/heatextend/PropertyTypeExt.java

index 358dab9..53baaec 100644 (file)
@@ -16,6 +16,8 @@ import org.apache.commons.configuration2.builder.fluent.Parameters;
 import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler;
 import org.apache.commons.configuration2.ex.ConfigurationException;
 import org.apache.commons.io.IOUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.onap.config.api.Config;
 import org.onap.config.api.ConfigurationManager;
 import org.onap.config.impl.ConfigurationRepository;
@@ -48,6 +50,7 @@ import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 import java.util.Queue;
 import java.util.Set;
 import java.util.SortedSet;
@@ -65,6 +68,8 @@ import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
 import static com.google.common.collect.ImmutableMap.builder;
+
+import static java.util.Optional.ofNullable;
 import static org.onap.config.api.Hint.EXTERNAL_LOOKUP;
 import static org.onap.config.api.Hint.LATEST_LOOKUP;
 import static org.onap.config.api.Hint.NODE_SPECIFIC;
@@ -73,19 +78,20 @@ import static org.onap.config.api.Hint.NODE_SPECIFIC;
  * The type Configuration utils.
  */
 public class ConfigurationUtils {
+    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationUtils.class);
 
     private ConfigurationUtils() {
     }
 
-    private static ImmutableMap<Class,Class> arrayClassMap;
+    private static ImmutableMap<Class, Class> arrayClassMap;
 
     static {
-        ImmutableMap.Builder<Class,Class> builder = builder();
-        builder.put(Byte.class,Byte[].class).put(Short.class, Short[].class)
-                .put(Integer.class,Integer[].class).put(Long.class,Long[].class)
-                .put(Float.class,Float[].class).put(Double.class,Double[].class)
-                .put(Boolean.class,Boolean[].class).put(Character.class,Character[].class)
-                .put(String.class,String[].class);
+        ImmutableMap.Builder<Class, Class> builder = builder();
+        builder.put(Byte.class, Byte[].class).put(Short.class, Short[].class)
+                .put(Integer.class, Integer[].class).put(Long.class, Long[].class)
+                .put(Float.class, Float[].class).put(Double.class, Double[].class)
+                .put(Boolean.class, Boolean[].class).put(Character.class, Character[].class)
+                .put(String.class, String[].class);
         arrayClassMap = builder.build();
     }
 
@@ -217,11 +223,10 @@ public class ConfigurationUtils {
      * @return the namespace
      */
     public static String getNamespace(URL url) {
-        String namespace = getNamespace(getConfiguration(url));
-        if (namespace != null) {
-            return namespace.toUpperCase();
-        }
-        return getNamespace(url.getFile().toUpperCase());
+
+        Optional<String> namespace = getConfiguration(url).flatMap(ConfigurationUtils::getNamespace).map(String::toUpperCase);
+
+        return namespace.orElseGet(() -> getNamespace(url.getFile().toUpperCase()));
     }
 
     /**
@@ -231,16 +236,16 @@ public class ConfigurationUtils {
      * @return the namespace
      */
     public static String getNamespace(File file) {
-        String namespace = getNamespace(getConfiguration(file));
-        if (namespace != null) {
-            return namespace.toUpperCase();
-        }
-        return getNamespace(file.getName().toUpperCase());
+        Optional<String> namespace = getConfiguration(file)
+                .flatMap(ConfigurationUtils::getNamespace)
+                .map(String::toUpperCase);
+        return namespace.orElseGet(() -> getNamespace(file.getName().toUpperCase()));
     }
 
-    private static String getNamespace(Configuration config) {
-        return config.getString(Constants.NAMESPACE_KEY) == null ? null
-                : config.getString(Constants.NAMESPACE_KEY).toUpperCase();
+    private static Optional<String> getNamespace(Configuration config) {
+        return ofNullable(config)
+                .flatMap(configuration -> ofNullable(configuration.getString(Constants.NAMESPACE_KEY)))
+                .map(String::toUpperCase);
     }
 
     /**
@@ -283,22 +288,27 @@ public class ConfigurationUtils {
      * @return the merge strategy
      */
     public static ConfigurationMode getMergeStrategy(URL url) {
-        String configMode = getMergeStrategy(getConfiguration(url));
-        if (configMode != null) {
-            try {
-                return Enum.valueOf(ConfigurationMode.class, configMode);
-            } catch (Exception exception) {
-                //do nothing
-            }
+        Optional<ConfigurationMode> configurationMode = getConfiguration(url).flatMap(ConfigurationUtils::getMergeStrategy).flatMap(ConfigurationUtils::convertConfigurationMode);
+        return configurationMode.orElseGet(() -> getMergeStrategy(url.getFile().toUpperCase()));
+    }
+
+    private static Optional<ConfigurationMode> convertConfigurationMode(String configMode) {
+        ConfigurationMode configurationMode = null;
+        try {
+            configurationMode = ConfigurationMode.valueOf(configMode);
+        } catch (Exception exception) {
+            LOGGER.error("Could not find convert {} into configuration mode", configMode);
         }
-        return getMergeStrategy(url.getFile().toUpperCase());
+        return Optional.ofNullable(configurationMode);
     }
 
-    private static String getMergeStrategy(Configuration config) {
-        return config.getString(Constants.MODE_KEY) == null ? null
-                : config.getString(Constants.MODE_KEY).toUpperCase();
+    private static Optional<String> getMergeStrategy(Configuration config) {
+        return ofNullable(config)
+                .flatMap(configuration -> ofNullable(configuration.getString(Constants.MODE_KEY)))
+                .map(String::toUpperCase);
     }
 
+
     /**
      * Gets merge strategy.
      *
@@ -306,15 +316,8 @@ public class ConfigurationUtils {
      * @return the merge strategy
      */
     public static ConfigurationMode getMergeStrategy(File file) {
-        String configMode = getMergeStrategy(getConfiguration(file));
-        if (configMode != null) {
-            try {
-                return Enum.valueOf(ConfigurationMode.class, configMode);
-            } catch (Exception exception) {
-                //do nothing
-            }
-        }
-        return getMergeStrategy(file.getName().toUpperCase());
+        Optional<ConfigurationMode> configurationMode = getConfiguration(file).flatMap(ConfigurationUtils::getMergeStrategy).flatMap(ConfigurationUtils::convertConfigurationMode);
+        return configurationMode.orElseGet(() -> getMergeStrategy(file.getName().toUpperCase()));
     }
 
     /**
@@ -356,7 +359,7 @@ public class ConfigurationUtils {
      * @param url the url
      * @return the configuration
      */
-    public static FileBasedConfiguration getConfiguration(URL url) {
+    public static Optional<FileBasedConfiguration> getConfiguration(URL url) {
         FileBasedConfiguration builder = null;
         try {
             ConfigurationType configType = ConfigurationUtils.getConfigType(url);
@@ -374,12 +377,12 @@ public class ConfigurationUtils {
                     builder = new Configurations().fileBased(YamlConfiguration.class, url);
                     break;
                 default:
-                    throw new ConfigurationException("Configuration type not supported:"+ configType);
+                    throw new ConfigurationException("Configuration type not supported:" + configType);
             }
         } catch (ConfigurationException exception) {
             exception.printStackTrace();
         }
-        return builder;
+        return ofNullable(builder);
     }
 
     /**
@@ -388,7 +391,7 @@ public class ConfigurationUtils {
      * @param file the file
      * @return the configuration
      */
-    public static FileBasedConfiguration getConfiguration(File file) {
+    public static Optional<FileBasedConfiguration> getConfiguration(File file) {
         FileBasedConfiguration builder = null;
         try {
             ConfigurationType configType = ConfigurationUtils.getConfigType(file);
@@ -406,12 +409,12 @@ public class ConfigurationUtils {
                     builder = new Configurations().fileBased(YamlConfiguration.class, file);
                     break;
                 default:
-                    throw new ConfigurationException("Configuration type not supported:"+ configType);
+                    throw new ConfigurationException("Configuration type not supported:" + configType);
             }
         } catch (ConfigurationException exception) {
             exception.printStackTrace();
         }
-        return builder;
+        return ofNullable(builder);
     }
 
     /**
@@ -441,7 +444,6 @@ public class ConfigurationUtils {
     }
 
 
-
     /**
      * Gets array class.
      *
@@ -534,7 +536,7 @@ public class ConfigurationUtils {
                 builder = new ReloadingFileBasedConfigurationBuilder<>(YamlConfiguration.class);
                 break;
             default:
-                throw new IllegalArgumentException("Configuration type not supported:"+ configType);
+                throw new IllegalArgumentException("Configuration type not supported:" + configType);
         }
         return builder;
     }
index 43b1b96..7faf3ee 100644 (file)
@@ -206,12 +206,13 @@ public class ConfigurationImpl implements org.onap.config.api.Configuration {
   @Override
   public <T> T get(String tenant, String namespace, String key, Class<T> clazz, Hint... hints) {
 
-    String[] tenantNamespaceArrayy = null;
-    if (tenant == null && namespace != null
-        && (tenantNamespaceArrayy = namespace.split(Constants.TENANT_NAMESPACE_SAPERATOR)).length
-        > 1) {
-      tenant = tenantNamespaceArrayy[0];
-      namespace = tenantNamespaceArrayy[1];
+    String[] tenantNamespaceArrayy;
+    if (tenant == null && namespace != null) {
+      tenantNamespaceArrayy = namespace.split(Constants.TENANT_NAMESPACE_SAPERATOR);
+      if (tenantNamespaceArrayy.length > 1) {
+        tenant = tenantNamespaceArrayy[0];
+        namespace = tenantNamespaceArrayy[1];
+      }
     }
 
     tenant = ConfigurationRepository.lookup().isValidTenant(tenant) ? tenant.toUpperCase()
index ac8dffa..83ded46 100644 (file)
@@ -26,7 +26,6 @@ import org.onap.sdc.generator.data.GeneratorConstants;
 import org.onap.sdc.generator.error.IllegalAccessException;
 
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.Map;
 import java.util.Set;
 
@@ -36,7 +35,6 @@ public abstract class Model {
   protected Set<Widget> widgets = new HashSet<>();
   private String modelId;
   private String modelName;
-  private ModelType modelType;
   private String modelVersion;
   private String modelNameVersionId;
   private String modelDescription;
@@ -50,7 +48,7 @@ public abstract class Model {
   public static Model getModelFor(String toscaType) {
 
     Model modelToBeReturned = null;
-    while (toscaType != null && toscaType.lastIndexOf(".") != -1 && modelToBeReturned == null) {
+    while (isModelNotSet(toscaType, modelToBeReturned)) {
 
       switch (toscaType) {
 
@@ -91,6 +89,7 @@ public abstract class Model {
     return modelToBeReturned;
   }
 
+
   public abstract boolean addResource(Resource resource);
 
   public abstract boolean addWidget(Widget resource);
@@ -152,7 +151,6 @@ public abstract class Model {
    * @return the model type
    */
   public ModelType getModelType() {
-    //checkSupported();
     if (this instanceof Service) {
       return ModelType.SERVICE;
     } else if (this instanceof Resource) {
@@ -165,12 +163,10 @@ public abstract class Model {
   }
 
   public String getModelName() {
-    //checkSupported();
     return modelName;
   }
 
   public String getModelVersion() {
-    //checkSupported();
     return modelVersion;
   }
 
@@ -180,7 +176,6 @@ public abstract class Model {
   }
 
   public String getModelDescription() {
-    //checkSupported();
     return modelDescription;
   }
 
@@ -190,51 +185,49 @@ public abstract class Model {
    * @param modelIdentInfo the model ident info
    */
   public void populateModelIdentificationInformation(Map<String, String> modelIdentInfo) {
-    Iterator<String> iter = modelIdentInfo.keySet().iterator();
-    String property;
-    while (iter.hasNext()) {
-      switch (property = iter.next()) {
+    for (Map.Entry<String,String> entry : modelIdentInfo.entrySet()) {
+      String property=entry.getKey();
+      switch (property) {
 
         case "vfModuleModelInvariantUUID":
         case "serviceInvariantUUID":
         case "resourceInvariantUUID":
         case "invariantUUID":
         case "providing_service_invariant_uuid":
-          modelId = modelIdentInfo.get(property);
+          modelId = entry.getValue();
           break;
         case "vfModuleModelUUID":
         case "resourceUUID":
         case "serviceUUID":
         case "UUID":
         case "providing_service_uuid":
-          modelNameVersionId = modelIdentInfo.get(property);
+          modelNameVersionId = entry.getValue();
           break;
         case "vfModuleModelVersion":
         case "serviceVersion":
         case "resourceversion":
         case "version":
-          modelVersion = modelIdentInfo.get(property);
+          modelVersion = entry.getValue();
           break;
         case "vfModuleModelName":
         case "serviceName":
         case "resourceName":
         case "name":
-          modelName = modelIdentInfo.get(property);
+          modelName = entry.getValue();
           break;
         case "serviceDescription":
         case "resourceDescription":
         case "vf_module_description":
         case "description":
-          modelDescription = modelIdentInfo.get(property);
+          modelDescription = entry.getValue();
           break;
         case "providing_service_name":
-          modelName = modelIdentInfo.get(property);
-          modelDescription = modelIdentInfo.get(property);
+          modelName = entry.getValue();
+          modelDescription = entry.getValue();
           break;
         default:
           break;
       }
-      property = null;
     }
 
 
@@ -249,11 +242,14 @@ public abstract class Model {
     return widgets;
   }
 
-  private void checkSupported() throws IllegalAccessException {
+  private void checkSupported() {
     if (this instanceof Widget) {
       throw new IllegalAccessException(GeneratorConstants
           .GENERATOR_AAI_ERROR_UNSUPPORTED_WIDGET_OPERATION);
     }
   }
 
+  private static boolean isModelNotSet(String toscaType, Model modelToBeReturned) {
+    return toscaType != null && toscaType.lastIndexOf(".") != -1 && modelToBeReturned == null;
+  }
 }
index 6b59e2e..2494656 100644 (file)
@@ -1555,14 +1555,15 @@ public class SampleJUnitTest extends TestCase {
 
     public static void readPayload(List<Artifact> inputArtifacts,InputStream fis, String fileName) throws IOException {
         byte[] payload = new byte[fis.available()];
-        fis.read(payload);
-        String checksum = GeneratorUtil.checkSum(payload);
-        byte[] encodedPayload = GeneratorUtil.encode(payload);
-        Artifact artifact = new Artifact(AAI_ARTIFACT_TYPE, AAI_ARTIFACT_GROUP_TYPE, checksum, encodedPayload);
-        artifact.setName(fileName);
-        artifact.setLabel(fileName);
-        artifact.setDescription(fileName);
-        inputArtifacts.add(artifact);
+        if (fis.read(payload) > 0) {
+            String checksum = GeneratorUtil.checkSum(payload);
+            byte[] encodedPayload = GeneratorUtil.encode(payload);
+            Artifact artifact = new Artifact(AAI_ARTIFACT_TYPE, AAI_ARTIFACT_GROUP_TYPE, checksum, encodedPayload);
+            artifact.setName(fileName);
+            artifact.setLabel(fileName);
+            artifact.setDescription(fileName);
+            inputArtifacts.add(artifact);
+        }
     }
 
 
index d08a127..cc861d2 100644 (file)
@@ -64,9 +64,6 @@ public enum PropertyType {
    * @return PropertyType
    */
   public static PropertyType getPropertyTypeByDisplayName(String displayName) {
-    if (mMap == null) {
-      initializeMapping();
-    }
     if (mMap.containsKey(displayName)) {
       return mMap.get(displayName);
     }
index 34d91cb..ffe06e6 100644 (file)
@@ -63,9 +63,6 @@ public enum PropertyTypeExt {
    * @return the property type by display name
    */
   public static PropertyTypeExt getPropertyTypeByDisplayName(String displayName) {
-    if (mMap == null) {
-      initializeMapping();
-    }
     if (mMap.containsKey(displayName)) {
       return mMap.get(displayName);
     }