/*
* ============LICENSE_START=======================================================
* Copyright (C) 2022 Bell Canada
- * Modifications Copyright (c) 2022-2024 Nordix Foundation
+ * Modifications Copyright (c) 2022-2025 OpenInfra Foundation Europe.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
- return ResponseEntity.ok(Collections.<RestOutputCmHandle>emptyList());
+ return ResponseEntity.ok(Collections.emptyList());
}
private ResponseEntity<Map<String, Object>> populateAsyncResponse(final String topicParamInQuery) {
@Service
public class ResourceProviderImpl implements ResourceProvider {
- private String pathToResponseFiles;
+ private final String pathToResponseFiles;
@Autowired
public ResourceProviderImpl(@Value("${stub.path}") final String pathToResponseFiles) {
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2023-2024 Nordix Foundation
+ * Copyright (C) 2023-2025 OpenInfra Foundation Europe. 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.
@Getter
public enum NcmpResponseStatus {
- SUCCESS("0", "Successfully applied changes"),
+ @SuppressWarnings("unused") SUCCESS("0", "Successfully applied changes"),
CM_DATA_SUBSCRIPTION_ACCEPTED("1", "ACCEPTED"),
CM_HANDLES_NOT_FOUND("100", "cm handle reference(s) not found"),
CM_HANDLES_NOT_READY("101", "cm handle(s) not ready"),
UNKNOWN_ERROR("108", "Unknown error"),
CM_HANDLE_ALREADY_EXIST("109", "cm-handle already exists"),
CM_HANDLE_INVALID_ID("110", "cm handle reference has an invalid character(s) in id"),
- ALTERNATE_ID_ALREADY_ASSOCIATED("111", "alternate id already associated"),
- MESSAGE_TOO_LARGE("112", "message too large");
+ @SuppressWarnings("unused") ALTERNATE_ID_ALREADY_ASSOCIATED("111", "alternate id already associated"),
+ @SuppressWarnings("unused") MESSAGE_TOO_LARGE("112", "message too large");
private final String code;
private final String message;
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2024 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
package org.onap.cps.ncmp.api.data.models;
-import lombok.Getter;
-import lombok.RequiredArgsConstructor;
import org.onap.cps.ncmp.config.CpsApplicationContext;
import org.onap.cps.ncmp.impl.utils.AlternateIdMatcher;
-@Getter
-@RequiredArgsConstructor
-public class CmResourceAddress {
-
- private final String datastoreName;
- private final String cmHandleReference;
- private final String resourceIdentifier;
+public record CmResourceAddress(String datastoreName, String cmHandleReference, String resourceIdentifier) {
public String resolveCmHandleReferenceToId() {
final AlternateIdMatcher alternateIdMatcher = CpsApplicationContext.getCpsBean(AlternateIdMatcher.class);
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2024 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
String dataJobId,
DataJobMetadata dataJobMetadata,
DataJobWriteRequest dataJobWriteRequest);
-}
\ No newline at end of file
+}
public String toString() {
return dmiServiceName + "#" + dataProducerIdentifier;
}
-}
\ No newline at end of file
+}
* @param dataContentType Define the data request content type.
* e.g. "application/3gpp-json-patch+json" etc.
* @param dataProducerId Identifier of the data producer.
- * @param dataJobId Identifier for the overall Datajob
+ * @param dataJobId Identifier for the overall data job
* @param data A collection of outgoing write operations.
*/
public record SubJobWriteRequest (
String dataContentType,
String dataProducerId,
String dataJobId,
- Collection<DmiWriteOperation> data) {}
\ No newline at end of file
+ Collection<DmiWriteOperation> data) {}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2022-2024 Nordix Foundation
+ * Copyright (C) 2022-2025 OpenInfra Foundation Europe. 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.
package org.onap.cps.ncmp.api.exceptions;
+import java.io.Serial;
import lombok.Getter;
import org.onap.cps.ncmp.api.NcmpResponseStatus;
@Getter
public class DmiClientRequestException extends NcmpException {
+ @Serial
private static final long serialVersionUID = 6659897770659834797L;
final NcmpResponseStatus ncmpResponseStatus;
final String message;
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation
+ * Copyright (C) 2021-2025 OpenInfra Foundation Europe. 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.
package org.onap.cps.ncmp.api.exceptions;
+import java.io.Serial;
import lombok.Getter;
/**
*/
public class NcmpException extends RuntimeException {
+ @Serial
private static final long serialVersionUID = 1482619410918497467L;
@Getter
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2024 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
package org.onap.cps.ncmp.api.exceptions;
+import java.io.Serial;
import lombok.Getter;
/**
@Getter
public class PolicyExecutorException extends NcmpException {
+ @Serial
private static final long serialVersionUID = 6659897770659834798L;
/**
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2022 Bell Canada
- * Modifications Copyright (C) 2022-2024 Nordix Foundation
+ * Modifications Copyright (C) 2022--2025 OpenInfra Foundation Europe.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
final Collection<String> failedXpaths, final NcmpResponseStatus ncmpResponseStatus) {
final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>(failedXpaths.size());
for (final String xpath : failedXpaths) {
- try {
- final String cmHandleId = YangDataConverter.extractCmHandleIdFromXpath(xpath);
- cmHandleRegistrationResponses
- .add(CmHandleRegistrationResponse.createFailureResponse(cmHandleId, ncmpResponseStatus));
- } catch (IllegalArgumentException | IllegalStateException e) {
- log.warn("Unexpected xpath {}", xpath);
+ final String cmHandleId = YangDataConverter.extractCmHandleIdFromXpath(xpath);
+ if (cmHandleId == null) {
+ log.warn("Unexpected xpath (no id found) {}", xpath);
+ } else {
+ final CmHandleRegistrationResponse cmHandleRegistrationResponse =
+ CmHandleRegistrationResponse.createFailureResponse(cmHandleId, ncmpResponseStatus);
+ cmHandleRegistrationResponses.add(cmHandleRegistrationResponse);
}
}
return cmHandleRegistrationResponses;
}
public enum Status {
- SUCCESS, FAILURE;
+ SUCCESS, FAILURE
}
}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2022-2023 Nordix Foundation
+ * Copyright (C) 2022-2025 OpenInfra Foundation Europe. 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.
private String lastSyncTime;
}
- @Data
- @Builder
- @JsonInclude(JsonInclude.Include.NON_NULL)
- public static class Running {
-
- @JsonProperty("sync-state")
- private String syncState;
-
- @JsonProperty("last-sync-time")
- private String lastSyncTime;
- }
-
/**
* The date and time format used for the cm handle sync state.
*
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2023 Nordix Foundation
+ * Copyright (C) 2023-2025 OpenInfra Foundation Europe. 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.
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
+import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
@Component
* @param cpsBeanClass cps class type
* @return requested bean instance
*/
- public static <T extends Object> T getCpsBean(final Class<T> cpsBeanClass) {
+ public static <T> T getCpsBean(final Class<T> cpsBeanClass) {
return applicationContext.getBean(cpsBeanClass);
}
@Override
- public void setApplicationContext(final ApplicationContext cpsApplicationContext) {
+ public void setApplicationContext(@NonNull final ApplicationContext cpsApplicationContext) {
setCpsApplicationContext(cpsApplicationContext);
}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2024 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
@Value("${spring.application.name:cps-application}")
private String serviceId;
+ @SuppressWarnings("HttpUrlsUsage")
@Value("${cps.tracing.exporter.endpoint:http://onap-otel-collector:4317}")
private String tracingExporterEndpointUrl;
+ @SuppressWarnings("HttpUrlsUsage")
@Value("${cps.tracing.sampler.jaeger_remote.endpoint:http://onap-otel-collector:14250}")
private String jaegerRemoteSamplerUrl;
/**
* Custom annotation to enable metric scraping.
*/
+@SuppressWarnings("UnusedReturnValue")
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TimedCustom {
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2023 Nordix Foundation
- * ================================================================================
- * 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.cps.ncmp.exceptions;
-
-import org.onap.cps.ncmp.api.exceptions.NcmpException;
-
-/**
- * NCMP start up exception.
- */
-public class NcmpStartUpException extends NcmpException {
-
- /**
- * Constructor.
- *
- * @param message the error message
- * @param details the error details
- */
- public NcmpStartUpException(final String message, final String details) {
- super(message, details);
- }
-}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2025 Nordix Foundation
+ * Copyright (C) 2025 OpenInfra Foundation Europe. 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.
@Configuration
public class AdminCacheConfig extends HazelcastCacheConfig {
- private static final MapConfig cmHandleStateCacheMapConfig = createMapConfig("cmHandleStateCacheMapConfig");
+ private static final MapConfig cmHandleStateCacheMapConfig = createGenericMapConfig("cmHandleStateCacheMapConfig");
/**
* Distributed instance admin cache map for cm handles by state for use of gauge metrics.
public class AlternateIdCacheConfig extends HazelcastCacheConfig {
private static final MapConfig cmHandleIdPerAlternateIdMapConfig =
- createMapConfig("cmHandleIdPerAlternateIdMapConfig");
+ createGenericMapConfig("cmHandleIdPerAlternateIdMapConfig");
/**
* Distributed instance used for mapping alternate id to cm handle id.
/*
* ============LICENSE_START========================================================
- * Copyright (C) 2024 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
// Lock names for different use cases ( to be used as cpsAndNcmpLock keys)
public static final String MODULE_SYNC_WORK_QUEUE_LOCK_NAME = "workQueueLock";
- private static final MapConfig cpsAndNcmpLockMapConfig = createMapConfig("cpsAndNcmpLockConfig");
+ private static final MapConfig cpsAndNcmpLockMapConfig = createGenericMapConfig("cpsAndNcmpLockConfig");
/**
* Distributed instance used for locking purpose for various use cases in cps-and-ncmp.
/*
* ============LICENSE_START========================================================
- * Copyright (C) 2023-2025 Nordix Foundation
+ * Copyright (C) 2023-2025 OpenInfra Foundation Europe. 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.
import com.hazelcast.config.Config;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.NamedConfig;
-import com.hazelcast.config.NearCacheConfig;
import com.hazelcast.config.QueueConfig;
import com.hazelcast.config.SetConfig;
import com.hazelcast.core.Hazelcast;
private Config getHazelcastInstanceConfig(final String instanceConfigName) {
final HazelcastInstance hazelcastInstance = Hazelcast.getHazelcastInstanceByName(instanceConfigName);
- Config config = null;
- if (hazelcastInstance != null) {
- config = hazelcastInstance.getConfig();
- } else {
- config = new Config(instanceConfigName);
+ if (hazelcastInstance == null) {
+ return new Config(instanceConfigName);
}
- return config;
+ return hazelcastInstance.getConfig();
}
- protected static MapConfig createMapConfig(final String configName) {
+ protected static MapConfig createGenericMapConfig(final String configName) {
final MapConfig mapConfig = new MapConfig(configName);
mapConfig.setBackupCount(1);
return mapConfig;
}
- protected static MapConfig createMapConfigWithTimeToLiveInSeconds(final String configName,
- final int timeToLiveInSeconds) {
- final MapConfig mapConfig = new MapConfig(configName);
- mapConfig.setBackupCount(1);
- mapConfig.setTimeToLiveSeconds(timeToLiveInSeconds);
- return mapConfig;
- }
- protected static MapConfig createNearCacheMapConfig(final String configName) {
- final MapConfig mapConfig = new MapConfig(configName);
- mapConfig.setBackupCount(1);
- mapConfig.setNearCacheConfig(new NearCacheConfig(configName));
- return mapConfig;
- }
protected static QueueConfig createQueueConfig(final String configName) {
final QueueConfig commonQueueConfig = new QueueConfig(configName);
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2024 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
public class CmSubscriptionConfig extends HazelcastCacheConfig {
private static final MapConfig cmNotificationSubscriptionCacheMapConfig =
- createMapConfig("cmNotificationSubscriptionCacheMapConfig");
+ createGenericMapConfig("cmNotificationSubscriptionCacheMapConfig");
/**
* Distributed instance of cm notification subscription information
/**
* Update status in map of subscription details per DMI.
*
- * @param subscriptionId String of subscription Id
+ * @param subscriptionId String of subscription id
* @param dmiServiceName String of dmiServiceName
* @param status String of status
*
/**
* Persist map of subscription details per DMI.
*
- * @param subscriptionId String of subscription Id
+ * @param subscriptionId String of subscription id
* @param dmiServiceName String of dmiServiceName
*
*/
if (Boolean.TRUE.equals(dataSyncEnabled)) {
final AvcEvent cmAvcEvent = toTargetEvent(cmAvcEventAsConsumerRecord.value(), AvcEvent.class);
log.debug("Event to be processed to update the cache with cmHandleId : {}", cmHandleId);
- cmAvcEventService.processCmAvcEvent(cmHandleId, cmAvcEvent);
+ if (cmAvcEvent != null) {
+ cmAvcEventService.processCmAvcEvent(cmHandleId, cmAvcEvent);
+ }
}
}
}
private String getCpsPath(final String cmHandleId, final String restConfStylePath) {
- log.debug("Getting cps path from the restconfpath : {}", restConfStylePath);
+ log.debug("Getting cps path from the rest config path : {}", restConfStylePath);
final Anchor anchor = cpsAnchorService.getAnchor(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleId);
return yangParser.getCpsPathFromRestConfStylePath(anchor, restConfStylePath);
}
final CmHandle cmHandle = new CmHandle();
final Map<String, String> cmHandleAdditionalProperties = new LinkedHashMap<>();
yangModelCmHandle.getAdditionalProperties()
- .forEach(additionalProperty -> cmHandleAdditionalProperties.put(additionalProperty.getName(),
- additionalProperty.getValue()));
+ .forEach(additionalProperty -> cmHandleAdditionalProperties.put(additionalProperty.name(),
+ additionalProperty.value()));
cmHandle.setCmhandleId(yangModelCmHandle.getId());
cmHandle.setPrivateProperties(cmHandleAdditionalProperties);
cmSubscriptionCmHandles.add(cmHandle);
/**
* Send the event to the provided dmi plugin with key as subscription id and the event is in Cloud Event format.
*
- * @param subscriptionId Cm Subscription Id
- * @param dmiPluginName Dmi Plugin Name
+ * @param subscriptionId CM subscription id
+ * @param dmiPluginName Dmi plugin Name
* @param eventType Type of event
* @param dmiInEvent Cm Notification Subscription event for Dmi
*/
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2024 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
public enum CmSubscriptionStatus {
- ACCEPTED("ACCEPTED"), REJECTED("REJECTED"), PENDING("PENDING");
+ ACCEPTED(), REJECTED(), PENDING()
- private final String cmNotificationSubscriptionStatusValue;
-
- CmSubscriptionStatus(final String cmNotificationSubscriptionStatusValue) {
- this.cmNotificationSubscriptionStatusValue = cmNotificationSubscriptionStatusValue;
- }
}
import java.util.Map;
/**
- * Tuple to be used during for to delete usecase.
+ * Tuple to be used during for to delete use case.
*
* @param lastRemainingSubscriptionsPerDmi subscriptions that are used by only one subscriber grouped per dmi
* @param overlappingSubscriptionsPerDmi subscriptions that are shared by multiple subscribers grouped per dmi
final DmiCmSubscriptionKey dmiCmSubscriptionKey = extractCmSubscriptionKey(subscriptionNode.getXpath());
final String dmiServiceName = inventoryPersistence.getYangModelCmHandle(
dmiCmSubscriptionKey.cmHandleId()).getDmiServiceName();
+ @SuppressWarnings("unchecked")
final List<String> subscribers = (List<String>) subscriptionNode.getLeaves().get("subscriptionIds");
populateDmiCmSubscriptionTuple(subscribers, overlappingSubscriptionsPerDmi,
lastRemainingSubscriptionsPerDmi, dmiServiceName, dmiCmSubscriptionKey);
throw new IllegalArgumentException("DataNode xpath does not represent a subscription key");
}
-}
\ No newline at end of file
+}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2024 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
containerFactory = "cloudEventConcurrentKafkaListenerContainerFactory")
public void consumeSubscriptionEvent(final ConsumerRecord<String, CloudEvent> ncmpInEventAsConsumerRecord) {
final CloudEvent cloudEvent = ncmpInEventAsConsumerRecord.value();
- final NcmpInEvent ncmpInEvent =
- toTargetEvent(cloudEvent, NcmpInEvent.class);
- log.info("Subscription with name {} to be mapped to hazelcast object...",
+ final NcmpInEvent ncmpInEvent = toTargetEvent(cloudEvent, NcmpInEvent.class);
+ if (ncmpInEvent != null) {
+ log.info("Subscription with name {} to be mapped to hazelcast object...",
ncmpInEvent.getData().getSubscriptionId());
- final String subscriptionId = ncmpInEvent.getData().getSubscriptionId();
- final List<Predicate> predicates = ncmpInEvent.getData().getPredicates();
- if ("subscriptionCreateRequest".equals(cloudEvent.getType())) {
- log.info("Subscription create request for source {} with subscription id {} ...",
+ final String subscriptionId = ncmpInEvent.getData().getSubscriptionId();
+ final List<Predicate> predicates = ncmpInEvent.getData().getPredicates();
+ if ("subscriptionCreateRequest".equals(cloudEvent.getType())) {
+ log.info("Subscription create request for source {} with subscription id {} ...",
cloudEvent.getSource(), subscriptionId);
- cmSubscriptionHandler.processSubscriptionCreateRequest(subscriptionId, predicates);
- }
- if ("subscriptionDeleteRequest".equals(cloudEvent.getType())) {
- log.info("Subscription delete request for source {} with subscription id {} ...",
+ cmSubscriptionHandler.processSubscriptionCreateRequest(subscriptionId, predicates);
+ }
+ if ("subscriptionDeleteRequest".equals(cloudEvent.getType())) {
+ log.info("Subscription delete request for source {} with subscription id {} ...",
cloudEvent.getSource(), subscriptionId);
- cmSubscriptionHandler.processSubscriptionDeleteRequest(subscriptionId);
+ cmSubscriptionHandler.processSubscriptionDeleteRequest(subscriptionId);
+ }
}
}
}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2024 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
/**
* Mapper to form a response for the client for the Cm Notification Subscription.
*
- * @param subscriptionId Cm Notification Subscription Id
+ * @param subscriptionId CM notification subscription id
* @param dmiSubscriptionsPerDmi contains CmNotificationSubscriptionDetails per dmi plugin
* @return CmNotificationSubscriptionNcmpOutEvent to sent back to the client
*/
* Send the event to the client who requested the subscription with key as subscription id and event is Cloud
* Event compliant.
*
- * @param subscriptionId Cm Subscription Id
+ * @param subscriptionId CM subscription id
* @param eventType Type of event
* @param ncmpOutEvent Cm Notification Subscription Event for the
* client
import java.time.OffsetDateTime;
import java.util.Collection;
import java.util.Collections;
-import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
* @param alternateId the alternate id target of the data job subscription
* @return collection of subscription ids of ongoing cm notification subscription
*/
+ @SuppressWarnings("unchecked")
public Collection<String> getSubscriptionIds(final String dataType, final String alternateId) {
final String query = CPS_PATH_TEMPLATE_FOR_SUBSCRIPTION_WITH_ALTERNATE_ID_AND_DATATYPE.formatted(
alternateId, dataType);
if (existingNodes.isEmpty()) {
return Collections.emptyList();
}
- return (List<String>) existingNodes.iterator().next().getLeaves().get("dataJobId");
+ return (Collection<String>) existingNodes.iterator().next().getLeaves().get("dataJobId");
}
/**
* @param subscriptionId data job subscription id to be added
*/
public void addSubscription(final String dataType, final String alternateId, final String subscriptionId) {
- final Collection<String> subscriptionIds =
- getSubscriptionIds(dataType, alternateId);
+ final Collection<String> subscriptionIds = getSubscriptionIds(dataType, alternateId);
if (subscriptionIds.isEmpty()) {
addNewSubscriptionDetails(dataType, alternateId, subscriptionId);
} else {
validateIfCmHandleStateReady(yangModelCmHandle, cmHandleState);
final String jsonRequestBody = getDmiRequestBody(READ, requestId, null, null, yangModelCmHandle);
final UrlTemplateParameters urlTemplateParameters = getUrlTemplateParameters(cmResourceAddress
- .getDatastoreName(), yangModelCmHandle, cmResourceAddress.getResourceIdentifier(), options, topic);
+ .datastoreName(), yangModelCmHandle, cmResourceAddress.resourceIdentifier(), options, topic);
return dmiRestClient.asynchronousPostOperationWithJsonData(DATA, urlTemplateParameters, jsonRequestBody, READ,
authorization);
}
final String authorization) {
final FetchDescendantsOption fetchDescendantsOption =
FetchDescendantsOption.getFetchDescendantsOption(includeDescendants);
-
- final Map<String, Object> dataNodes = cpsFacade.getDataNodesByAnchorV3(resolveDatastoreName(cmResourceAddress),
- cmResourceAddress.resolveCmHandleReferenceToId(), cmResourceAddress.getResourceIdentifier(),
+ validateDatastore(cmResourceAddress.datastoreName());
+ final Map<String, Object> dataNodes = cpsFacade.getDataNodesByAnchorV3(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME,
+ cmResourceAddress.resolveCmHandleReferenceToId(), cmResourceAddress.resourceIdentifier(),
fetchDescendantsOption);
return Mono.justOrEmpty(dataNodes);
}
- private String resolveDatastoreName(final CmResourceAddress cmResourceAddress) {
- final String datastoreName = cmResourceAddress.getDatastoreName();
- if (datastoreName.equals(OPERATIONAL.getDatastoreName())) {
- return NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME;
- }
- throw new IllegalArgumentException(
+ private void validateDatastore(final String datastoreName) {
+ if (!datastoreName.equals(OPERATIONAL.getDatastoreName())) {
+ throw new IllegalArgumentException(
"Unsupported datastore name provided to fetch the cached data: " + datastoreName);
+ }
}
}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2022-2024 Nordix Foundation
+ * Copyright (C) 2022-2025 OpenInfra Foundation Europe. 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.
* @param topic the topic param in query
* @param dataOperationRequest data operation request details for resource data
* @param authorization contents of Authorization header, or null if not present
- * @return a map with one entry of request Id for success or status and error when async feature is disabled
+ * @return a map with one entry of request id for success or status and error when async feature is disabled
*/
public Map<String, String> executeAsynchronousRequest(final String topic,
final DataOperationRequest dataOperationRequest,
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2021 highstreet technologies GmbH
- * Modifications Copyright (C) 2021-2024 Nordix Foundation
+ * Modifications Copyright (C) 2021-2025 OpenInfra Foundation Europe.
* Modifications Copyright (C) 2021 Pantheon.tech
* Modifications Copyright (C) 2021-2022 Bell Canada
* Modifications Copyright (C) 2023 TechMahindra Ltd.
final String authorization) {
final NcmpDatastoreRequestHandler ncmpDatastoreRequestHandler
- = getNcmpDatastoreRequestHandler(cmResourceAddress.getDatastoreName());
+ = getNcmpDatastoreRequestHandler(cmResourceAddress.datastoreName());
return ncmpDatastoreRequestHandler.executeRequest(cmResourceAddress, optionsParamInQuery,
topicParamInQuery, includeDescendants, authorization);
}
* @param topic the topic param in query
* @param dataOperationRequest data operation request details for resource data
* @param authorization contents of Authorization header, or null if not present
- * @return a map with one entry of request Id for success or status and error when async feature is disabled
+ * @return a map with one entry of request id for success or status and error when async feature is disabled
*/
public Object executeDataOperationForCmHandles(final String topic,
final DataOperationRequest dataOperationRequest,
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2023 Nordix Foundation
+ * Copyright (C) 2023-2025 OpenInfra Foundation Europe. 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.
*/
@Bean
public RecordFilterStrategy<String, CloudEvent> includeDataOperationEventsOnly() {
- return consumerRecord ->
- isNotCloudEventOfType(consumerRecord.headers(), "DataOperationEvent");
+ return consumerRecord -> isNotCloudDataOperationEvent(consumerRecord.headers());
}
/**
return headers.lastHeader("ce_type") != null;
}
- private boolean isNotCloudEventOfType(final Headers headers, final String requiredEventType) {
+ private boolean isNotCloudDataOperationEvent(final Headers headers) {
final String eventTypeHeaderValue = KafkaHeaders.getParsedKafkaHeader(headers, "ce_type");
if (eventTypeHeaderValue == null) {
log.trace("No ce_type header found, possibly a legacy event (ignored)");
return EXCLUDE_EVENT;
}
- return !(eventTypeHeaderValue.contains(requiredEventType));
+ return !(eventTypeHeaderValue.contains("DataOperationEvent"));
}
}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2024 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
@Value("${ncmp.policy-executor.defaultDecision:deny}")
private String defaultDecision;
+ @SuppressWarnings("HttpUrlsUsage")
@Value("${ncmp.policy-executor.server.address:http://policy-executor}")
private String serverAddress;
if (!cmHandleIdsPerResponseCodesPerOperation.isEmpty()) {
final CloudEvent dataOperationCloudEvent = DataOperationEventCreator.createDataOperationEvent(clientTopic,
requestId, cmHandleIdsPerResponseCodesPerOperation);
+ @SuppressWarnings("unchecked")
final EventsProducer<CloudEvent> eventsProducer = CpsApplicationContext.getCpsBean(EventsProducer.class);
log.warn("sending error message to client topic: {} ,requestId: {}, data operation cloud event id: {}",
clientTopic, requestId, dataOperationCloudEvent.getId());
final String dataJobId,
final DataJobMetadata dataJobMetadata,
final DataJobReadRequest dataJobReadRequest) {
- log.info("data job id for read operation is: {}", dataJobId);
+ logJobIdAndSize(dataJobId, dataJobReadRequest.data().size());
+ log.info("Destination: {}", dataJobMetadata.destination());
+ log.info("authorization: {}", authorization);
}
@Override
final String dataJobId,
final DataJobMetadata dataJobMetadata,
final DataJobWriteRequest dataJobWriteRequest) {
-
- log.info("Data Job ID: {} - Total operations received: {}", dataJobId, dataJobWriteRequest.data().size());
+ logJobIdAndSize(dataJobId, dataJobWriteRequest.data().size());
logJsonRepresentation("Initiating WRITE operation for Data Job ID: " + dataJobId, dataJobWriteRequest);
final Map<ProducerKey, List<DmiWriteOperation>> dmiWriteOperationsPerProducerKey =
return subJobWriteResponses;
}
+ private void logJobIdAndSize(final String dataJobId, final int numberOfOperations) {
+ log.info("Data Job ID: {} - Total operations received: {}", dataJobId, numberOfOperations);
+ }
+
private void logJsonRepresentation(final String description, final Object object) {
if (log.isDebugEnabled()) {
final String objectAsJsonString = jsonObjectMapper.asJsonString(object);
log.debug("{} (JSON): {}", description, objectAsJsonString);
}
}
+
}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2024-2025 Nordix Foundation
+ * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.
jsonObjectMapper.asJsonString(subJobWriteRequest),
OperationType.CREATE,
authorization);
+ @SuppressWarnings("unchecked")
final Map<String, String> responseAsKeyValuePairs = jsonObjectMapper
.convertToValueType(responseEntity.getBody(), Map.class);
final String subJobId = responseAsKeyValuePairs.get("subJobId");
private static Map<String, String> additionalPropertiesAsMap(
final List<YangModelCmHandle.Property> additionalProperties) {
return additionalProperties.stream().collect(
- Collectors.toMap(YangModelCmHandle.Property::getName, YangModelCmHandle.Property::getValue));
+ Collectors.toMap(YangModelCmHandle.Property::name, YangModelCmHandle.Property::value));
}
}
*/
Collection<DataNode> queryCmHandleAncestorsByCpsPath(String cpsPath, FetchDescendantsOption fetchDescendantsOption);
- /**
- * Method to return data nodes representing the cm handles.
- *
- * @param cpsPath cps path for which the cmHandle is requested
- * @return a list of data nodes representing the cm handles.
- */
- Collection<DataNode> queryNcmpRegistryByCpsPath(String cpsPath, FetchDescendantsOption fetchDescendantsOption);
-
- /**
- * Method to return data nodes representing the cm handles.
- *
- * @param cpsPath cps path for which the cmHandle is requested
- * @param queryResultLimit the maximum number of data nodes to return; if less than 1, returns all matching nodes
- * @return a list of data nodes representing the cm handles.
- */
- Collection<DataNode> queryNcmpRegistryByCpsPath(String cpsPath, FetchDescendantsOption fetchDescendantsOption,
- int queryResultLimit);
-
/**
* Method to check the state of a cm handle with given id.
*
.toList();
}
- @Override
- public Collection<DataNode> queryNcmpRegistryByCpsPath(final String cpsPath,
- final FetchDescendantsOption fetchDescendantsOption) {
- return queryNcmpRegistryByCpsPath(cpsPath, fetchDescendantsOption, NO_LIMIT);
- }
-
- @Override
- public Collection<DataNode> queryNcmpRegistryByCpsPath(final String cpsPath,
- final FetchDescendantsOption fetchDescendantsOption,
- final int queryResultLimit) {
- return cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, cpsPath,
- fetchDescendantsOption, queryResultLimit);
- }
-
@Override
public Collection<DataNode> queryCmHandleAncestorsByCpsPath(final String cpsPath,
final FetchDescendantsOption fetchDescendantsOption) {
return cpsDataService.getDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
xpath, OMIT_DESCENDANTS).iterator().next();
}
+
+ private Collection<DataNode> queryNcmpRegistryByCpsPath(final String cpsPath,
+ final FetchDescendantsOption fetchDescendantsOption) {
+ return cpsQueryService.queryDataNodes(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, cpsPath,
+ fetchDescendantsOption, NO_LIMIT);
+ }
+
}
if (CmHandleState.READY.equals(compositeState.getCmHandleState())) {
final DataStoreSyncState dataStoreSyncState = compositeState.getDataStores()
.getOperationalDataStore().getDataStoreSyncState();
- if (Boolean.FALSE.equals(dataSyncEnabledTargetValue)
- && DataStoreSyncState.SYNCHRONIZED.equals(dataStoreSyncState)) {
+ if (!dataSyncEnabledTargetValue && DataStoreSyncState.SYNCHRONIZED.equals(dataStoreSyncState)) {
// TODO : This is hard-coded for onap dmi that need to be addressed
cpsDataService.deleteDataNode(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleId,
"/netconf-state", OffsetDateTime.now());
Collection<DataNode> getCmHandleDataNodeByCmHandleId(String cmHandleId,
FetchDescendantsOption fetchDescendantsOption);
- /**
- * Get collection of data nodes of given cm handles.
- *
- * @param cmHandleIds collection of cmHandle IDs
- * @param fetchDescendantsOption fetch descendants option
- * @return collection of data nodes
- */
- Collection<DataNode> getCmHandleDataNodes(Collection<String> cmHandleIds,
- FetchDescendantsOption fetchDescendantsOption);
-
/**
* get CM handles that has given module names.
*
@Component
public class InventoryPersistenceImpl extends NcmpPersistenceImpl implements InventoryPersistence {
- private static final int CMHANDLE_BATCH_SIZE = 300;
+ private static final int CM_HANDLE_BATCH_SIZE = 300;
private final CpsModuleService cpsModuleService;
private final CpsValidator cpsValidator;
@Override
public void saveCmHandleBatch(final List<YangModelCmHandle> yangModelCmHandles) {
for (final List<YangModelCmHandle> yangModelCmHandleBatch :
- Lists.partition(yangModelCmHandles, CMHANDLE_BATCH_SIZE)) {
+ Lists.partition(yangModelCmHandles, CM_HANDLE_BATCH_SIZE)) {
final String cmHandlesJsonData = createCmHandlesJsonData(yangModelCmHandleBatch);
cpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
NCMP_DMI_REGISTRY_PARENT, cmHandlesJsonData, NO_TIMESTAMP, ContentType.JSON);
return this.getDataNode(getXPathForCmHandleById(cmHandleId), fetchDescendantsOption);
}
- @Override
- public Collection<DataNode> getCmHandleDataNodes(final Collection<String> cmHandleIds,
- final FetchDescendantsOption fetchDescendantsOption) {
- final Collection<String> xpaths = new ArrayList<>(cmHandleIds.size());
- cmHandleIds.forEach(cmHandleId -> xpaths.add(getXPathForCmHandleById(cmHandleId)));
- return this.getDataNodes(xpaths, fetchDescendantsOption);
- }
-
@Override
public Collection<String> getCmHandleReferencesWithGivenModules(final Collection<String> moduleNamesForQuery,
final boolean outputAlternateId) {
return YangDataConverter.toYangModelCmHandles(getCmHandleDataNodes(validCmHandleIds, fetchDescendantsOption));
}
+ private Collection<DataNode> getCmHandleDataNodes(final Collection<String> cmHandleIds,
+ final FetchDescendantsOption fetchDescendantsOption) {
+ final Collection<String> xpaths = new ArrayList<>(cmHandleIds.size());
+ cmHandleIds.forEach(cmHandleId -> xpaths.add(getXPathForCmHandleById(cmHandleId)));
+ return this.getDataNodes(xpaths, fetchDescendantsOption);
+ }
+
}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2022-2025 Nordix Foundation
+ * Copyright (C) 2022-2025 OpenInfra Foundation Europe. 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.
*/
Collection<DataNode> getDataNode(String xpath, FetchDescendantsOption fetchDescendantsOption);
- /**
- * Get collection of data nodes via xpaths.
- *
- * @param xpaths collection of xpaths
- * @return collection of data nodes
- */
- Collection<DataNode> getDataNodes(Collection<String> xpaths);
-
- /**
- * Get collection of data nodes via xpaths.
- *
- * @param xpaths collection of xpaths
- * @param fetchDescendantsOption fetch descendants option
- * @return collection of data nodes
- */
- Collection<DataNode> getDataNodes(Collection<String> xpaths,
- FetchDescendantsOption fetchDescendantsOption);
-
/**
* Replaces list content by removing all existing elements and inserting the given new elements as data nodes.
*
* @param parentNodeXpath parent node xpath
- * @param dataNodes datanodes representing the updated data
+ * @param dataNodes data nodes representing the updated data
*/
void replaceListContent(String parentNodeXpath, Collection<DataNode> dataNodes);
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2023-2025 Nordix Foundation
+ * Copyright (C) 2023-2025 OpenInfra Foundation Europe. 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.
fetchDescendantsOption);
}
- @Override
- public Collection<DataNode> getDataNodes(final Collection<String> xpaths) {
- return getDataNodes(xpaths, INCLUDE_ALL_DESCENDANTS);
- }
-
- @Override
public Collection<DataNode> getDataNodes(final Collection<String> xpaths,
final FetchDescendantsOption fetchDescendantsOption) {
return cpsDataService.getDataNodesForMultipleXpaths(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, xpaths,
}
private Collection<NcmpServiceCmHandle> getNcmpServiceCmHandleBatch(final Collection<String> cmHandleIds) {
- final Collection<YangModelCmHandle> yangModelcmHandles
+ final Collection<YangModelCmHandle> yangModelCmHandles
= inventoryPersistence.getYangModelCmHandles(cmHandleIds);
- final Collection<NcmpServiceCmHandle> ncmpServiceCmHandles = new ArrayList<>(yangModelcmHandles.size());
+ final Collection<NcmpServiceCmHandle> ncmpServiceCmHandles = new ArrayList<>(yangModelCmHandles.size());
- yangModelcmHandles.forEach(yangModelcmHandle ->
+ yangModelCmHandles.forEach(yangModelcmHandle ->
ncmpServiceCmHandles.add(YangDataConverter.toNcmpServiceCmHandle(yangModelcmHandle))
);
trustLevelManager.applyEffectiveTrustLevels(ncmpServiceCmHandles);
return ncmpServiceCmHandles;
}
+ @SafeVarargs
private Collection<String> executeQueries(final CmHandleQueryServiceParameters cmHandleQueryServiceParameters,
final boolean outputAlternateId,
final BiFunction<CmHandleQueryServiceParameters, Boolean,
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2022-2023 Nordix Foundation
+ * Copyright (C) 2022-2025 OpenInfra Foundation Europe. 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.
package org.onap.cps.ncmp.impl.inventory.models;
+import lombok.Getter;
+
+@Getter
public enum ModelledDmiServiceLeaves {
DMI_SERVICE_NAME("dmi-service-name"),
DMI_DATA_SERVICE_NAME("dmi-data-service-name"),
DMI_MODEL_SERVICE_NAME("dmi-model-service-name");
- private String leafName;
+ private final String leafName;
ModelledDmiServiceLeaves(final String dmiPluginIdentifierKey) {
this.leafName = dmiPluginIdentifierKey;
}
- public String getLeafName() {
- return leafName;
- }
-
}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2021-2024 Nordix Foundation
+ * Copyright (C) 2021-2025 OpenInfra Foundation Europe. 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.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import lombok.AllArgsConstructor;
-import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
return yangModelCmHandleProperties;
}
- @AllArgsConstructor
- @Data
- public static class Property {
-
- @JsonProperty()
- private final String name;
-
- @JsonProperty()
- private final String value;
- }
+ public record Property(@JsonProperty() String name, @JsonProperty() String value) { }
}
/**
* Operations class for DMI Model.
*/
+@SuppressWarnings({"ALL", "rawtypes"})
@RequiredArgsConstructor
@Service
public class DmiModelOperations {
additionalProperties) {
final JsonObject asJsonObject = new JsonObject();
for (final YangModelCmHandle.Property additionalProperty : additionalProperties) {
- asJsonObject.addProperty(additionalProperty.getName(), additionalProperty.getValue());
+ asJsonObject.addProperty(additionalProperty.name(), additionalProperty.value());
}
return asJsonObject;
}
/*
* ============LICENSE_START========================================================
- * Copyright (C) 2022-2025 Nordix Foundation
+ * Copyright (C) 2022-2025 OpenInfra Foundation Europe. 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.
@Configuration
public class SynchronizationCacheConfig extends HazelcastCacheConfig {
- public static final int MODULE_SYNC_STARTED_TTL_SECS = 600;
public static final int DATA_SYNC_SEMAPHORE_TTL_SECS = 1800;
+ private static final int MODULE_SYNC_STARTED_TTL_SECS = 600;
+
private static final QueueConfig commonQueueConfig = createQueueConfig("defaultQueueConfig");
- private static final MapConfig moduleSyncStartedConfig =
- createMapConfigWithTimeToLiveInSeconds("moduleSyncStartedConfig", MODULE_SYNC_STARTED_TTL_SECS);
- private static final MapConfig dataSyncSemaphoresConfig = createMapConfig("dataSyncSemaphoresConfig");
+ private static final MapConfig moduleSyncStartedConfig = createModuleSyncStartedMapConfig();
+ private static final MapConfig dataSyncSemaphoresConfig = createGenericMapConfig("dataSyncSemaphoresConfig");
/**
* Module Sync Distributed Queue Instance.
return getOrCreateHazelcastInstance(dataSyncSemaphoresConfig).getMap("dataSyncSemaphores");
}
+ private static MapConfig createModuleSyncStartedMapConfig() {
+ final MapConfig mapConfig = createGenericMapConfig("moduleSyncStartedConfig");
+ mapConfig.setTimeToLiveSeconds(MODULE_SYNC_STARTED_TTL_SECS);
+ return mapConfig;
+ }
+
}
final String stateMetricKey = cmHandleStateAsString + METRIC_POSTFIX;
final int cmHandleCountForState = cmHandleQueryService.queryCmHandleIdsByState(cmHandleState).size();
cmHandlesByState.putIfAbsent(stateMetricKey, cmHandleCountForState);
- log.info("Cm handle state monitor has set " + stateMetricKey + " to " + cmHandleCountForState);
+ log.info("Cm handle state monitor has set {} to {}", stateMetricKey, cmHandleCountForState);
}
}
}
}
-
-}
\ No newline at end of file
+}
* Sends an LCM event to the dedicated topic with optional notification headers.
* Capture and log KafkaException If an error occurs while sending the event to Kafka
*
- * @param cmHandleId Cm Handle Id associated with the LCM event
+ * @param cmHandleId CM handle id associated with the LCM event
* @param lcmEvent The LCM event object to be sent
* @param lcmEventHeader Optional headers associated with the LCM event
*/
if (notificationsEnabled) {
final Timer.Sample timerSample = Timer.start(meterRegistry);
try {
+ @SuppressWarnings("unchecked")
final Map<String, Object> lcmEventHeadersMap =
jsonObjectMapper.convertToValueType(lcmEventHeader, Map.class);
eventsProducer.sendEvent(topicName, cmHandleId, lcmEventHeadersMap, lcmEvent);
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2023 Nordix Foundation
+ * Copyright (C) 2023-2025 OpenInfra Foundation Europe. 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.
final DeviceTrustLevel deviceTrustLevel =
CloudEventMapper.toTargetEvent(consumerRecord.value(), DeviceTrustLevel.class);
- final String trustLevelAsString = deviceTrustLevel.getData().getTrustLevel();
- trustLevelManager.updateCmHandleTrustLevel(cmHandleId, TrustLevel.valueOf(trustLevelAsString));
+ if (deviceTrustLevel != null) {
+ final String trustLevelAsString = deviceTrustLevel.getData().getTrustLevel();
+ trustLevelManager.updateCmHandleTrustLevel(cmHandleId, TrustLevel.valueOf(trustLevelAsString));
+ }
}
}
/*
* ============LICENSE_START========================================================
- * Copyright (C) 2023-2024 Nordix Foundation
+ * Copyright (C) 2023-2025 OpenInfra Foundation Europe. 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.
package org.onap.cps.ncmp.impl.inventory.trustlevel;
import com.hazelcast.config.MapConfig;
+import com.hazelcast.config.NearCacheConfig;
import com.hazelcast.map.IMap;
import org.onap.cps.ncmp.api.inventory.models.TrustLevel;
import org.onap.cps.ncmp.impl.cache.HazelcastCacheConfig;
public static final String TRUST_LEVEL_PER_CM_HANDLE = "trustLevelPerCmHandle";
private static final MapConfig trustLevelPerCmHandleIdNearCacheConfig =
- createNearCacheMapConfig("trustLevelPerCmHandleCacheConfig");
+ createMapConfigsWithNearCache();
private static final MapConfig trustLevelPerDmiPluginCacheConfig =
- createMapConfig("trustLevelPerDmiPluginCacheConfig");
+ createGenericMapConfig("trustLevelPerDmiPluginCacheConfig");
/**
* Distributed instance of trust level cache containing the trust level per cm handle.
trustLevelPerDmiPluginCacheConfig).getMap(TRUST_LEVEL_PER_DMI_PLUGIN);
}
+ private static MapConfig createMapConfigsWithNearCache() {
+ final MapConfig mapConfig = createGenericMapConfig("trustLevelPerCmHandleCacheConfig");
+ mapConfig.setNearCacheConfig(new NearCacheConfig("trustLevelPerCmHandleCacheConfig"));
+ return mapConfig;
+ }
+
}
final List<YangModelCmHandle.Property> yangModelCmHandleProperties) {
additionalProperties = new LinkedHashMap<>();
for (final YangModelCmHandle.Property additionalProperty : yangModelCmHandleProperties) {
- additionalProperties.put(additionalProperty.getName(), additionalProperty.getValue());
+ additionalProperties.put(additionalProperty.name(), additionalProperty.value());
}
}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2021 Nordix Foundation
+ * Copyright (C) 2021-2025 OpenInfra Foundation Europe. 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.
package org.onap.cps.ncmp.impl.models;
/**
- * Enmm to determine if the required service is for a data or model operation.
+ * Enum to determine if the required service is for a data or model operation.
*/
public enum RequiredDmiService {
DATA, MODEL
}
/**
- * Get cm handle Id from given cmHandleReference.
+ * Get cm handle id from given cmHandleReference.
*
* @param cmHandleReference cm handle or alternate identifier
* @return cm handle id string
public static Map<String, String> toPropertiesMap(final List<YangModelCmHandle.Property> properties) {
final Map<String, String> propertiesMap = new LinkedHashMap<>(properties.size());
for (final YangModelCmHandle.Property property : properties) {
- propertiesMap.put(property.getName(), property.getValue());
+ propertiesMap.put(property.name(), property.value());
}
return propertiesMap;
}
/**
* This method extracts cm handle id from xpath of data node.
* @param xpath for data node of the cm handle
- * @return cm handle Id
+ * @return cm handle id or null if no id can be found
*/
public static String extractCmHandleIdFromXpath(final String xpath) {
final Matcher matcher = cmHandleIdInXpathPattern.matcher(xpath);
- matcher.find();
- return matcher.group(1);
+ return matcher.find() ? matcher.group(1) : null;
}
/**
* Constructs a URL template with variables based on the accumulated path segments and query parameters.
*
- * @param serviceBaseUrl the base URL of the service, e.g., "http://dmi-service.com".
+ * @param serviceBaseUrl the base URL of the service, e.g., "<a href="http://dmi-service.com">...</a>".
* @param basePath the base path of the service
* @return a UrlTemplateParameters instance containing the complete URL template and URL variables
*/
/**
* Constructs a URL for a spring actuator health check based on the given base URL.
*
- * @param serviceBaseUrl the base URL of the service, e.g., "http://dmi-service.com".
+ * @param serviceBaseUrl the base URL of the service, e.g., "<a href="http://dmi-service.com">...</a>".
* @return a {@link UrlTemplateParameters} instance containing the complete URL template and empty URL variables,
* suitable for DMI health check.
*/
revision "2022-05-10" {
description
- "Added data-sync-enabled, sync-state with state, last-sync-time, data-store-sync-state with operational and running syncstate";
+ "Added data-sync-enabled, sync-state with state, last-sync-time, data-store-sync-state with operational and running sync-state";
}
revision "2022-02-10" {
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2022 Bell Canada
- * Modifications Copyright (C) 2023-2025 Nordix Foundation
+ * Modifications Copyright (C) 2023-2025 OpenInfra Foundation Europe.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
def 'Failed cm-handle Registration Response: for unexpected exception'() {
when: 'cm-handle response is created for an unexpected exception'
- def cmHandleRegistrationResponse =
- CmHandleRegistrationResponse.createFailureResponse('cmHandle', new Exception('unexpected error'))
+ def result = CmHandleRegistrationResponse.createFailureResponse('cmHandle', new Exception('unexpected error'))
then: 'the response is created with expected value'
- with(cmHandleRegistrationResponse) {
+ with(result) {
assert it.ncmpResponseStatus == UNKNOWN_ERROR
assert it.cmHandle == 'cmHandle'
assert errorText == 'unexpected error'
def 'Failed cm-handle Registration Response'() {
when: 'cm-handle failure response is created'
- def cmHandleRegistrationResponse =
- CmHandleRegistrationResponse.createFailureResponse('cmHandle', CM_HANDLE_ALREADY_EXIST)
+ def result = CmHandleRegistrationResponse.createFailureResponse('cmHandle', CM_HANDLE_ALREADY_EXIST)
then: 'the response is created with expected value'
- with(cmHandleRegistrationResponse) {
- assert it.ncmpResponseStatus == CM_HANDLE_ALREADY_EXIST
- assert it.cmHandle == 'cmHandle'
- assert it.status == Status.FAILURE
- assert errorText == CM_HANDLE_ALREADY_EXIST.message
- }
+ with(result) {
+ assert it.ncmpResponseStatus == CM_HANDLE_ALREADY_EXIST
+ assert it.cmHandle == 'cmHandle'
+ assert it.status == Status.FAILURE
+ assert errorText == CM_HANDLE_ALREADY_EXIST.message
+ }
}
def 'Failed cm-handle Registration with multiple responses.'() {
when: 'cm-handle failure response is created for 2 xpaths'
- def cmHandleRegistrationResponses =
- CmHandleRegistrationResponse.createFailureResponsesFromXpaths(["somePathWithId[@id='123']", "somePathWithId[@id='456']"], CM_HANDLE_ALREADY_EXIST)
+ def result = CmHandleRegistrationResponse.createFailureResponsesFromXpaths(["somePathWithId[@id='123']", "somePathWithId[@id='456']"], CM_HANDLE_ALREADY_EXIST)
then: 'the response has the correct cm handle ids'
- assert cmHandleRegistrationResponses.size() == 2
- assert cmHandleRegistrationResponses.stream().map(it -> it.cmHandle).collect(Collectors.toList())
- .containsAll(['123','456'])
+ assert result.size() == 2
+ assert result.stream().map(it -> it.cmHandle).collect(Collectors.toList()).containsAll(['123','456'])
}
def 'Failed cm-handle Registration with multiple responses with an unexpected xpath.'() {
when: 'cm-handle failure response is created for one valid and one unexpected xpath'
- def cmHandleRegistrationResponses =
- CmHandleRegistrationResponse.createFailureResponsesFromXpaths(["somePathWithId[@id='123']", "valid/xpath/without-id[@key='123']"], CM_HANDLE_ALREADY_EXIST)
+ def result = CmHandleRegistrationResponse.createFailureResponsesFromXpaths(["somePathWithId[@id='123']", "valid/xpath/without-id[@key='123']"], CM_HANDLE_ALREADY_EXIST)
then: 'the response has only one entry'
- assert cmHandleRegistrationResponses.size() == 1
+ assert result.size() == 1
}
def 'Failed cm-handle registration based on cm handle id and registration error'() {
when: 'the failure response is created with "cm-handle already exists" error code for 1 cm handle'
- def cmHandleRegistrationResponses =
- CmHandleRegistrationResponse.createFailureResponses(['ch 1'], CM_HANDLE_ALREADY_EXIST)
+ def result = CmHandleRegistrationResponse.createFailureResponses(['ch 1'], CM_HANDLE_ALREADY_EXIST)
then: 'the response with expected values'
- assert cmHandleRegistrationResponses[0].cmHandle == 'ch 1'
- assert cmHandleRegistrationResponses[0].status == Status.FAILURE
- assert cmHandleRegistrationResponses[0].ncmpResponseStatus == CM_HANDLE_ALREADY_EXIST
- assert cmHandleRegistrationResponses[0].errorText == 'cm-handle already exists'
+ assert result[0].cmHandle == 'ch 1'
+ assert result[0].status == Status.FAILURE
+ assert result[0].ncmpResponseStatus == CM_HANDLE_ALREADY_EXIST
+ assert result[0].errorText == 'cm-handle already exists'
}
}
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2023-2025 Nordix Foundation
+ * Copyright (C) 2023-2025 OpenInfra Foundation Europe. 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.
package org.onap.cps.ncmp.impl.cache
-
import com.hazelcast.core.Hazelcast
import spock.lang.Specification
}
where: 'the following configs are used'
scenario | config || expectMapConfig | expectQueueConfig | expectSetConfig
- 'Map Config' | HazelcastCacheConfig.createMapConfig('my map config') || true | false | false
+ 'Map Config' | HazelcastCacheConfig.createGenericMapConfig('my map config') || true | false | false
'Queue Config' | HazelcastCacheConfig.createQueueConfig('my queue config') || false | true | false
'Set Config' | HazelcastCacheConfig.createSetConfig('my set config') || false | false | true
}
/*
* ============LICENSE_START=======================================================
- * Copyright (c) 2024 Nordix Foundation.
+ * Copyright (c) 2024-2025 OpenInfra Foundation Europe. 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.
}
- def 'Consume valid CmNotificationSubscriptionNcmpInEvent create message'() {
+ def 'Consume valid CmNotificationSubscriptionNcmpInEvent create message.'() {
given: 'a cmNotificationSubscription event'
def jsonData = TestUtils.getResourceFileContent('cmSubscription/cmNotificationSubscriptionNcmpInEvent.json')
- def testEventSent = jsonObjectMapper.convertJsonString(jsonData, NcmpInEvent.class)
+ def testEventSent = jsonObjectMapper.convertJsonString(jsonData, NcmpInEvent)
def testCloudEventSent = CloudEventBuilder.v1()
.withData(objectMapper.writeValueAsBytes(testEventSent))
.withId('subscriptionCreated')
1 * mockCmSubscriptionHandler.processSubscriptionCreateRequest('test-id',_)
}
- def 'Consume valid CmNotificationSubscriptionNcmpInEvent delete message'() {
+ def 'Consume valid CmNotificationSubscriptionNcmpInEvent delete message.'() {
given: 'a cmNotificationSubscription event'
def jsonData = TestUtils.getResourceFileContent('cmSubscription/cmNotificationSubscriptionNcmpInEvent.json')
- def testEventSent = jsonObjectMapper.convertJsonString(jsonData, NcmpInEvent.class)
+ def testEventSent = jsonObjectMapper.convertJsonString(jsonData, NcmpInEvent)
def testCloudEventSent = CloudEventBuilder.v1()
.withData(objectMapper.writeValueAsBytes(testEventSent))
.withId('sub-id')
1 * mockCmSubscriptionHandler.processSubscriptionDeleteRequest('test-id')
}
+ def 'Attempt to consume unsupported Event.'() {
+ given: 'a unsupported event with a valid supported type'
+ def unsupportedEvent = Mock(CloudEvent)
+ def cloudEventWithUnsupportedEvent = CloudEventBuilder.v1()
+ .withId('some id')
+ .withType('subscriptionCreateRequest') // this is valid but does not match the event object
+ .withSource(URI.create('some-resource'))
+ .withData(objectMapper.writeValueAsBytes(unsupportedEvent)).build()
+ def consumerRecord = new ConsumerRecord<String, CloudEvent>('some topic', 0, 0, 'some key', cloudEventWithUnsupportedEvent)
+ when: 'attempt to consume the unsupported event'
+ objectUnderTest.consumeSubscriptionEvent(consumerRecord)
+ then: 'the subscription handler service is not called at all'
+ 0 * mockCmSubscriptionHandler.processSubscriptionDeleteRequest(*_)
+ 0 * mockCmSubscriptionHandler.processSubscriptionCreateRequest(*_)
+ }
def getLoggingEvent() {
return logger.list[1]
+/*
+ * ============LICENSE_START========================================================
+ * Copyright (C) 2023-2025 OpenInfra Foundation Europe. 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
package org.onap.cps.ncmp.impl.data.async
import org.apache.kafka.common.header.Header
'non-cloud event' | 'other' || false
}
- def 'Excluding cloud event of given type only with #scenario.'() {
+ def 'Excluding cloud event with header #scenario.'() {
given: 'headers contain a header for key: #key and value: #value'
header.value() >> value.getBytes(Charset.defaultCharset())
headers.lastHeader(key) >> header
expect: 'the event would (not) be excluded: #expectedToBeExcluded'
- assert objectUnderTest.isNotCloudEventOfType(headers,'requiredType') == expectedToBeExcluded
+ assert objectUnderTest.isNotCloudDataOperationEvent(headers) == expectedToBeExcluded
where: 'the following headers are defined'
- scenario | key | value || expectedToBeExcluded
- 'required type' | 'ce_type' | 'requiredType' || false
- 'contains requiredType' | 'ce_type' | 'Contains requiredType and more' || false
- 'other type' | 'ce_type' | 'other' || true
- 'no ce_type header' | 'other' | 'irrelevant' || true
+ scenario | key | value || expectedToBeExcluded
+ 'DataOperationEvent' | 'ce_type' | 'DataOperationEvent' || false
+ 'contains DataOperationEvent' | 'ce_type' | 'Contains DataOperationEvent and more' || false
+ 'other type' | 'ce_type' | 'other' || true
+ 'no ce_type header' | 'other' | 'irrelevant' || true
}
}
then: 'the data job id is correctly logged'
def loggingEvent = logger.list[0]
assert loggingEvent.level == Level.INFO
- assert loggingEvent.formattedMessage.contains('data job id for read operation is: my-job-id')
+ assert loggingEvent.formattedMessage.contains('Data Job ID: my-job-id')
}
def 'Write data-job request and verify logging when info enabled.'() {
/*
* ============LICENSE_START=======================================================
- * Copyright (C) 2023 Nordix Foundation
+ * Copyright (C) 2023-2025 OpenInfra Foundation Europe. 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.
DuplicatedYangResourceException duplicatedYangResourceException = null;
final Throwable cause = originalException.getCause();
- if (cause instanceof ConstraintViolationException) {
- final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
+ if (cause instanceof final ConstraintViolationException constraintException) {
if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
// Db constraint related to yang resource checksum uniqueness is not respected
final String checksumInError = getDuplicatedChecksumFromException(constraintException);
private final Sleeper sleeper;
private static final Pattern ERROR_CODE_PATTERN = Pattern.compile("(\\d{3})");
private int decisionCounter = 0;
+ // Do NOT change below to final as it needs to be set during test
private static int slowResponseTimeInSeconds = 40;
@Override