Configuration file **application.yml** contains global definitions required to be consumed by PM REST adapters services.
-- **token-api-username** Defines the username to be used for login
- **synchronization-time-start** Defines the time for execution of pull of PM files and forwarding as VES Message
- **synchronization-time-frequency** Defines the time for execution of pull of PM files and forwarding as VES Message
- **mapping-config-path** Defines the path where mapping configuration file is located
# ==================================================================================
-# Copyright (c) 2020 Nordix
+# Copyright (C) 2021 AT&T Intellectual Property
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
final String trustStorePassword, final Long conectionTimeout, final Long responseTimeout)
throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException,
CertificateException {
- final SSLContext sslContext = getSslContext(new File(trustStore), trustStorePassword);
+ final var sslContext = getSslContext(new File(trustStore), trustStorePassword);
return trustTrustStore(sslContext, conectionTimeout, responseTimeout);
}
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Single;
import java.util.List;
-import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpRequests;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
}
private Completable notify(final String url, final String payload) {
- final SimpleHttpRequest request = SimpleHttpRequests.post(url);
+ final var request = SimpleHttpRequests.post(url);
request.setBody(payload, ContentType.APPLICATION_JSON);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
return Single.fromFuture(httpClient.execute(request, null))
}
private static Completable validatePost(final SimpleHttpResponse response) {
- final String statusLine = new StatusLine(response).toString();
+ final var statusLine = new StatusLine(response).toString();
final String entity;
final int code = response.getCode();
if (code == HttpStatus.SC_OK || code == HttpStatus.SC_ACCEPTED) {
private static void sendTrap(final CommunityTarget<UdpAddress> target, final HashMap<String, String> trap,
final String trapType) throws IOException {
- final PDU pdu = new PDU();
+ final var pdu = new PDU();
pdu.setType(PDU.TRAP);
trap.forEach((key, value) -> {
try {
}
});
- try (final Snmp snmp = new Snmp(new DefaultUdpTransportMapping())) {
+ try (final var snmp = new Snmp(new DefaultUdpTransportMapping())) {
snmp.send(pdu, target, null, null);
LOG.info("Trap {} sent successfully.", trapType);
}
@Override
public ResponseEntity<Resource> getPerformanceManagementFiles() {
LOG.info("Read pm files.");
- final HttpHeaders headers = new HttpHeaders();
+ final var headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<>(ZipUtil.read(), headers, HttpStatus.OK);
}
@Override
public ResponseEntity<String> getTimeZone() {
- final ZoneId zoneId = ZoneId.systemDefault();
+ final var zoneId = ZoneId.systemDefault();
final ZoneOffset offset = zoneId.getRules().getOffset(Instant.now());
LOG.info("ZoneId {} / Offset {}", zoneId, offset);
return ResponseEntity.ok(GSON.toJson(new TimeZoneOffsetResponse(OFFSET_FORMATTER.format(offset))));
if (adapters.get(hostIpAddress) != null) {
throw new AlreadyPresentException(hostIpAddress);
}
- final Adapter adapter =
+ final var adapter =
Adapter.builder().username(username).password(password).hostIpAddress(hostIpAddress).build();
final PerformanceManagementRestAgent pmRestAgent =
pmRestAgentFactory.createPerformanceManagementRestAgent(adapter).blockingGet();
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.io.IOException;
import java.io.StringWriter;
-import java.net.URI;
import java.nio.file.Paths;
import javax.annotation.PostConstruct;
import org.apache.commons.configuration2.YAMLConfiguration;
@PostConstruct
public void init() throws IOException, ConfigurationException {
requireNonNull(mappingFilePath);
- final URI filePath = Paths.get(mappingFilePath).toUri();
+ final var filePath = Paths.get(mappingFilePath).toUri();
builder = new ReloadingFileBasedConfigurationBuilder<>(YAMLConfiguration.class)
.configure(new Parameters().hierarchical().setURL(filePath.toURL()));
builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST, event -> {
*/
public VesMappingConfiguration getVesMappingConfiguration() throws ConfigurationException, IOException {
final YAMLConfiguration configuration = builder.getConfiguration();
- final StringWriter output = new StringWriter();
+ final var output = new StringWriter();
configuration.write(output);
return YAML_READER.readValue(output.toString(), VesMappingConfiguration.class);
}
}
private long initialDelay() {
- final ZonedDateTime now = ZonedDateTime.now(zoneId);
+ final var now = ZonedDateTime.now(zoneId);
ZonedDateTime nextRun = now
.withHour(synchronizationTimeStart.getHour())
if (now.compareTo(nextRun) > 0) {
nextRun = nextRun.plusSeconds(synchronizationTimeFrequency);
}
- final Duration duration = Duration.between(now, nextRun);
- return duration.getSeconds();
+ return Duration.between(now, nextRun).getSeconds();
}
public ZoneId getTimeZone() {
*/
public final Single<PerformanceManagementRestAgent> createPerformanceManagementRestAgent(final Adapter adapter) {
return httpRestClient.getTimeZone(adapter).map(timeZone -> {
- final PerformanceManagementAgentRunnable pmAgentRunnable =
- new PerformanceManagementAgentRunnable(httpRestClient, eventListener, pmFileMapper, adapter);
+ final var pmAgentRunnable = new PerformanceManagementAgentRunnable(httpRestClient, eventListener,
+ pmFileMapper, adapter);
return new PerformanceManagementRestAgent(pmAgentRunnable, properties.getSynchronizationTimeStart(),
properties.getSynchronizationTimeFrequency(), timeZone);
});
.stream().filter(records::containsKey)
.collect(Collectors.toMap(Function.identity(), records::get)));
- final NamedHashMap namedHashMap = new NamedHashMap();
+ final var namedHashMap = new NamedHashMap();
namedHashMap.setName(csv.getAdditionalMeasurementsName());
namedHashMap.setHashMap(csv.getAdditionalMeasurements().stream()
.filter(records::containsKey)
static MeasurementFields toMeasurementFields(final VesMappingConfiguration config,
final Map<String, String> records) {
- final MeasurementFields measurementFields = new MeasurementFields();
+ final var measurementFields = new MeasurementFields();
setMandatoryFields(measurementFields, config);
setOptionalsFields(measurementFields, records, config);
return measurementFields;
LOG.info("Converting ZIP files to VES Message started");
final List<CommonEventFormat302ONAP> listOfNotifications = new ArrayList<>();
final CsvSchema schema = CsvSchema.emptySchema().withHeader();
- final CsvMapper mapper = new CsvMapper();
+ final var mapper = new CsvMapper();
mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
try {
ZipEntry entry;
- final VesMappingConfiguration mappingConfiguration = pmConfigProvider.getVesMappingConfiguration();
+ final var mappingConfiguration = pmConfigProvider.getVesMappingConfiguration();
while ((entry = zipInputStream.getNextEntry()) != null) {
if (entry.getSize() > THRESHOLD_SIZE || entry.getSize() == -1) {
throw new IllegalStateException("File to be unzipped too big.");
final List<List<Event>> mappedEvents = toEvent(mappingConfiguration, hostIp, iterator);
mappedEvents.forEach(mapped -> {
- final CommonEventFormat302ONAP eventFormat = new CommonEventFormat302ONAP();
+ final var eventFormat = new CommonEventFormat302ONAP();
eventFormat.setEventList(mapped);
listOfNotifications.add(eventFormat);
});
final Iterator<Map<String, String>> iterator) {
final List<List<Event>> globalList = new ArrayList<>();
final int batchSize = mappingConfiguration.getBatchSize();
- int sequence = 0;
+ var sequence = 0;
List<Event> events = new ArrayList<>();
final CsvConfiguration csv = mappingConfiguration.getCsv();
while (iterator.hasNext()) {
- final Event event = new Event();
+ final var event = new Event();
final Map<String, String> recordMap = iterator.next();
event.setCommonEventHeader(CommonEventHeaderHandler.toCommonEventHeader(mappingConfiguration, hostIp, csv,
recordMap, sequence));
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipInputStream;
-import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpRequests;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
@Override
public Single<ZoneId> getTimeZone(final Adapter adapter) {
try {
- final ZoneId zoneId = zoneIdCache.get(adapter);
+ final var zoneId = zoneIdCache.get(adapter);
final String offset = OFFSET_FORMATTER.format(zoneId.getRules().getOffset(Instant.now()));
LOG.info("Adapter {} has offset {}", adapter.getHostIpAddress(), offset);
return Single.just(zoneId);
*/
public Single<SimpleHttpResponse> get(final Adapter adapter, final String url) {
return getToken(adapter).flatMap(token -> {
- final SimpleHttpRequest request =
- SimpleHttpRequests.get(HTTPS + adapter.getHostIpAddress() + url);
+ final var request = SimpleHttpRequests.get(HTTPS + adapter.getHostIpAddress() + url);
request.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_VALUE);
request.addHeader(HttpHeaders.AUTHORIZATION, BEARER + token);
return Single.fromFuture(client.execute(request, null))
}
private static Single<SimpleBody> validateGetZipFile(final Adapter adapter, final SimpleHttpResponse response) {
- final String statusLine = new StatusLine(response).toString();
- final ContentType contentType = response.getContentType();
+ final var statusLine = new StatusLine(response).toString();
+ final var contentType = response.getContentType();
final SimpleBody entity = response.getBody();
if (response.getCode() == HttpStatus.SC_OK && entity != null && ContentType.APPLICATION_OCTET_STREAM
.getMimeType().equals(contentType.getMimeType())) {
import java.util.concurrent.ExecutionException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
-import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpRequests;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
public static synchronized String returnToken(final CloseableHttpAsyncClient client, final String tokenEndpoint,
final Adapter adapter) throws ExecutionException, InterruptedException {
final String host = HTTPS + adapter.getHostIpAddress();
- final SimpleHttpRequest request = SimpleHttpRequests.post(host + tokenEndpoint);
- final String basicAuth = Base64.getEncoder().encodeToString(
+ final var request = SimpleHttpRequests.post(host + tokenEndpoint);
+ final var basicAuth = Base64.getEncoder().encodeToString(
(adapter.getUsername() + ":" + adapter.getPassword()).getBytes(StandardCharsets.UTF_8));
request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
request.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_VALUE);
request.addHeader(HttpHeaders.ACCEPT, APPLICATION_JSON_VALUE);
final SimpleHttpResponse response = client.execute(request, null).get();
- final String statusLine = new StatusLine(response).toString();
+ final var statusLine = new StatusLine(response).toString();
if (response.getCode() != HttpStatus.SC_OK) {
throw new TokenGenerationException("Failed to obtain a token for host " + host + ": " + statusLine);
}
*/
public SnmpManagerImpl(final String host, final int port, final SnmpMapper mapper,
final VesEventNotifier vesEventNotifier, final TimeZoneOffsetService timeZoneOffsetService) {
- final SnmpTrapListener trapListener =
- new SnmpTrapListener(host, port, mapper, vesEventNotifier, timeZoneOffsetService);
+ final var trapListener = new SnmpTrapListener(host, port, mapper, vesEventNotifier, timeZoneOffsetService);
this.snmpThread = new Thread(trapListener, SNMP_MANAGER_THREAD);
}
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.io.IOException;
import java.io.StringWriter;
-import java.net.URI;
import java.nio.file.Paths;
import javax.annotation.PostConstruct;
import org.apache.commons.configuration2.YAMLConfiguration;
@PostConstruct
public void init() throws IOException, ConfigurationException {
requireNonNull(mappingFilePath);
- final URI filePath = Paths.get(mappingFilePath).toUri();
+ final var filePath = Paths.get(mappingFilePath).toUri();
builder = new ReloadingFileBasedConfigurationBuilder<>(YAMLConfiguration.class)
.configure(new Parameters().hierarchical().setURL(filePath.toURL()));
builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST, event -> {
*/
public VesMappingConfiguration getVesMappingConfiguration() throws ConfigurationException, IOException {
final YAMLConfiguration configuration = builder.getConfiguration();
- final StringWriter output = new StringWriter();
+ final var output = new StringWriter();
configuration.write(output);
return YAML_READER.readValue(output.toString(), VesMappingConfiguration.class);
}
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.time.LocalDateTime;
-import java.time.ZoneId;
import java.util.Optional;
import org.o.ran.oam.nf.oam.adopter.api.VesEventNotifier;
import org.o.ran.oam.nf.oam.adopter.snmp.manager.api.TimeZoneOffsetService;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.MessageDispatcher;
import org.snmp4j.MessageDispatcherImpl;
-import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.smi.UdpAddress;
@Override
public synchronized void run() {
- try (final DefaultUdpTransportMapping snmpTarget = new DefaultUdpTransportMapping(
+ try (final var snmpTarget = new DefaultUdpTransportMapping(
new UdpAddress(hostPortAddress))) {
- final ThreadPool threadPool = ThreadPool.create("SNMP_V2_Listener", THREADS_SIZE);
- final MessageDispatcher dispatcher =
- new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());
+ final var threadPool = ThreadPool.create("SNMP_V2_Listener", THREADS_SIZE);
+ final var dispatcher = new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());
dispatcher.addMessageProcessingModel(new MPv2c());
listenSnmp(dispatcher, snmpTarget);
} catch (final IOException e) {
@SuppressFBWarnings("WA_NOT_IN_LOOP")
private synchronized void listenSnmp(final MessageDispatcher dispatcher,
final DefaultUdpTransportMapping snmpTarget) {
- try (final Snmp snmp = new Snmp(dispatcher, snmpTarget)) {
+ try (final var snmp = new Snmp(dispatcher, snmpTarget)) {
snmp.addCommandResponder(this);
snmpTarget.listen();
LOG.debug("Listening on {}", snmpTarget);
@Override
public synchronized void processPdu(final CommandResponderEvent cmdRespEvent) {
LOG.info("Received PDU");
- final PDU pdu = cmdRespEvent.getPDU();
+ final var pdu = cmdRespEvent.getPDU();
if (pdu == null) {
LOG.warn("Ignoring PDU.");
return;
}
final UdpAddress address = (UdpAddress) cmdRespEvent.getPeerAddress();
- final ZoneId optZoneId = timeZoneOffsetService.getTimeZone(address.getInetAddress().getHostAddress());
+ final var optZoneId = timeZoneOffsetService.getTimeZone(address.getInetAddress().getHostAddress());
final String timeZone = Optional.ofNullable(optZoneId)
.map(zoneId -> "UTC" + LocalDateTime.now().atZone(zoneId).getOffset().toString()).orElse(null);
static CommonEventHeader toCommonEventHeader(final UdpAddress peerAddress,
final VesMappingConfiguration vesMappingConfig, final TrapsMappingConfiguration mappingConfiguration,
final PDU pdu, final String timeZone) {
- final CommonEventHeader header = new CommonEventHeader();
+ final var header = new CommonEventHeader();
setMandatoryFields(header, peerAddress, vesMappingConfig, mappingConfiguration, pdu);
setOptionalFields(header, vesMappingConfig, mappingConfiguration, pdu, timeZone);
return header;
header.setNfVendorName(vesMappingConfig.getNfVendorName());
final String oidEntityId = mappingConfiguration.getOidReportingEntityID();
if (oidEntityId != null) {
- final Variable uuid = pdu.getVariable(new OID(oidEntityId));
+ final var uuid = pdu.getVariable(new OID(oidEntityId));
header.setReportingEntityId(uuid == null ? null : uuid.toString());
}
header.setNfNamingCode(null); //NOP
final String oidStartEpoch = mappingConfiguration.getEventStartEpochMicrosec();
if (oidStartEpoch != null) {
- final Variable uuid = pdu.getVariable(new OID(oidStartEpoch));
+ final var uuid = pdu.getVariable(new OID(oidStartEpoch));
header.setStartEpochMicrosec(uuid == null ? null : Long.valueOf(uuid.toString()));
} else {
header.setStartEpochMicrosec(System.currentTimeMillis());
final String oidLastEpoch = mappingConfiguration.getEventLastEpochMicrosec();
if (oidLastEpoch != null) {
- final Variable uuid = pdu.getVariable(new OID(oidLastEpoch));
+ final var uuid = pdu.getVariable(new OID(oidLastEpoch));
header.setLastEpochMicrosec(uuid == null ? null : Long.valueOf(uuid.toString()));
} else {
header.setLastEpochMicrosec(System.currentTimeMillis());
header.setSequence(extractEventSequence(mappingConfiguration, pdu));
final String oidSourceName = mappingConfiguration.getOidSourceName();
if (oidSourceName != null) {
- final Variable sourceName = pdu.getVariable(new OID(oidSourceName));
+ final var sourceName = pdu.getVariable(new OID(oidSourceName));
header.setSourceName(sourceName.toString());
} else {
header.setSourceName(peerAddress.getInetAddress().getHostAddress());
import org.o.ran.oam.nf.oam.adopter.snmp.manager.pojos.TrapsMappingConfiguration;
import org.snmp4j.PDU;
import org.snmp4j.smi.OID;
-import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
private static final String SNMP_UNKNOWN = "Unknown";
public static FaultFields toFaultFields(final TrapsMappingConfiguration trapsDescription, final PDU pdu) {
- final FaultFields faultFields = new FaultFields();
+ final var faultFields = new FaultFields();
setMandatoryFields(faultFields, trapsDescription, pdu);
setOptionalFields(faultFields, trapsDescription, pdu);
return faultFields;
final String descOid = trapsDescription.getOidSpecificProblemDesc();
faultFields.setSpecificProblem(SNMP_FAULT);
if (descOid != null && !DEFAULT.equals(descOid)) {
- final Variable desc = pdu.getVariable(new OID(descOid));
+ final var desc = pdu.getVariable(new OID(descOid));
faultFields.setSpecificProblem(desc == null ? SNMP_FAULT : desc.toString());
}
faultFields.setVfStatus(FaultFields.VfStatus.ACTIVE);
faultFields.setAlarmAdditionalInformation(map.isEmpty() ? null : map);
final String interfaceOid = trapsDescription.getOidAlarmInterfaceName();
if (interfaceOid != null) {
- final Variable desc = pdu.getVariable(new OID(interfaceOid));
+ final var desc = pdu.getVariable(new OID(interfaceOid));
faultFields.setAlarmInterfaceA(desc == null ? SNMP_FAULT : desc.toString());
}
final String eCategory = trapsDescription.getEventCategory();
import org.o.ran.oam.nf.oam.adopter.api.Event;
import org.o.ran.oam.nf.oam.adopter.snmp.manager.SnmpMappingConfigurationProvider;
import org.o.ran.oam.nf.oam.adopter.snmp.manager.pojos.TrapsMappingConfiguration;
-import org.o.ran.oam.nf.oam.adopter.snmp.manager.pojos.VesMappingConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.PDU;
}
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();
- final VesMappingConfiguration vesMappingConfig =
- snmpMappingConfigurationProvider.getVesMappingConfiguration();
+ final var event = new Event();
+ final var trapOidVariable = pdu.getVariable(SNMP_TRAP_OID).toString();
+ final var vesMappingConfig = snmpMappingConfigurationProvider.getVesMappingConfiguration();
final Map<String, TrapsMappingConfiguration> trapsDescriptions = vesMappingConfig.getTraps().stream()
.collect(Collectors.toMap(TrapsMappingConfiguration::getOid, trapsDescription -> trapsDescription));
final TrapsMappingConfiguration trapsDescription =
event.setCommonEventHeader(CommonEventHeaderHandler.toCommonEventHeader(peerAddress, vesMappingConfig,
trapsDescription, pdu, timeZone));
event.setFaultFields(FaultFieldsHandler.toFaultFields(trapsDescription, pdu));
- final CommonEventFormat302ONAP eventFormat = new CommonEventFormat302ONAP();
+ final var eventFormat = new CommonEventFormat302ONAP();
eventFormat.setEvent(event);
eventFormat.setEventList(null);
LOG.info("Mapping of SNMP Event type {} finished.", eventType);