a4eb2ae722b3f397964419b794f8df0937890ec0
[ccsdk/cds.git] /
1 /*\r
2  * Copyright © 2017-2018 AT&T Intellectual Property.\r
3  * Modifications Copyright © 2018 IBM.\r
4  *\r
5  * Licensed under the Apache License, Version 2.0 (the "License");\r
6  * you may not use this file except in compliance with the License.\r
7  * You may obtain a copy of the License at\r
8  *\r
9  *     http://www.apache.org/licenses/LICENSE-2.0\r
10  *\r
11  * Unless required by applicable law or agreed to in writing, software\r
12  * distributed under the License is distributed on an "AS IS" BASIS,\r
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
14  * See the License for the specific language governing permissions and\r
15  * limitations under the License.\r
16  */\r
17 \r
18 package org.onap.ccsdk.apps.controllerblueprints.service;\r
19 \r
20 import com.google.common.base.Preconditions;\r
21 import org.apache.commons.collections.CollectionUtils;\r
22 import org.apache.commons.io.IOUtils;\r
23 import org.apache.commons.lang3.StringUtils;\r
24 import org.apache.commons.lang3.text.StrBuilder;\r
25 import org.jetbrains.annotations.NotNull;\r
26 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants;\r
27 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException;\r
28 import org.onap.ccsdk.apps.controllerblueprints.core.data.ArtifactType;\r
29 import org.onap.ccsdk.apps.controllerblueprints.core.data.DataType;\r
30 import org.onap.ccsdk.apps.controllerblueprints.core.data.NodeType;\r
31 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils;\r
32 import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDefinition;\r
33 import org.onap.ccsdk.apps.controllerblueprints.service.domain.ConfigModel;\r
34 import org.onap.ccsdk.apps.controllerblueprints.service.domain.ModelType;\r
35 import org.onap.ccsdk.apps.controllerblueprints.service.domain.ResourceDictionary;\r
36 import org.onap.ccsdk.apps.controllerblueprints.service.utils.ConfigModelUtils;\r
37 import com.att.eelf.configuration.EELFLogger;\r
38 import com.att.eelf.configuration.EELFManager;\r
39 import org.springframework.beans.factory.annotation.Autowired;\r
40 import org.springframework.beans.factory.annotation.Value;\r
41 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;\r
42 import org.springframework.boot.context.event.ApplicationReadyEvent;\r
43 import org.springframework.context.event.EventListener;\r
44 import org.springframework.core.io.Resource;\r
45 import org.springframework.core.io.support.ResourcePatternResolver;\r
46 import org.springframework.stereotype.Component;\r
47 import java.io.IOException;\r
48 import java.nio.charset.Charset;\r
49 import java.util.List;\r
50 \r
51 /**\r
52  * DataBaseInitService.java Purpose: Provide DataBaseInitService Service\r
53  *\r
54  * @author Brinda Santh\r
55  * @version 1.0\r
56  */\r
57 \r
58 @Component\r
59 @ConditionalOnProperty(name = "blueprints.load.initial-data", havingValue = "true")\r
60 public class DataBaseInitService {\r
61 \r
62     private static EELFLogger log = EELFManager.getInstance().getLogger(DataBaseInitService.class);\r
63     private ModelTypeService modelTypeService;\r
64     private ResourceDictionaryService resourceDictionaryService;\r
65     private ConfigModelService configModelService;\r
66 \r
67     @Value("${load.dataTypePath}")\r
68     private String dataTypePath;\r
69     @Value("${load.nodeTypePath}")\r
70     private String nodeTypePath;\r
71     @Value("${load.artifactTypePath}")\r
72     private String artifactTypePath;\r
73     @Value("${load.resourceDictionaryPath}")\r
74     private String resourceDictionaryPath;\r
75     @Value("${load.blueprintsPath}")\r
76     private String bluePrintsPath;\r
77 \r
78     @Autowired\r
79     private ResourcePatternResolver resourceLoader;\r
80 \r
81     /**\r
82      * This is a DataBaseInitService, used to load the initial data\r
83      *\r
84      * @param modelTypeService modelTypeService\r
85      * @param resourceDictionaryService resourceDictionaryService\r
86      * @param configModelService configModelService\r
87      */\r
88     public DataBaseInitService(ModelTypeService modelTypeService, ResourceDictionaryService resourceDictionaryService,\r
89                                ConfigModelService configModelService) {\r
90         this.modelTypeService = modelTypeService;\r
91         this.resourceDictionaryService = resourceDictionaryService;\r
92         this.configModelService = configModelService;\r
93         log.info("DataBaseInitService started...");\r
94 \r
95     }\r
96 \r
97     @SuppressWarnings("unused")\r
98     @EventListener(ApplicationReadyEvent.class)\r
99     private void initDatabase() {\r
100         log.info("loading dataTypePath from DIR : {}", dataTypePath);\r
101         log.info("loading nodeTypePath from DIR : {}", nodeTypePath);\r
102         log.info("loading artifactTypePath from DIR : {}", artifactTypePath);\r
103         log.info("loading resourceDictionaryPath from DIR : {}", resourceDictionaryPath);\r
104         log.info("loading bluePrintsPath from DIR : {}", bluePrintsPath);\r
105 \r
106         loadModelType();\r
107         loadResourceDictionary();\r
108         // TODO("Enable after Multi file Service Template Repository implementation in place")\r
109         //loadBlueprints();\r
110     }\r
111 \r
112     private void loadModelType() {\r
113         log.info(" *************************** loadModelType **********************");\r
114         try {\r
115             Resource[] dataTypefiles = getPathResources(dataTypePath, ".json");\r
116             StrBuilder errorBuilder = new StrBuilder();\r
117                 for (Resource file : dataTypefiles) {\r
118                     if (file != null) {\r
119                         loadDataType(file, errorBuilder);\r
120                     }\r
121                 }\r
122 \r
123             Resource[] nodeTypefiles = getPathResources(nodeTypePath, ".json");\r
124                        for (Resource file : nodeTypefiles) {\r
125                     if (file != null) {\r
126                         loadNodeType(file, errorBuilder);\r
127                     }\r
128                 }\r
129 \r
130 \r
131             Resource[] artifactTypefiles = getPathResources(artifactTypePath, ".json");\r
132 \r
133                 for (Resource file : artifactTypefiles) {\r
134                     if (file != null) {\r
135                         loadArtifactType(file, errorBuilder);\r
136                     }\r
137                 }\r
138 \r
139 \r
140             if (!errorBuilder.isEmpty()) {\r
141                 log.error(errorBuilder.toString());\r
142             }\r
143         } catch (Exception e) {\r
144             log.error("Failed in Data type loading", e);\r
145         }\r
146     }\r
147 \r
148     private void loadResourceDictionary() {\r
149         log.info(\r
150                 " *************************** loadResourceDictionary **********************");\r
151         try {\r
152             Resource[] dataTypefiles = getPathResources(resourceDictionaryPath, ".json");\r
153 \r
154                 StrBuilder errorBuilder = new StrBuilder();\r
155                 String fileName;\r
156                 for (Resource file : dataTypefiles) {\r
157                     try {\r
158                         fileName = file.getFilename();\r
159                         log.trace("Loading : {}", fileName);\r
160                         String definitionContent = getResourceContent(file);\r
161                         ResourceDefinition resourceDefinition =\r
162                                 JacksonUtils.readValue(definitionContent, ResourceDefinition.class);\r
163                         if (resourceDefinition != null) {\r
164                             Preconditions.checkNotNull(resourceDefinition.getProperty(), "Failed to get Property Definition");\r
165                             ResourceDictionary resourceDictionary = new ResourceDictionary();\r
166                             resourceDictionary.setName(resourceDefinition.getName());\r
167                             resourceDictionary.setDefinition(resourceDefinition);\r
168 \r
169                             Preconditions.checkNotNull(resourceDefinition.getProperty(), "Property field is missing");\r
170                             resourceDictionary.setDescription(resourceDefinition.getProperty().getDescription());\r
171                             resourceDictionary.setDataType(resourceDefinition.getProperty().getType());\r
172                             if(resourceDefinition.getProperty().getEntrySchema() != null){\r
173                                 resourceDictionary.setEntrySchema(resourceDefinition.getProperty().getEntrySchema().getType());\r
174                             }\r
175                             resourceDictionary.setUpdatedBy(resourceDefinition.getUpdatedBy());\r
176                             if (StringUtils.isBlank(resourceDefinition.getTags())) {\r
177                                 resourceDictionary.setTags(\r
178                                         resourceDefinition.getName() + ", " + resourceDefinition.getUpdatedBy()\r
179                                                 + ", " + resourceDefinition.getUpdatedBy());\r
180 \r
181                             } else {\r
182                                 resourceDictionary.setTags(resourceDefinition.getTags());\r
183                             }\r
184                             resourceDictionaryService.saveResourceDictionary(resourceDictionary);\r
185 \r
186                             log.trace(" Loaded successfully : {}", file.getFilename());\r
187                         } else {\r
188                             throw new BluePrintException("couldn't get dictionary from content information");\r
189                         }\r
190                     } catch (Exception e) {\r
191                         errorBuilder.appendln("Dictionary loading Errors : " + file.getFilename() + ":" + e.getMessage());\r
192                     }\r
193                 }\r
194                 if (!errorBuilder.isEmpty()) {\r
195                     log.error(errorBuilder.toString());\r
196                 }\r
197 \r
198 \r
199         } catch (Exception e) {\r
200             log.error(\r
201                     "Failed in Resource dictionary loading", e);\r
202         }\r
203     }\r
204 \r
205     private void loadBlueprints() {\r
206         log.info("*************************** loadServiceTemplate **********************");\r
207         try {\r
208             List<String> serviceTemplateDirs = ConfigModelUtils.getBlueprintNames(bluePrintsPath);\r
209             if (CollectionUtils.isNotEmpty(serviceTemplateDirs)) {\r
210                 StrBuilder errorBuilder = new StrBuilder();\r
211                 for (String fileName : serviceTemplateDirs) {\r
212                     try {\r
213                         String bluePrintPath = this.bluePrintsPath.concat("/").concat(fileName);\r
214                         log.debug("***** Loading service template :  {}", bluePrintPath);\r
215                         ConfigModel configModel = ConfigModelUtils.getConfigModel(bluePrintPath);\r
216 \r
217                         configModel = this.configModelService.saveConfigModel(configModel);\r
218 \r
219                         log.info("Publishing : {}", configModel.getId());\r
220 \r
221                         this.configModelService.publishConfigModel(configModel.getId());\r
222 \r
223                         log.info("Loaded service template successfully: {}", fileName);\r
224 \r
225                     } catch (Exception e) {\r
226                         errorBuilder.appendln("load config model " + fileName + " error : " + e.getMessage());\r
227                     }\r
228                 }\r
229 \r
230                 if (!errorBuilder.isEmpty()) {\r
231                     log.error(errorBuilder.toString());\r
232                 }\r
233             }\r
234         } catch (Exception e) {\r
235             log.error("Failed in Service Template loading", e);\r
236         }\r
237     }\r
238 \r
239     private void loadNodeType(Resource file, StrBuilder errorBuilder) {\r
240         try {\r
241             log.trace("Loading Node Type : {}", file.getFilename());\r
242             String nodeKey = file.getFilename().replace(".json", "");\r
243             String definitionContent = getResourceContent(file);\r
244             NodeType nodeType = JacksonUtils.readValue(definitionContent, NodeType.class);\r
245             Preconditions.checkNotNull(nodeType, String.format("failed to get node type from file : %s", file.getFilename()));\r
246             ModelType modelType = new ModelType();\r
247             modelType.setDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE);\r
248             modelType.setDerivedFrom(nodeType.getDerivedFrom());\r
249             modelType.setDescription(nodeType.getDescription());\r
250             modelType.setDefinition(JacksonUtils.jsonNode(definitionContent));\r
251             modelType.setModelName(nodeKey);\r
252             modelType.setVersion(nodeType.getVersion());\r
253             modelType.setUpdatedBy("System");\r
254             modelType.setTags(nodeKey + "," + BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE + ","\r
255                     + nodeType.getDerivedFrom());\r
256             modelTypeService.saveModel(modelType);\r
257             log.trace("Loaded Node Type successfully : {}", file.getFilename());\r
258         } catch (Exception e) {\r
259             errorBuilder.appendln("Node type loading error : " + file.getFilename() + ":" + e.getMessage());\r
260         }\r
261     }\r
262 \r
263     private void loadDataType(@NotNull Resource file, StrBuilder errorBuilder) {\r
264         try {\r
265             log.trace("Loading Data Type: {}", file.getFilename());\r
266             String dataKey = file.getFilename().replace(".json", "");\r
267             String definitionContent = getResourceContent(file);\r
268             DataType dataType = JacksonUtils.readValue(definitionContent, DataType.class);\r
269             Preconditions.checkNotNull(dataType, String.format("failed to get data type from file : %s", file.getFilename()));\r
270             ModelType modelType = new ModelType();\r
271             modelType.setDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE);\r
272             modelType.setDerivedFrom(dataType.getDerivedFrom());\r
273             modelType.setDescription(dataType.getDescription());\r
274             modelType.setDefinition(JacksonUtils.jsonNode(definitionContent));\r
275             modelType.setModelName(dataKey);\r
276             modelType.setVersion(dataType.getVersion());\r
277             modelType.setUpdatedBy("System");\r
278             modelType.setTags(dataKey + "," + dataType.getDerivedFrom() + ","\r
279                     + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE);\r
280             modelTypeService.saveModel(modelType);\r
281             log.trace(" Loaded Data Type successfully : {}", file.getFilename());\r
282         } catch (Exception e) {\r
283             errorBuilder.appendln("Data type loading error : " + file.getFilename() + ":" + e.getMessage());\r
284         }\r
285     }\r
286 \r
287     private void loadArtifactType(Resource file, StrBuilder errorBuilder) {\r
288         try {\r
289             log.trace("Loading Artifact Type: {}", file.getFilename());\r
290             String dataKey = file.getFilename().replace(".json", "");\r
291             String definitionContent = getResourceContent(file);\r
292             ArtifactType artifactType = JacksonUtils.readValue(definitionContent, ArtifactType.class);\r
293             Preconditions.checkNotNull(artifactType, String.format("failed to get artifact type from file : %s", file.getFilename()));\r
294             ModelType modelType = new ModelType();\r
295             modelType.setDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE);\r
296             modelType.setDerivedFrom(artifactType.getDerivedFrom());\r
297             modelType.setDescription(artifactType.getDescription());\r
298             modelType.setDefinition(JacksonUtils.jsonNode(definitionContent));\r
299             modelType.setModelName(dataKey);\r
300             modelType.setVersion(artifactType.getVersion());\r
301             modelType.setUpdatedBy("System");\r
302             modelType.setTags(dataKey + "," + artifactType.getDerivedFrom() + ","\r
303                     + BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE);\r
304             modelTypeService.saveModel(modelType);\r
305             log.trace("Loaded Artifact Type successfully : {}", file.getFilename());\r
306         } catch (Exception e) {\r
307             errorBuilder.appendln("Artifact type loading error : " + file.getFilename() + ":" + e.getMessage());\r
308         }\r
309     }\r
310 \r
311     private Resource[] getPathResources(String path, String extension) throws IOException {\r
312         return resourceLoader.getResources("file:" + path + "/*" + extension);\r
313     }\r
314 \r
315     private String getResourceContent(Resource resource) throws IOException {\r
316         return IOUtils.toString(resource.getInputStream(), Charset.defaultCharset());\r
317     }\r
318 \r
319 }\r