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.NonNull;
28 import lombok.RequiredArgsConstructor;
29 import lombok.extern.slf4j.Slf4j;
30 import org.onap.cps.api.CpsAdminService;
31 import org.onap.cps.api.CpsDataService;
32 import org.onap.cps.api.CpsModuleService;
33 import org.onap.cps.ncmp.api.impl.exception.NcmpStartUpException;
34 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
35 import org.springframework.beans.factory.annotation.Value;
36 import org.springframework.boot.SpringApplication;
37 import org.springframework.boot.context.event.ApplicationReadyEvent;
38 import org.springframework.stereotype.Component;
39
40 @Slf4j
41 @Component
42 @RequiredArgsConstructor
43 public class SubscriptionModelLoader implements ModelLoader {
44
45     private final CpsAdminService cpsAdminService;
46     private final CpsModuleService cpsModuleService;
47     private final CpsDataService cpsDataService;
48     private static final String SUBSCRIPTION_DATASPACE_NAME = "NCMP-Admin";
49     private static final String SUBSCRIPTION_ANCHOR_NAME = "AVC-Subscriptions";
50     private static final String SUBSCRIPTION_SCHEMASET_NAME = "subscriptions";
51     private static final String SUBSCRIPTION_REGISTRY_DATANODE_NAME = "subscription-registry";
52
53     @Value("${ncmp.model-loader.subscription:false}")
54     private boolean subscriptionModelLoaderEnabled;
55
56     /**
57      * Method calls boarding subscription model when Application is ready.
58      *
59      * @param applicationReadyEvent the event to respond to
60      */
61     @Override
62     public void onApplicationEvent(@NonNull final ApplicationReadyEvent applicationReadyEvent) {
63         try {
64             if (subscriptionModelLoaderEnabled) {
65                 onboardSubscriptionModel();
66             } else {
67                 log.info("Subscription Model Loader is disabled");
68             }
69         } catch (final NcmpStartUpException ncmpStartUpException) {
70             log.debug("Onboarding model for NCMP failed: {} ", ncmpStartUpException.getMessage());
71             SpringApplication.exit(applicationReadyEvent.getApplicationContext(), () -> 1);
72         }
73     }
74
75     /**
76      * Method to onboard subscription model for NCMP.
77      */
78     private void onboardSubscriptionModel() {
79         final Map<String, String> yangResourceContentMap = createYangResourceToContentMap();
80         if (!yangResourceContentMap.get("subscription.yang").isEmpty()) {
81             createSchemaSet(SUBSCRIPTION_DATASPACE_NAME, SUBSCRIPTION_SCHEMASET_NAME, yangResourceContentMap);
82             createAnchor(SUBSCRIPTION_DATASPACE_NAME, SUBSCRIPTION_SCHEMASET_NAME, SUBSCRIPTION_ANCHOR_NAME);
83             createTopLevelDataNode(SUBSCRIPTION_DATASPACE_NAME, SUBSCRIPTION_ANCHOR_NAME,
84                 SUBSCRIPTION_REGISTRY_DATANODE_NAME);
85         }
86     }
87
88
89     @Override
90     public boolean createSchemaSet(final String dataspaceName,
91                                 final String schemaSetName,
92                                 final Map<String, String> yangResourceContentMap) {
93         try {
94             cpsModuleService.createSchemaSet(dataspaceName, schemaSetName, yangResourceContentMap);
95         } catch (final AlreadyDefinedException exception) {
96             log.info("Creating new schema set failed as schema set already exists");
97         } catch (final Exception exception) {
98             log.debug("Creating schema set for subscription model failed: {} ", exception.getMessage());
99             throw new NcmpStartUpException("Creating schema set failed", exception.getMessage());
100         }
101         return true;
102     }
103
104     /**
105      * Create Anchor.
106      *
107      * @param dataspaceName dataspace name
108      * @param schemaSetName schema set name
109      * @param anchorName anchor name
110      */
111     @Override
112     public boolean createAnchor(final String dataspaceName, final String schemaSetName,
113                              final String anchorName) {
114         try {
115             cpsAdminService.createAnchor(dataspaceName, schemaSetName, anchorName);
116         } catch (final AlreadyDefinedException exception) {
117             log.info("Creating new anchor failed as anchor already exists");
118         } catch (final Exception exception) {
119             log.debug("Creating anchor for subscription model failed: {} ", exception.getMessage());
120             throw new NcmpStartUpException("Creating anchor failed", exception.getMessage());
121         }
122         return true;
123     }
124
125     private void createTopLevelDataNode(final String dataspaceName,
126                                         final String anchorName,
127                                         final String dataNodeName) {
128         final String nodeData = "{\"" + dataNodeName + "\":{}}";
129         try {
130             cpsDataService.saveData(dataspaceName, anchorName, nodeData, OffsetDateTime.now());
131         } catch (final AlreadyDefinedException exception) {
132             log.info("Creating new data node {} failed as data node already exists", dataNodeName);
133         } catch (final Exception exception) {
134             log.debug("Creating data node for subscription model failed: {}", exception.getMessage());
135             throw new NcmpStartUpException("Creating data node failed", exception.getMessage());
136         }
137     }
138
139     private String getFileContentAsString() {
140         try (InputStream inputStream = getClass().getClassLoader()
141                 .getResourceAsStream("model/subscription.yang")) {
142             return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
143         } catch (final Exception exception) {
144             log.debug("Onboarding failed as unable to read file: {}", exception.getCause().toString());
145             throw new NcmpStartUpException("Onboarding failed as unable to read file: {}", exception.getMessage());
146         }
147     }
148
149     private Map<String, String> createYangResourceToContentMap() {
150         return Map.of("subscription.yang", getFileContentAsString());
151     }
152 }