Fix Sonar complains 07/6107/1
authorClaudio D. Gasparini <claudio.gasparini@intl.att.com>
Fri, 21 May 2021 07:31:40 +0000 (09:31 +0200)
committerClaudio D. Gasparini <claudio.gasparini@intl.att.com>
Fri, 21 May 2021 08:12:32 +0000 (10:12 +0200)
Issue-ID: OAM-215
Signed-off-by: Claudio D. Gasparini <claudio.gasparini@intl.att.com>
Change-Id: I5ed509a75577327419a9a6f24b18519093bcb945

23 files changed:
ves-nf-oam-adopter/ves-nf-oam-adopter-app/src/main/java/org/o/ran/oam/nf/oam/adopter/app/config/LoginAttemptsLogger.java
ves-nf-oam-adopter/ves-nf-oam-adopter-app/src/main/java/org/o/ran/oam/nf/oam/adopter/app/config/SecurityConfiguration.java
ves-nf-oam-adopter/ves-nf-oam-adopter-app/src/main/java/org/o/ran/oam/nf/oam/adopter/app/controller/RestExceptionHandler.java
ves-nf-oam-adopter/ves-nf-oam-adopter-app/src/main/java/org/o/ran/oam/nf/oam/adopter/app/properties/ServerProperties.java
ves-nf-oam-adopter/ves-nf-oam-adopter-app/src/main/java/org/o/ran/oam/nf/oam/adopter/app/properties/SslProperties.java [deleted file]
ves-nf-oam-adopter/ves-nf-oam-adopter-app/src/test/java/org/o/ran/oam/nf/oam/adopter/app/AdapterApplicationTest.java
ves-nf-oam-adopter/ves-nf-oam-adopter-event-notifier/src/test/java/org/o/ran/oam/nf/oam/adopter/event/notifier/NotificationProviderTest.java
ves-nf-oam-adopter/ves-nf-oam-adopter-mock/src/main/java/org/o/ran/oam/nf/oam/adopter/mock/app/SnmpNotifier.java
ves-nf-oam-adopter/ves-nf-oam-adopter-mock/src/main/java/org/o/ran/oam/nf/oam/adopter/mock/app/config/AuthTokenFilter.java
ves-nf-oam-adopter/ves-nf-oam-adopter-mock/src/main/java/org/o/ran/oam/nf/oam/adopter/mock/app/config/BasicAuthConfiguration.java
ves-nf-oam-adopter/ves-nf-oam-adopter-parent/pom.xml
ves-nf-oam-adopter/ves-nf-oam-adopter-pm-manager/src/main/java/org/o/ran/oam/nf/oam/adopter/pm/rest/manager/AdaptersDeployer.java
ves-nf-oam-adopter/ves-nf-oam-adopter-pm-manager/src/main/java/org/o/ran/oam/nf/oam/adopter/pm/rest/manager/PerformanceManagementMapperConfigProvider.java
ves-nf-oam-adopter/ves-nf-oam-adopter-pm-manager/src/main/java/org/o/ran/oam/nf/oam/adopter/pm/rest/manager/mapper/CommonEventHeaderHandler.java
ves-nf-oam-adopter/ves-nf-oam-adopter-pm-manager/src/main/java/org/o/ran/oam/nf/oam/adopter/pm/rest/manager/mapper/PerformanceManagementFile2VesMapper.java
ves-nf-oam-adopter/ves-nf-oam-adopter-pm-manager/src/main/java/org/o/ran/oam/nf/oam/adopter/pm/rest/manager/pojos/Adapter.java
ves-nf-oam-adopter/ves-nf-oam-adopter-pm-manager/src/test/java/org/o/ran/oam/nf/oam/adopter/pm/rest/manager/PerformanceManagementManagerTest.java
ves-nf-oam-adopter/ves-nf-oam-adopter-pm-sb-rest-client/src/main/java/org/o/ran/oam/nf/oam/adopter/pm/sb/rest/client/DefaultHttpRestClient.java
ves-nf-oam-adopter/ves-nf-oam-adopter-pm-sb-rest-client/src/main/java/org/o/ran/oam/nf/oam/adopter/pm/sb/rest/client/pojos/TimeZoneResponse.java
ves-nf-oam-adopter/ves-nf-oam-adopter-pm-sb-rest-client/src/test/java/org/o/ran/oam/nf/oam/adopter/pm/sb/rest/client/DefaultHttpRestClientTest.java
ves-nf-oam-adopter/ves-nf-oam-adopter-snmp-manager/src/main/java/org/o/ran/oam/nf/oam/adopter/snmp/manager/SnmpMappingConfigurationProvider.java
ves-nf-oam-adopter/ves-nf-oam-adopter-snmp-manager/src/main/java/org/o/ran/oam/nf/oam/adopter/snmp/manager/SnmpTrapListener.java
ves-nf-oam-adopter/ves-nf-oam-adopter-snmp-manager/src/main/java/org/o/ran/oam/nf/oam/adopter/snmp/manager/mapper/SnmpMapperImpl.java

