}
@Bean
- public InMemoryAuditEventRepository auditEventRepository() throws Exception {
+ public InMemoryAuditEventRepository auditEventRepository() {
return new InMemoryAuditEventRepository();
}
}
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;
@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()
}
@Bean
+ @Autowired
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@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);
private int port;
private String username;
private String password;
- private SslProperties ssl;
}
+++ /dev/null
-/*
- * ============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;
-}
@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())
@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))
@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");
@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");
@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");
}
@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"));
@SpringBootTest(classes = {NotificationProvider.class, VesCollectorProperties.class})
@EnableConfigurationProperties
-public class NotificationProviderTest {
+class NotificationProviderTest {
@Autowired
VesEventNotifier vesEventNotifier;
private final HashMap<String, String> alarmTrap;
private final HashMap<String, String> clearTrap;
- private final CommunityTarget target;
+ private final CommunityTarget<UdpAddress> target;
/**
* Default constructor.
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);
}
});
-
- 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);
+ }
}
}
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;
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);
.httpBasic();
}
+ @Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
${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>
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;
@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);
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;
private String mappingFilePath;
private ReloadingFileBasedConfigurationBuilder<YAMLConfiguration> builder;
- @Autowired
- public PerformanceManagementMapperConfigProvider() {
-
- }
-
/**
* Initialize Service.
*/
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();
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;
}
}
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()
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));
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());
}
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) {
@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;
}
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {VesEventNotifierMock.class, PerformanceManagementMapperConfigProvider.class,
PerformanceManagementFile2VesMapper.class, PerformanceManagementAdaptersDeployer.class})
-public class PerformanceManagementManagerTest {
+class PerformanceManagementManagerTest {
@Autowired
@Qualifier("test")
@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());
}
@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());
}
@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"));
}
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();
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));
});
}
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);
@Setter
public class TimeZoneResponse {
@SerializedName(value = "offset")
- private @NonNull final String offset;
+ @NonNull
+ private final String offset;
}
@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();
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
- public void testGetFailedToken() {
+ void testGetFailedToken() {
final SimpleHttpResponse response =
SimpleHttpResponse.create(HttpStatus.SC_UNAUTHORIZED, "error", ContentType.APPLICATION_JSON);
}
@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);
}
@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);
}
@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);
}
@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);
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;
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);
});
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();
}
}
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();