Merge "Update performance test timings"
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / init / SubscriptionModelLoader.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2023 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.init;
22
23 import java.io.InputStream;
24 import java.nio.charset.StandardCharsets;
25 import java.time.OffsetDateTime;
26 import java.util.Map;
27 import lombok.RequiredArgsConstructor;
28 import lombok.extern.slf4j.Slf4j;
29 import org.onap.cps.api.CpsAdminService;
30 import org.onap.cps.api.CpsDataService;
31 import org.onap.cps.api.CpsModuleService;
32 import org.onap.cps.ncmp.api.impl.exception.NcmpStartUpException;
33 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
34 import org.springframework.beans.factory.annotation.Value;
35 import org.springframework.boot.SpringApplication;
36 import org.springframework.boot.context.event.ApplicationReadyEvent;
37 import org.springframework.stereotype.Component;
38
39 @Slf4j
40 @Component
41 @RequiredArgsConstructor
42 public class SubscriptionModelLoader implements ModelLoader {
43
44     private final CpsAdminService cpsAdminService;
45     private final CpsModuleService cpsModuleService;
46     private final CpsDataService cpsDataService;
47     private static final String SUBSCRIPTION_MODEL_FILENAME = "subscription.yang";
48     private static final String SUBSCRIPTION_MODEL_RESOURCE_PATH = "model/" + SUBSCRIPTION_MODEL_FILENAME;
49     private static final String SUBSCRIPTION_DATASPACE_NAME = "NCMP-Admin";
50     private static final String SUBSCRIPTION_ANCHOR_NAME = "AVC-Subscriptions";
51     private static final String SUBSCRIPTION_SCHEMASET_NAME = "subscriptions";
52     private static final String SUBSCRIPTION_REGISTRY_DATANODE_NAME = "subscription-registry";
53
54     @Value("${ncmp.model-loader.subscription:false}")
55     private boolean subscriptionModelLoaderEnabled;
56
57     /**
58      * Method calls boarding subscription model when Application is ready.
59      *
60      * @param applicationReadyEvent the event to respond to
61      */
62     @Override
63     public void onApplicationEvent(final ApplicationReadyEvent applicationReadyEvent) {
64         try {
65             if (subscriptionModelLoaderEnabled) {
66                 onboardSubscriptionModel(createYangResourceToContentMap());
67             } else {
68                 log.info("Subscription Model Loader is disabled");
69             }
70         } catch (final NcmpStartUpException ncmpStartUpException) {
71             log.debug("Onboarding model for NCMP failed: {} ", ncmpStartUpException.getMessage());
72             SpringApplication.exit(applicationReadyEvent.getApplicationContext(), () -> 1);
73         }
74     }
75
76     /**
77      * Method to onboard subscription model for NCMP.
78      */
79     private void onboardSubscriptionModel(final Map<String, String> yangResourceContentMap) {
80         createSchemaSet(SUBSCRIPTION_DATASPACE_NAME, SUBSCRIPTION_SCHEMASET_NAME, yangResourceContentMap);
81         createAnchor(SUBSCRIPTION_DATASPACE_NAME, SUBSCRIPTION_SCHEMASET_NAME, SUBSCRIPTION_ANCHOR_NAME);
82         createTopLevelDataNode(SUBSCRIPTION_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME,
83             SUBSCRIPTION_REGISTRY_DATANODE_NAME);
84     }
85
86
87     @Override
88     public boolean createSchemaSet(final String dataspaceName,
89                                    final String schemaSetName,
90                                    final Map<String, String> yangResourceContentMap) {
91         try {
92             cpsModuleService.createSchemaSet(dataspaceName, schemaSetName, yangResourceContentMap);
93         } catch (final AlreadyDefinedException exception) {
94             log.info("Creating new schema set failed as schema set already exists");
95         } catch (final Exception exception) {
96             log.debug("Creating schema set for subscription model failed: {} ", exception.getMessage());
97             throw new NcmpStartUpException("Creating schema set failed", exception.getMessage());
98         }
99         return true;
100     }
101
102     /**
103      * Create Anchor.
104      *
105      * @param dataspaceName dataspace name
106      * @param schemaSetName schema set name
107      * @param anchorName anchor name
108      */
109     @Override
110     public boolean createAnchor(final String dataspaceName, final String schemaSetName,
111                              final String anchorName) {
112         try {
113             cpsAdminService.createAnchor(dataspaceName, schemaSetName, anchorName);
114         } catch (final AlreadyDefinedException exception) {
115             log.info("Creating new anchor failed as anchor already exists");
116         } catch (final Exception exception) {
117             log.debug("Creating anchor for subscription model failed: {} ", exception.getMessage());
118             throw new NcmpStartUpException("Creating anchor failed", exception.getMessage());
119         }
120         return true;
121     }
122
123     private void createTopLevelDataNode(final String dataspaceName,
124                                         final String anchorName,
125                                         final String dataNodeName) {
126         final String nodeData = "{\"" + dataNodeName + "\":{}}";
127         try {
128             cpsDataService.saveData(dataspaceName, anchorName, nodeData, OffsetDateTime.now());
129         } catch (final AlreadyDefinedException exception) {
130             log.info("Creating new data node '{}' failed as data node already exists", dataNodeName);
131         } catch (final Exception exception) {
132             log.debug("Creating data node for subscription model failed: {}", exception.getMessage());
133             throw new NcmpStartUpException("Creating data node failed", exception.getMessage());
134         }
135     }
136
137     private String getFileContentAsString(final String fileName) {
138         try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName)) {
139             return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
140         } catch (final Exception exception) {
141             final String message = String.format("Onboarding failed as unable to read file: %s", fileName);
142             log.debug(message);
143             throw new NcmpStartUpException(message, exception.getMessage());
144         }
145     }
146
147     private Map<String, String> createYangResourceToContentMap() {
148         return Map.of(SUBSCRIPTION_MODEL_FILENAME, getFileContentAsString(SUBSCRIPTION_MODEL_RESOURCE_PATH));
149     }
150 }