index 072fbb9..0389b6a 100644 (file)
@@ -49,7 +49,7 @@ public class LoginAttemptsLogger {
     }
 
     @Bean
-    public InMemoryAuditEventRepository auditEventRepository() throws Exception {
+    public InMemoryAuditEventRepository auditEventRepository() {
         return new InMemoryAuditEventRepository();
     }
 }
index 2fc030f..de317f3 100644 (file)
@@ -20,7 +20,6 @@
 package org.o.ran.oam.nf.oam.adopter.app.config;
 
 import org.o.ran.oam.nf.oam.adopter.app.properties.ServerProperties;
-import org.o.ran.oam.nf.oam.adopter.app.properties.SslProperties;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.context.properties.EnableConfigurationProperties;
 import org.springframework.context.annotation.Bean;
@@ -43,10 +42,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
 
     @Override
     protected void configure(final HttpSecurity http) throws Exception {
-        final SslProperties ssl = properties.getSsl();
-        if (ssl != null && ssl.getEnabled() != null && ssl.getEnabled()) {
-            http.requiresChannel().anyRequest().requiresSecure();
-        }
+        http.requiresChannel().anyRequest().requiresSecure();
         http.csrf().disable()
                 .antMatcher("/adapters/**")
                 .authorizeRequests().anyRequest()
@@ -55,6 +51,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
     }
 
     @Bean
+    @Autowired
     public AuthenticationManager authenticationManagerBean() throws Exception {
         return super.authenticationManagerBean();
     }
