a1a9b9ca6f48ad40fb5690a36e91163e39cfc09a
[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     private String updateBySystem = "System";\r
67 \r
68     @Value("${load.dataTypePath}")\r
69     private String dataTypePath;\r
70     @Value("${load.nodeTypePath}")\r
71     private String nodeTypePath;\r
72     @Value("${load.artifactTypePath}")\r
73     private String artifactTypePath;\r
74     @Value("${load.resourceDictionaryPath}")\r
75     private String resourceDictionaryPath;\r
76     @Value("${load.blueprintsPath}")\r
77     private String bluePrintsPath;\r
78 \r
79     @Autowired\r
80     private ResourcePatternResolver resourceLoader;\r
81 \r
82     /**\r
83      * This is a DataBaseInitService, used to load the initial data\r
84      *\r
85      * @param modelTypeService modelTypeService\r
86      * @param resourceDictionaryService resourceDictionaryService\r
87      * @param configModelService configModelService\r
88      */\r
89     public DataBaseInitService(ModelTypeService modelTypeService, ResourceDictionaryService resourceDictionaryService,\r
90                                ConfigModelService configModelService) {\r
91         this.modelTypeService = modelTypeService;\r
92         this.resourceDictionaryService = resourceDictionaryService;\r
93         this.configModelService = configModelService;\r
94         log.info("DataBaseInitService started...");\r
95 \r
96     }\r
97 \r
98     @SuppressWarnings("unused")\r
99     @EventListener(ApplicationReadyEvent.class)\r
100     private void initDatabase() {\r
101         log.info("loading dataTypePath from DIR : {}", dataTypePath);\r
102         log.info("loading nodeTypePath from DIR : {}", nodeTypePath);\r
103         log.info("loading artifactTypePath from DIR : {}", artifactTypePath);\r
104         log.info("loading resourceDictionaryPath from DIR : {}", resourceDictionaryPath);\r
105         log.info("loading bluePrintsPath from DIR : {}", bluePrintsPath);\r
106 \r
107         loadModelType();\r
108         loadResourceDictionary();\r
109     }\r
110 \r
111     private void loadModelType() {\r
112         log.info(" *************************** loadModelType **********************");\r
113         try {\r
114             Resource[] dataTypefiles = getPathResources(dataTypePath, ".json");\r
115             StrBuilder errorBuilder = new StrBuilder();\r
116                 for (Resource file : dataTypefiles) {\r
117                     if (file != null) {\r
118                         loadDataType(file, errorBuilder);\r
119                     }\r
120                 }\r
121 \r
122             Resource[] nodeTypefiles = getPathResources(nodeTypePath, ".json");\r
123                        for (Resource file : nodeTypefiles) {\r
124                     if (file != null) {\r
125                         loadNodeType(file, errorBuilder);\r
126                     }\r
127                 }\r
128 \r
129 \r
130             Resource[] artifactTypefiles = getPathResources(artifactTypePath, ".json");\r
131 \r
132                 for (Resource file : artifactTypefiles) {\r
133                     if (file != null) {\r
134                         loadArtifactType(file, errorBuilder);\r
135                     }\r
136                 }\r
137 \r
138 \r
139             if (!errorBuilder.isEmpty()) {\r
140                 log.error(errorBuilder.toString());\r
141             }\r
142         } catch (Exception e) {\r
143             log.error("Failed in Data type loading", e);\r
144         }\r
145     }\r
146 \r
147     private void loadResourceDictionary() {\r
148         log.info(\r
149                 " *************************** loadResourceDictionary **********************");\r
150         try {\r
151             Resource[] dataTypefiles = getPathResources(resourceDictionaryPath, ".json");\r
152 \r
153                 StrBuilder errorBuilder = new StrBuilder();\r
154                 String fileName;\r
155                 for (Resource file : dataTypefiles) {\r
156                     try {\r
157                         fileName = file.getFilename();\r
158                         log.trace("Loading : {}", fileName);\r
159                         String definitionContent = getResourceContent(file);\r
160                         ResourceDefinition resourceDefinition =\r
161                                 JacksonUtils.readValue(definitionContent, ResourceDefinition.class);\r
162                         if (resourceDefinition != null) {\r
163                             Preconditions.checkNotNull(resourceDefinition.getProperty(), "Failed to get Property Definition");\r
164                             ResourceDictionary resourceDictionary = new ResourceDictionary();\r
165                             resourceDictionary.setName(resourceDefinition.getName());\r
166                             resourceDictionary.setDefinition(resourceDefinition);\r
167 \r
168                             Preconditions.checkNotNull(resourceDefinition.getProperty(), "Property field is missing");\r
169                             resourceDictionary.setDescription(resourceDefinition.getProperty().getDescription());\r
170                             resourceDictionary.setDataType(resourceDefinition.getProperty().getType());\r
171                             if(resourceDefinition.getProperty().getEntrySchema() != null){\r
172                                 resourceDictionary.setEntrySchema(resourceDefinition.getProperty().getEntrySchema().getType());\r
173                             }\r
174                             resourceDictionary.setUpdatedBy(resourceDefinition.getUpdatedBy());\r
175                             if (StringUtils.isBlank(resourceDefinition.getTags())) {\r
176                                 resourceDictionary.setTags(\r
177                                         resourceDefinition.getName() + ", " + resourceDefinition.getUpdatedBy()\r
178                                                 + ", " + resourceDefinition.getUpdatedBy());\r
179 \r
180                             } else {\r
181                                 resourceDictionary.setTags(resourceDefinition.getTags());\r
182                             }\r
183                             resourceDictionaryService.saveResourceDictionary(resourceDictionary);\r
184 \r
185                             log.trace(" Loaded successfully : {}", file.getFilename());\r
186                         } else {\r
187                             throw new BluePrintException("couldn't get dictionary from content information");\r
188                         }\r
189                     } catch (Exception e) {\r
190                         log.error("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                         log.error("Exception", e);\r
227                         errorBuilder.appendln("load config model " + fileName + " error : " + e.getMessage());\r
228                     }\r
229                 }\r
230 \r
231                 if (!errorBuilder.isEmpty()) {\r
232                     log.error(errorBuilder.toString());\r
233                 }\r
234             }\r
235         } catch (Exception e) {\r
236             log.error("Failed in Service Template loading", e);\r
237         }\r
238     }\r
239 \r
240     private void loadNodeType(Resource file, StrBuilder errorBuilder) {\r
241         try {\r
242             log.trace("Loading Node Type : {}", file.getFilename());\r
243             String nodeKey = file.getFilename().replace(".json", "");\r
244             String definitionContent = getResourceContent(file);\r
245             NodeType nodeType = JacksonUtils.readValue(definitionContent, NodeType.class);\r
246             Preconditions.checkNotNull(nodeType, String.format("failed to get node type from file : %s", file.getFilename()));\r
247             ModelType modelType = new ModelType();\r
248             modelType.setDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE);\r
249             modelType.setDerivedFrom(nodeType.getDerivedFrom());\r
250             modelType.setDescription(nodeType.getDescription());\r
251             modelType.setDefinition(JacksonUtils.jsonNode(definitionContent));\r
252             modelType.setModelName(nodeKey);\r
253             modelType.setVersion(nodeType.getVersion());\r
254             modelType.setUpdatedBy(updateBySystem);\r
255             modelType.setTags(nodeKey + "," + BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE + ","\r
256                     + nodeType.getDerivedFrom());\r
257             modelTypeService.saveModel(modelType);\r
258             log.trace("Loaded Node Type successfully : {}", file.getFilename());\r
259         } catch (Exception e) {\r
260             log.error("Exception", e);\r
261             errorBuilder.appendln("Node type loading error : " + file.getFilename() + ":" + e.getMessage());\r
262         }\r
263     }\r
264 \r
265     private void loadDataType(@NotNull Resource file, StrBuilder errorBuilder) {\r
266         try {\r
267             log.trace("Loading Data Type: {}", file.getFilename());\r
268             String dataKey = file.getFilename().replace(".json", "");\r
269             String definitionContent = getResourceContent(file);\r
270             DataType dataType = JacksonUtils.readValue(definitionContent, DataType.class);\r
271             Preconditions.checkNotNull(dataType, String.format("failed to get data type from file : %s", file.getFilename()));\r
272             ModelType modelType = new ModelType();\r
273             modelType.setDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE);\r
274             modelType.setDerivedFrom(dataType.getDerivedFrom());\r
275             modelType.setDescription(dataType.getDescription());\r
276             modelType.setDefinition(JacksonUtils.jsonNode(definitionContent));\r
277             modelType.setModelName(dataKey);\r
278             modelType.setVersion(dataType.getVersion());\r
279             modelType.setUpdatedBy(updateBySystem);\r
280             modelType.setTags(dataKey + "," + dataType.getDerivedFrom() + ","\r
281                     + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE);\r
282             modelTypeService.saveModel(modelType);\r
283             log.trace(" Loaded Data Type successfully : {}", file.getFilename());\r
284         } catch (Exception e) {\r
285             log.error("Exception", e);\r
286             errorBuilder.appendln("Data type loading error : " + file.getFilename() + ":" + e.getMessage());\r
287         }\r
288     }\r
289 \r
290     private void loadArtifactType(Resource file, StrBuilder errorBuilder) {\r
291         try {\r
292             log.trace("Loading Artifact Type: {}", file.getFilename());\r
293             String dataKey = file.getFilename().replace(".json", "");\r
294             String definitionContent = getResourceContent(file);\r
295             ArtifactType artifactType = JacksonUtils.readValue(definitionContent, ArtifactType.class);\r
296             Preconditions.checkNotNull(artifactType, String.format("failed to get artifact type from file : %s", file.getFilename()));\r
297             ModelType modelType = new ModelType();\r
298             modelType.setDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE);\r
299             modelType.setDerivedFrom(artifactType.getDerivedFrom());\r
300             modelType.setDescription(artifactType.getDescription());\r
301             modelType.setDefinition(JacksonUtils.jsonNode(definitionContent));\r
302             modelType.setModelName(dataKey);\r
303             modelType.setVersion(artifactType.getVersion());\r
304             modelType.setUpdatedBy(updateBySystem);\r
305             modelType.setTags(dataKey + "," + artifactType.getDerivedFrom() + ","\r
306                     + BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE);\r
307             modelTypeService.saveModel(modelType);\r
308             log.trace("Loaded Artifact Type successfully : {}", file.getFilename());\r
309         } catch (Exception e) {\r
310             log.error("Exception", e);\r
311             errorBuilder.appendln("Artifact type loading error : " + file.getFilename() + ":" + e.getMessage());\r
312         }\r
313     }\r
314 \r
315     private Resource[] getPathResources(String path, String extension) throws IOException {\r
316         return resourceLoader.getResources("file:" + path + "/*" + extension);\r
317     }\r
318 \r
319     private String getResourceContent(Resource resource) throws IOException {\r
320         return IOUtils.toString(resource.getInputStream(), Charset.defaultCharset());\r
321     }\r
322 \r
323 }\r