index a4a7d6f..4eb1625 100644 (file)
@@ -64,7 +64,7 @@ public class RestExceptionHandler {
     @ExceptionHandler(MethodArgumentNotValidException.class)
     public Map<String, String> handleValidationExceptions(final MethodArgumentNotValidException ex) {
         final Map<String, String> errors = new HashMap<>();
-        ex.getBindingResult().getAllErrors().forEach((error) -> {
+        ex.getBindingResult().getAllErrors().forEach(error -> {
             final String fieldName = ((FieldError) error).getField();
             final String errorMessage = error.getDefaultMessage();
             errors.put(fieldName, errorMessage);
diff --git a/ves-nf-oam-adopter/ves-nf-oam-adopter-app/src/main/java/org/o/ran/oam/nf/oam/adopter/app/properties/SslProperties.java b/ves-nf-oam-adopter/ves-nf-oam-adopter-app/src/main/java/org/o/ran/oam/nf/oam/adopter/app/properties/SslProperties.java
deleted file mode 100644 (file)
index 6e34bc9..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- *  ============LICENSE_START=======================================================
- *  O-RAN-SC
- *  ================================================================================
- *  Copyright © 2021 AT&T Intellectual Property. 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.o.ran.oam.nf.oam.adopter.app.properties;
-
-import lombok.Data;
-import lombok.NoArgsConstructor;
-
-@Data
-@NoArgsConstructor
-public class SslProperties {
-    private Boolean enabled;
-}
index 3b9cdf3..73cea18 100644 (file)
@@ -82,7 +82,7 @@ class AdapterApplicationTest {
 
     @Test
     @WithMockUser(username = "admin", roles = "ADMIN")
-    public void testGetAllAdapters() throws Exception {
+    void testGetAllAdapters() throws Exception {
         when(deployer.getAll()).thenReturn(Collections.singletonList("mockResult"));
 
         mockMvc.perform(get("/adapters/").secure(true).contentType(MediaType.APPLICATION_JSON)).andDo(print())
@@ -91,14 +91,14 @@ class AdapterApplicationTest {
 
     @Test
     @WithMockUser(username = "admin", roles = "ADMIN")
-    public void testDeleteAdapter() throws Exception {
+    void testDeleteAdapter() throws Exception {
         mockMvc.perform(delete("/adapters/adapter/172.10.55.3").secure(true).contentType(MediaType.APPLICATION_JSON))
                 .andDo(print()).andExpect(status().isOk());
     }
 
     @Test
     @WithMockUser(username = "admin", roles = "ADMIN")
-    public void testNotFound() throws Exception {
+    void testNotFound() throws Exception {
         doThrow(NotFoundException.class).when(deployer).delete(anyString());
 
         mockMvc.perform(delete("/adapters/adapter/172.10.55.3").secure(true).contentType(MediaType.APPLICATION_JSON))
@@ -107,7 +107,7 @@ class AdapterApplicationTest {
 
     @Test
     @WithMockUser(username = "admin", roles = "ADMIN")
-    public void testAddAdapter() throws Exception {
+    void testAddAdapter() throws Exception {
 
         final Adapter adapter = new Adapter();
         adapter.setHost("172.10.55.3");
@@ -123,7 +123,7 @@ class AdapterApplicationTest {
 
     @Test
     @WithMockUser(username = "admin", roles = "ADMIN")
-    public void testAlreadyExist() throws Exception {
+    void testAlreadyExist() throws Exception {
 
         final Adapter adapter = new Adapter();
         adapter.setHost("172.10.55.3");
@@ -141,7 +141,7 @@ class AdapterApplicationTest {
 
     @Test
     @WithMockUser(username = "admin", roles = "ADMIN")
-    public void testMissingArguments() throws Exception {
+    void testMissingArguments() throws Exception {
 
         final Adapter adapter = new Adapter();
         adapter.setHost("172.10.55.3");
@@ -156,7 +156,7 @@ class AdapterApplicationTest {
     }
 
     @Test
-    public void test() {
+    void test() {
         final ZoneId zoneId = ZoneId.of("+02:00");
         when(deployer.getTimeZone("172.10.55.3")).thenReturn(zoneId);
         assertEquals(zoneId, timeZoneServiceProvider.getTimeZone("172.10.55.3"));
index 080eead..95cf87a 100644 (file)
@@ -50,7 +50,7 @@ import org.springframework.boot.test.mock.mockito.MockBean;
 
 @SpringBootTest(classes = {NotificationProvider.class, VesCollectorProperties.class})
 @EnableConfigurationProperties
-public class NotificationProviderTest {
+class NotificationProviderTest {
 
     @Autowired
     VesEventNotifier vesEventNotifier;
index 388a1ce..3f759f2 100644 (file)
@@ -47,7 +47,7 @@ public class SnmpNotifier {
 
     private final HashMap<String, String> alarmTrap;
     private final HashMap<String, String> clearTrap;
-    private final CommunityTarget target;
+    private final CommunityTarget<UdpAddress> target;
 
     /**
      * Default constructor.
@@ -74,7 +74,7 @@ public class SnmpNotifier {
         sendTrap(target, clearTrap, "clear");
     }
 
-    private static void sendTrap(final CommunityTarget target, final HashMap<String, String> trap,
+    private static void sendTrap(final CommunityTarget<UdpAddress> target, final HashMap<String, String> trap,
             final String trapType) throws IOException {
         final PDU pdu = new PDU();
         pdu.setType(PDU.TRAP);
@@ -86,10 +86,9 @@ public class SnmpNotifier {
             }
         });
 
-
-        final Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
-        snmp.send(pdu, target, null, null);
-        snmp.close();
-        LOG.info("Trap {} sent successfully.", trapType);
+        try (final Snmp snmp = new Snmp(new DefaultUdpTransportMapping())) {
+            snmp.send(pdu, target, null, null);
+            LOG.info("Trap {} sent successfully.", trapType);
+        }
     }
 }
index ca5ec04..79e0633 100644 (file)
@@ -33,7 +33,7 @@ import org.springframework.util.StringUtils;
 import org.springframework.web.filter.OncePerRequestFilter;
 
 public class AuthTokenFilter extends OncePerRequestFilter {
-    private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
+    private static final Logger LOG = LoggerFactory.getLogger(AuthTokenFilter.class);
 
     public static final String TOKEN = "someRandomToken";
     private final UsernamePasswordAuthenticationToken authentication;
@@ -52,7 +52,7 @@ public class AuthTokenFilter extends OncePerRequestFilter {
                 SecurityContextHolder.getContext().setAuthentication(authentication);
             }
         } catch (final Exception e) {
-            logger.error("Cannot set user authentication", e);
+            LOG.error("Cannot set user authentication", e);
         }
 
         filterChain.doFilter(request, response);
index 0c4be6a..93c44f8 100644 (file)
@@ -52,6 +52,7 @@ public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter {
                 .httpBasic();
     }
 
+    @Override
     @Bean
     public AuthenticationManager authenticationManagerBean() throws Exception {
         return super.authenticationManagerBean();
index a200391..cdc7b9e 100644 (file)
             ${project.reporting.outputDirectory}/jacoco-aggregate
         </jacoco.reportDirectory.aggregate>
         <sonar.coverage.jacoco.xmlReportPaths>
-            ../ves-nf-oam-adopter-event-notifier/target/site/jacoco-ut/jacoco.xml,
-            ../ves-nf-oam-adopter-event-notifier/target/site/jacoco-aggregate/jacoco.xml,
-            ../ves-nf-oam-adopter-snmp-manager/target/site/jacoco-ut/jacoco.xml,
-            ../ves-nf-oam-adopter-snmp-manager/target/site/jacoco-aggregate/jacoco.xml,
-            ../ves-nf-oam-adopter-pm-manager/target/site/jacoco-ut/jacoco.xml,
-            ../ves-nf-oam-adopter-pm-manager/target/site/jacoco-aggregate/jacoco.xml,
-            ../ves-nf-oam-adopter-pm-sb-rest-client/target/site/jacoco-ut/jacoco.xml,
-            ../ves-nf-oam-adopter-pm-sb-rest-client/target/site/jacoco-aggregate/jacoco.xml
+            ../ves-nf-oam-adopter/ves-nf-oam-adopter-event-notifier/target/site/jacoco-ut/jacoco.xml,
+            ../ves-nf-oam-adopter/ves-nf-oam-adopter-event-notifier/target/site/jacoco-aggregate/jacoco.xml,
+            ../ves-nf-oam-adopter/ves-nf-oam-adopter-snmp-manager/target/site/jacoco-ut/jacoco.xml,
+            ../ves-nf-oam-adopter/ves-nf-oam-adopter-snmp-manager/target/site/jacoco-aggregate/jacoco.xml,
+            ../ves-nf-oam-adopter/ves-nf-oam-adopter-pm-manager/target/site/jacoco-ut/jacoco.xml,
+            ../ves-nf-oam-adopter/ves-nf-oam-adopter-pm-manager/target/site/jacoco-aggregate/jacoco.xml,
+            ../ves-nf-oam-adopter/ves-nf-oam-adopter-pm-sb-rest-client/target/site/jacoco-ut/jacoco.xml,
+            ../ves-nf-oam-adopter/ves-nf-oam-adopter-pm-sb-rest-client/target/site/jacoco-aggregate/jacoco.xml,
+            ../ves-nf-oam-adopter/ves-nf-oam-adopter-app/target/site/jacoco-ut/jacoco.xml,
+            ../ves-nf-oam-adopter/ves-nf-oam-adopter-app/target/site/jacoco-aggregate/jacoco.xml
         </sonar.coverage.jacoco.xmlReportPaths>
-        <sonar.scanner.version>3.8.0.2131</sonar.scanner.version>
+        <sonar.scanner.version>4.4.0.2170</sonar.scanner.version>
+        <sonar.exclusions>
+            **/api/**,
+            **/model/**,
+            **/pojos/**,
+            **/configurations/**,
+            **/properties/**,
+            **/config/**,
+            **/dto/**
+        </sonar.exclusions>
         <!--Dependency Versions-->
         <commons-configuration2.version>2.7</commons-configuration2.version>
         <commons-io.version>2.6</commons-io.version>
index 924373d..2cd5c5c 100644 (file)
@@ -19,8 +19,6 @@
 
 package org.o.ran.oam.nf.oam.adopter.pm.rest.manager;
 
-import static org.eclipse.jdt.annotation.Checks.requireNonNull;
-
 import com.google.common.collect.ImmutableList;
 import java.time.ZoneId;
 import java.util.List;
@@ -66,7 +64,7 @@ public final class AdaptersDeployer implements PerformanceManagementAdaptersDepl
 
     @Override
     public synchronized void delete(final String host) throws NotFoundException {
-        LOG.info("Adapter PM adapter removed {}", requireNonNull(host));
+        LOG.info("Adapter PM adapter removed {}", host);
         final PerformanceManagementRestAgent adapter = adapters.remove(host);
         if (adapter == null) {
             throw new NotFoundException(host);
index b7c24f8..36ff149 100644 (file)
@@ -32,12 +32,10 @@ import org.apache.commons.configuration2.YAMLConfiguration;
 import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent;
 import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
 import org.apache.commons.configuration2.builder.fluent.Parameters;
-import org.apache.commons.configuration2.event.EventListener;
 import org.apache.commons.configuration2.ex.ConfigurationException;
 import org.o.ran.oam.nf.oam.adopter.pm.rest.manager.pojos.VesMappingConfiguration;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
@@ -51,11 +49,6 @@ public class PerformanceManagementMapperConfigProvider  {
     private String mappingFilePath;
     private ReloadingFileBasedConfigurationBuilder<YAMLConfiguration> builder;
 
-    @Autowired
-    public PerformanceManagementMapperConfigProvider() {
-
-    }
-
     /**
      * Initialize Service.
      */
@@ -65,9 +58,9 @@ public class PerformanceManagementMapperConfigProvider  {
         final URI filePath = Paths.get(mappingFilePath).toUri();
         builder = new ReloadingFileBasedConfigurationBuilder<>(YAMLConfiguration.class)
                           .configure(new Parameters().hierarchical().setURL(filePath.toURL()));
-        builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST, (EventListener) event -> {
+        builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST, event -> {
             builder.getReloadingController().checkForReloading(null);
-            LOG.debug("Reloading {}", filePath.toString());
+            LOG.debug("Reloading {}", filePath);
         });
         //Test initial configuration
         builder.getConfiguration();
index 7049285..b2375ec 100644 (file)
@@ -36,9 +36,9 @@ final class CommonEventHeaderHandler {
     private static final String PM_NOTIFICATIONS = "PM_Notification";
 
     static CommonEventHeader toCommonEventHeader(final VesMappingConfiguration config, final String hostIp,
-            final CsvConfiguration csv, final Map<String, String> record, final int sequence) {
+            final CsvConfiguration csv, final Map<String, String> recordMap, final int sequence) {
         final CommonEventHeader header = new CommonEventHeader();
-        setMandatoryFields(config, hostIp, csv, header, record, sequence);
+        setMandatoryFields(config, hostIp, csv, header, recordMap, sequence);
         setOptionalFields(config, header);
         return header;
     }
@@ -52,7 +52,7 @@ final class CommonEventHeaderHandler {
     }
 
     private static void setMandatoryFields(final VesMappingConfiguration config, final String hostIp,
-            final CsvConfiguration csv, final CommonEventHeader header, final Map<String, String> record,
+            final CsvConfiguration csv, final CommonEventHeader header, final Map<String, String> recordMap,
             final int sequence) {
         header.setDomain(CommonEventHeader.Domain.MEASUREMENT);
         header.setEventName(CommonEventHeader.Domain.FAULT.name()
@@ -64,7 +64,7 @@ final class CommonEventHeaderHandler {
         header.setReportingEntityName(config.getReportingEntityName());
         header.setSequence((long) sequence);
         final String sourceNameField = csv.getSourceName();
-        final String sourceNameRecordValue = Optional.ofNullable(sourceNameField).map(record::get).orElse(hostIp);
+        final String sourceNameRecordValue = Optional.ofNullable(sourceNameField).map(recordMap::get).orElse(hostIp);
         final Optional<String> optRegex = Optional.ofNullable(csv.getSourceNameRegex());
         header.setSourceName(optRegex.map(regex -> sourceNameRecordValue.replaceAll(regex, ""))
             .orElse(sourceNameRecordValue));
@@ -75,8 +75,8 @@ final class CommonEventHeaderHandler {
 
         final List<String> eventId = csv.getEventId();
         final String keyIdConcat =  eventId.stream()
-                .filter(record::containsKey)
-                .map(record::get)
+                .filter(recordMap::containsKey)
+                .map(recordMap::get)
                 .collect(Collectors.joining());
         header.setEventId(UUID.nameUUIDFromBytes(keyIdConcat.getBytes(StandardCharsets.UTF_8)).toString());
     }
index 6036a93..3cc99cd 100644 (file)
@@ -108,10 +108,10 @@ public class PerformanceManagementFile2VesMapper {
         final CsvConfiguration csv = mappingConfiguration.getCsv();
         while (iterator.hasNext()) {
             final Event event = new Event();
-            final Map<String, String> record = iterator.next();
-            event.setCommonEventHeader(
-                    CommonEventHeaderHandler.toCommonEventHeader(mappingConfiguration, hostIp, csv, record, sequence));
-            event.setMeasurementFields(MeasurementFieldsHandler.toMeasurementFields(mappingConfiguration, record));
+            final Map<String, String> recordMap = iterator.next();
+            event.setCommonEventHeader(CommonEventHeaderHandler.toCommonEventHeader(mappingConfiguration, hostIp, csv,
+                recordMap,  sequence));
+            event.setMeasurementFields(MeasurementFieldsHandler.toMeasurementFields(mappingConfiguration, recordMap));
             events.add(event);
             sequence++;
             if (sequence % batchSize == 0) {
index 555634b..e061d81 100644 (file)
@@ -28,7 +28,7 @@ import lombok.NonNull;
 @Getter
 @Builder
 public final class Adapter {
-    private @NonNull final String hostIpAddress;
-    private @NonNull final String username;
-    private @NonNull final String password;
+    @NonNull private final String hostIpAddress;
+    @NonNull private final String username;
+    @NonNull private final String password;
 }
index eb0112e..46c942c 100644 (file)
@@ -49,7 +49,7 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
 @ExtendWith(SpringExtension.class)
 @SpringBootTest(classes = {VesEventNotifierMock.class, PerformanceManagementMapperConfigProvider.class,
     PerformanceManagementFile2VesMapper.class, PerformanceManagementAdaptersDeployer.class})
-public class PerformanceManagementManagerTest {
+class PerformanceManagementManagerTest {
 
     @Autowired
     @Qualifier("test")
@@ -75,7 +75,7 @@ public class PerformanceManagementManagerTest {
 
     @Test
     @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
-    public void testMapping() throws IOException, InterruptedException, AlreadyPresentException {
+    void testMapping() throws IOException, InterruptedException, AlreadyPresentException {
         assertTrue(deployer.getAll().isEmpty());
         deployer.create("172.0.10.2", "admin", "admin");
         assertFalse(deployer.getAll().isEmpty());
@@ -87,7 +87,7 @@ public class PerformanceManagementManagerTest {
     }
 
     @Test
-    public void testDelete() throws AlreadyPresentException, NotFoundException {
+    void testDelete() throws AlreadyPresentException, NotFoundException {
         assertTrue(deployer.getAll().isEmpty());
         deployer.create("172.0.10.2", "admin", "admin");
         assertFalse(deployer.getAll().isEmpty());
@@ -97,24 +97,24 @@ public class PerformanceManagementManagerTest {
     }
 
     @Test
-    public void testAlreadyPresent() throws AlreadyPresentException {
+    void testAlreadyPresent() throws AlreadyPresentException {
         assertTrue(deployer.getAll().isEmpty());
         deployer.create("172.0.10.2", "admin", "admin");
         assertFalse(deployer.getAll().isEmpty());
 
         final Exception alreadyPresentException = assertThrows(AlreadyPresentException.class,
                 () -> deployer.create("172.0.10.2", "admin", "admin"));
-        assertEquals(alreadyPresentException.getMessage(), "Adapter 172.0.10.2 already present.");
+        assertEquals("Adapter 172.0.10.2 already present.", alreadyPresentException.getMessage());
     }
 
     @Test
-    public void testNotPresent() {
+    void testNotPresent() {
         final Exception exception = assertThrows(NotFoundException.class, () -> deployer.delete("172.0.10.2"));
-        assertEquals(exception.getMessage(), "Adapter 172.0.10.2 is not present.");
+        assertEquals("Adapter 172.0.10.2 is not present.", exception.getMessage());
     }
 
     @Test
-    public void testTimeZone() throws AlreadyPresentException {
+    void testTimeZone() throws AlreadyPresentException {
         deployer.create("172.0.10.2", "admin", "admin");
         assertEquals(deployer.getTimeZone("172.0.10.2"), ZoneId.of("+02:00"));
     }
index b1d6008..a99fedd 100644 (file)
@@ -111,8 +111,8 @@ public final class DefaultHttpRestClient implements HttpRestClient {
     public Single<ZoneId> getTimeZone(final Adapter adapter) {
         try {
             final ZoneId zoneId = zoneIdCache.get(adapter);
-            LOG.info("Adapter {} has offset {}", adapter.getHostIpAddress(),
-                    OFFSET_FORMATTER.format(zoneId.getRules().getOffset(Instant.now())));
+            final String offset = OFFSET_FORMATTER.format(zoneId.getRules().getOffset(Instant.now()));
+            LOG.info("Adapter {} has offset {}", adapter.getHostIpAddress(), offset);
             return Single.just(zoneId);
         } catch (final Exception e) {
             final Throwable cause = e.getCause();
@@ -136,7 +136,7 @@ public final class DefaultHttpRestClient implements HttpRestClient {
             request.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_VALUE);
             request.addHeader(HttpHeaders.AUTHORIZATION, BEARER + token);
             return Single.fromFuture(client.execute(request, null))
-                    .doOnSubscribe(result -> LOG.trace("GET Request started {} ...", request.toString()))
+                    .doOnSubscribe(result -> LOG.trace("GET Request started {} ...", request))
                     .doOnSuccess(result -> LOG.trace("GET Request finished {}", request));
         });
     }
@@ -146,9 +146,7 @@ public final class DefaultHttpRestClient implements HttpRestClient {
             final String token = sessionCache.get(adapter);
             return Single.just(token);
         } catch (final Exception e) {
-            if (e.getCause() instanceof TokenGenerationException) {
-                return Single.error(e.getCause());
-            } else if (e.getCause() instanceof ConnectionClosedException) {
+            if (e.getCause() instanceof TokenGenerationException || e.getCause() instanceof ConnectionClosedException) {
                 return Single.error(e.getCause());
             }
             return Single.error(e);
index f9c115a..4088e05 100644 (file)
@@ -35,7 +35,7 @@ import org.springframework.test.annotation.DirtiesContext.MethodMode;
 @SpringBootTest(classes = {DefaultHttpRestClient.class, PmEndpointsUrlsProperties.class})
 @EnableConfigurationProperties
 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
-public class DefaultHttpRestClientTest {
+class DefaultHttpRestClientTest {
 
     private static final Adapter ADAPTER =
             Adapter.builder().hostIpAddress("150.62.25.26").username("admin").password("secretPassword").build();
@@ -47,7 +47,7 @@ public class DefaultHttpRestClientTest {
 
     @Test
     @DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
-    public void testGetFailedToken() {
+    void testGetFailedToken() {
         final SimpleHttpResponse response =
                 SimpleHttpResponse.create(HttpStatus.SC_UNAUTHORIZED, "error", ContentType.APPLICATION_JSON);
 
@@ -67,7 +67,7 @@ public class DefaultHttpRestClientTest {
     }
 
     @Test
-    public void testReadFiles() throws IOException {
+    void testReadFiles() throws IOException {
         final String tokenJson = JsonUtils.readJson("/json/tokenResponse.json");
         final SimpleHttpResponse response =
                 SimpleHttpResponse.create(HttpStatus.SC_OK, tokenJson, ContentType.APPLICATION_JSON);
@@ -95,7 +95,7 @@ public class DefaultHttpRestClientTest {
     }
 
     @Test
-    public void testReadFilesResponseFail() throws IOException {
+    void testReadFilesResponseFail() throws IOException {
         final String tokenJson = JsonUtils.readJson("/json/tokenResponse.json");
         final SimpleHttpResponse response =
                 SimpleHttpResponse.create(HttpStatus.SC_OK, tokenJson, ContentType.APPLICATION_JSON);
@@ -123,7 +123,7 @@ public class DefaultHttpRestClientTest {
     }
 
     @Test
-    public void testGetTimeOffset() throws IOException {
+    void testGetTimeOffset() throws IOException {
         final String tokenJson = JsonUtils.readJson("/json/tokenResponse.json");
         final SimpleHttpResponse response =
                 SimpleHttpResponse.create(HttpStatus.SC_OK, tokenJson, ContentType.APPLICATION_JSON);
@@ -151,7 +151,7 @@ public class DefaultHttpRestClientTest {
     }
 
     @Test
-    public void testGetTimeOffsetFail() throws IOException {
+    void testGetTimeOffsetFail() throws IOException {
         final String tokenJson = JsonUtils.readJson("/json/tokenResponse.json");
         final SimpleHttpResponse response =
                 SimpleHttpResponse.create(HttpStatus.SC_OK, tokenJson, ContentType.APPLICATION_JSON);
index ac2a810..9797e5c 100644 (file)
@@ -32,7 +32,6 @@ import org.apache.commons.configuration2.YAMLConfiguration;
 import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent;
 import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
 import org.apache.commons.configuration2.builder.fluent.Parameters;
-import org.apache.commons.configuration2.event.EventListener;
 import org.apache.commons.configuration2.ex.ConfigurationException;
 import org.o.ran.oam.nf.oam.adopter.snmp.manager.pojos.VesMappingConfiguration;
 import org.slf4j.Logger;
@@ -62,7 +61,7 @@ public class SnmpMappingConfigurationProvider {
         final URI filePath = Paths.get(mappingFilePath).toUri();
         builder = new ReloadingFileBasedConfigurationBuilder<>(YAMLConfiguration.class)
                 .configure(new Parameters().hierarchical().setURL(filePath.toURL()));
-        builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST, (EventListener) event -> {
+        builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST, event -> {
             builder.getReloadingController().checkForReloading(null);
             LOG.info("Reloading {}", filePath);
         });
index 0784b3e..09c7ff3 100644 (file)
@@ -61,29 +61,29 @@ final class SnmpTrapListener implements CommandResponder, Runnable {
         this.timeZoneOffsetService = timeZoneOffsetService;
     }
 
-    @SuppressFBWarnings("WA_NOT_IN_LOOP")
     @Override
     public synchronized void run() {
-        try {
-            final UdpAddress udpAddress = new UdpAddress(hostPortAddress);
-            final DefaultUdpTransportMapping snmpTarget = new DefaultUdpTransportMapping(udpAddress);
+        try (final DefaultUdpTransportMapping snmpTarget = new DefaultUdpTransportMapping(
+                new UdpAddress(hostPortAddress))) {
             final ThreadPool threadPool = ThreadPool.create("SNMP_V2_Listener", THREADS_SIZE);
             final MessageDispatcher dispatcher =
                     new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());
             dispatcher.addMessageProcessingModel(new MPv2c());
+            listenSnmp(dispatcher, snmpTarget);
+        } catch (final IOException e) {
+            LOG.error("Error occurred while listening to SNMP messages: {}", e.getMessage());
+        }
+    }
 
-            final Snmp snmp = new Snmp(dispatcher, snmpTarget);
+    @SuppressFBWarnings("WA_NOT_IN_LOOP")
+    private void listenSnmp(final MessageDispatcher dispatcher, final DefaultUdpTransportMapping snmpTarget) {
+        try (final Snmp snmp = new Snmp(dispatcher, snmpTarget)) {
             snmp.addCommandResponder(this);
-
             snmpTarget.listen();
             LOG.debug("Listening on {}", snmpTarget);
-            try {
-                wait();
-            } catch (final InterruptedException ex) {
-                Thread.currentThread().interrupt();
-            }
-        } catch (final IOException e) {
-            LOG.error("Error occurred while listening to SNMP messages: {}", e.getMessage());
+            wait();
+        } catch (final InterruptedException | IOException ex) {
+            Thread.currentThread().interrupt();
         }
     }
 
index 125e37d..901ac2f 100644 (file)
@@ -58,7 +58,7 @@ public class SnmpMapperImpl implements SnmpMapper {
                 LOG.warn("SNMP Event type {} not supported, ignoring event.", eventType);
                 return Maybe.empty();
             }
-            LOG.info("Starting Mapping of SNMP Event type {}.", eventType);
+            LOG.info("Starting Mapping of SNMP Event.");
             LOG.trace("Pdu received {}.", pdu);
             final Event event = new Event();
             final String trapOidVariable = pdu.getVariable(SNMP_TRAP_OID).toString();