Merge "Code refactoring"
[clamp.git] / src / main / java / org / onap / clamp / clds / dao / CldsDao.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23
24 package org.onap.clamp.clds.dao;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
29 import java.io.InputStream;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34
35 import javax.sql.DataSource;
36
37 import org.onap.clamp.clds.model.CldsDBServiceCache;
38 import org.onap.clamp.clds.model.CldsEvent;
39 import org.onap.clamp.clds.model.CldsModel;
40 import org.onap.clamp.clds.model.CldsModelInstance;
41 import org.onap.clamp.clds.model.CldsModelProp;
42 import org.onap.clamp.clds.model.CldsServiceData;
43 import org.onap.clamp.clds.model.CldsTemplate;
44 import org.onap.clamp.clds.model.ValueItem;
45 import org.springframework.dao.EmptyResultDataAccessException;
46 import org.springframework.jdbc.core.JdbcTemplate;
47 import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
48 import org.springframework.jdbc.core.namedparam.SqlParameterSource;
49 import org.springframework.jdbc.core.simple.SimpleJdbcCall;
50 import org.springframework.stereotype.Repository;
51
52 /**
53  * Data Access for CLDS Model tables.
54  */
55 @Repository("cldsDao")
56 public class CldsDao {
57     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsDao.class);
58     private JdbcTemplate jdbcTemplateObject;
59     private SimpleJdbcCall procGetModel;
60     private SimpleJdbcCall procGetModelTemplate;
61     private SimpleJdbcCall procSetModel;
62     private SimpleJdbcCall procInsEvent;
63     private SimpleJdbcCall procUpdEvent;
64     private SimpleJdbcCall procSetTemplate;
65     private SimpleJdbcCall procGetTemplate;
66     private SimpleJdbcCall procDelAllModelInstances;
67     private SimpleJdbcCall procInsModelInstance;
68     private static final String HEALTHCHECK = "Select 1";
69
70     /**
71      * Log message when instantiating
72      */
73     public CldsDao() {
74         logger.info("CldsDao instantiating...");
75     }
76
77     /**
78      * When dataSource is provided, instantiate spring jdbc objects.
79      */
80     public void setDataSource(DataSource dataSource) {
81         this.jdbcTemplateObject = new JdbcTemplate(dataSource);
82         this.procGetModel = new SimpleJdbcCall(dataSource).withProcedureName("get_model");
83         this.procGetModelTemplate = new SimpleJdbcCall(dataSource).withProcedureName("get_model_template");
84         this.procSetModel = new SimpleJdbcCall(dataSource).withProcedureName("set_model");
85         this.procInsEvent = new SimpleJdbcCall(dataSource).withProcedureName("ins_event");
86         this.procUpdEvent = new SimpleJdbcCall(dataSource).withProcedureName("upd_event");
87         this.procGetTemplate = new SimpleJdbcCall(dataSource).withProcedureName("get_template");
88         this.procSetTemplate = new SimpleJdbcCall(dataSource).withProcedureName("set_template");
89         this.procInsModelInstance = new SimpleJdbcCall(dataSource).withProcedureName("ins_model_instance");
90         this.procDelAllModelInstances = new SimpleJdbcCall(dataSource).withProcedureName("del_all_model_instances");
91     }
92
93     /**
94      * Get a model from the database given the model name.
95      */
96     public CldsModel getModel(String modelName) {
97         return getModel(modelName, null);
98     }
99
100     /**
101      * Get a model from the database given the controlNameUuid.
102      */
103     public CldsModel getModelByUuid(String controlNameUuid) {
104         return getModel(null, controlNameUuid);
105     }
106
107     // Get a model from the database given the model name or a controlNameUuid.
108     private CldsModel getModel(String modelName, String controlNameUuid) {
109         CldsModel model = new CldsModel();
110         model.setName(modelName);
111         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName)
112                 .addValue("v_control_name_uuid", controlNameUuid);
113         Map<String, Object> out = logSqlExecution(procGetModel, in);
114         model.setControlNamePrefix((String) out.get("v_control_name_prefix"));
115         model.setControlNameUuid((String) out.get("v_control_name_uuid"));
116         model.setId((String) (out.get("v_model_id")));
117         model.setTemplateId((String) (out.get("v_template_id")));
118         model.setTemplateName((String) (out.get("v_template_name")));
119         model.setBpmnText((String) out.get("v_template_bpmn_text"));
120         model.setPropText((String) out.get("v_model_prop_text"));
121         model.setImageText((String) out.get("v_template_image_text"));
122         model.setDocText((String) out.get("v_template_doc_text"));
123         model.setBlueprintText((String) out.get("v_model_blueprint_text"));
124         model.getEvent().setId((String) (out.get("v_event_id")));
125         model.getEvent().setActionCd((String) out.get("v_action_cd"));
126         model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
127         model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
128         model.getEvent().setUserid((String) out.get("v_event_user_id"));
129         model.setTypeId((String) out.get("v_service_type_id"));
130         model.setDeploymentId((String) out.get("v_deployment_id"));
131         return model;
132     }
133
134     /**
135      * Get a model and template information from the database given the model
136      * name.
137      *
138      * @param modelName
139      * @return model
140      */
141     public CldsModel getModelTemplate(String modelName) {
142         CldsModel model = new CldsModel();
143         model.setName(modelName);
144         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName);
145         Map<String, Object> out = logSqlExecution(procGetModelTemplate, in);
146         // todo : rationalize
147         model.setControlNamePrefix((String) out.get("v_control_name_prefix"));
148         model.setControlNameUuid((String) out.get("v_control_name_uuid"));
149         model.setId((String) (out.get("v_model_id")));
150         model.setTemplateId((String) (out.get("v_template_id")));
151         model.setTemplateName((String) (out.get("v_template_name")));
152         model.setBpmnText((String) out.get("v_template_bpmn_text"));
153         model.setPropText((String) out.get("v_model_prop_text"));
154         model.setImageText((String) out.get("v_template_image_text"));
155         model.setDocText((String) out.get("v_template_doc_text"));
156         model.setBlueprintText((String) out.get("v_model_blueprint_text"));
157         model.getEvent().setId((String) (out.get("v_event_id")));
158         model.getEvent().setActionCd((String) out.get("v_action_cd"));
159         model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
160         model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
161         model.getEvent().setUserid((String) out.get("v_event_user_id"));
162         model.setTypeId((String) out.get("v_service_type_id"));
163         model.setDeploymentId((String) out.get("v_deployment_id"));
164         Map<String, Object> modelResults = logSqlExecution(procGetModel, in);
165         Object modelResultObject = modelResults.get("#result-set-1");
166         if (modelResultObject != null && modelResultObject instanceof ArrayList) {
167             List<Object> modelInstanceRs = (List<Object>) modelResultObject;
168             for (Object currModelInstance : modelInstanceRs) {
169                 if (currModelInstance != null && currModelInstance instanceof HashMap) {
170                     HashMap<String, String> modelInstanceMap = (HashMap<String, String>) currModelInstance;
171                     CldsModelInstance modelInstance = new CldsModelInstance();
172                     modelInstance.setModelInstanceId(modelInstanceMap.get("model_instance_id"));
173                     modelInstance.setVmName(modelInstanceMap.get("vm_name"));
174                     modelInstance.setLocation(modelInstanceMap.get("location"));
175                     model.getCldsModelInstanceList().add(modelInstance);
176                     logger.info("value of currModel: {}", currModelInstance);
177                 }
178             }
179         }
180         return model;
181     }
182
183     /**
184      * Update model in the database using parameter values and return updated
185      * model object.
186      *
187      * @param model
188      * @param userid
189      * @return
190      */
191     public CldsModel setModel(CldsModel model, String userid) {
192         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", model.getName())
193                 .addValue("v_template_id", model.getTemplateId()).addValue("v_user_id", userid)
194                 .addValue("v_model_prop_text", model.getPropText())
195                 .addValue("v_model_blueprint_text", model.getBlueprintText())
196                 .addValue("v_service_type_id", model.getTypeId()).addValue("v_deployment_id", model.getDeploymentId())
197                 .addValue("v_control_name_prefix", model.getControlNamePrefix())
198                 .addValue("v_control_name_uuid", model.getControlNameUuid());
199         Map<String, Object> out = logSqlExecution(procSetModel, in);
200         model.setControlNamePrefix((String) out.get("v_control_name_prefix"));
201         model.setControlNameUuid((String) out.get("v_control_name_uuid"));
202         model.setId((String) (out.get("v_model_id")));
203         model.getEvent().setId((String) (out.get("v_event_id")));
204         model.getEvent().setActionCd((String) out.get("v_action_cd"));
205         model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
206         model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
207         model.getEvent().setUserid((String) out.get("v_event_user_id"));
208         return model;
209     }
210
211     /**
212      * Inserts new modelInstance in the database using parameter values and
213      * return updated model object.
214      *
215      * @param model
216      * @param modelInstancesList
217      * @return
218      */
219     public void insModelInstance(CldsModel model, List<CldsModelInstance> modelInstancesList) {
220         // Delete all existing model instances for given controlNameUUID
221         logger.debug("deleting instances for: {}", model.getControlNameUuid());
222         delAllModelInstances(model.getControlNameUuid());
223         if (modelInstancesList == null) {
224             logger.debug("modelInstancesList == null");
225         } else {
226             for (CldsModelInstance currModelInstance : modelInstancesList) {
227                 logger.debug("v_control_name_uuid={}", model.getControlNameUuid());
228                 logger.debug("v_vm_name={}", currModelInstance.getVmName());
229                 logger.debug("v_location={}", currModelInstance.getLocation());
230                 SqlParameterSource in = new MapSqlParameterSource()
231                         .addValue("v_control_name_uuid", model.getControlNameUuid())
232                         .addValue("v_vm_name", currModelInstance.getVmName())
233                         .addValue("v_location", currModelInstance.getLocation());
234                 Map<String, Object> out = logSqlExecution(procInsModelInstance, in);
235                 model.setId((String) (out.get("v_model_id")));
236                 CldsModelInstance modelInstance = new CldsModelInstance();
237                 modelInstance.setLocation(currModelInstance.getLocation());
238                 modelInstance.setVmName(currModelInstance.getVmName());
239                 modelInstance.setModelInstanceId((String) (out.get("v_model_instance_id")));
240                 model.getCldsModelInstanceList().add(modelInstance);
241             }
242         }
243     }
244
245     /**
246      * Insert an event in the database - require either modelName or
247      * controlNamePrefix/controlNameUuid.
248      *
249      * @param modelName
250      * @param controlNamePrefix
251      * @param controlNameUuid
252      * @param cldsEvent
253      * @return
254      */
255     public CldsEvent insEvent(String modelName, String controlNamePrefix, String controlNameUuid, CldsEvent cldsEvent) {
256         CldsEvent event = new CldsEvent();
257         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName)
258                 .addValue("v_control_name_prefix", controlNamePrefix).addValue("v_control_name_uuid", controlNameUuid)
259                 .addValue("v_user_id", cldsEvent.getUserid()).addValue("v_action_cd", cldsEvent.getActionCd())
260                 .addValue("v_action_state_cd", cldsEvent.getActionStateCd())
261                 .addValue("v_process_instance_id", cldsEvent.getProcessInstanceId());
262         Map<String, Object> out = logSqlExecution(procInsEvent, in);
263         event.setId((String) (out.get("v_event_id")));
264         return event;
265     }
266
267     private String delAllModelInstances(String controlNameUUid) {
268         SqlParameterSource in = new MapSqlParameterSource().addValue("v_control_name_uuid", controlNameUUid);
269         Map<String, Object> out = logSqlExecution(procDelAllModelInstances, in);
270         return (String) (out.get("v_model_id"));
271     }
272
273     /**
274      * Update event with process instance id.
275      *
276      * @param eventId
277      * @param processInstanceId
278      */
279     public void updEvent(String eventId, String processInstanceId) {
280         SqlParameterSource in = new MapSqlParameterSource().addValue("v_event_id", eventId)
281                 .addValue("v_process_instance_id", processInstanceId);
282         logSqlExecution(procUpdEvent, in);
283     }
284
285     /**
286      * Return list of model names
287      *
288      * @return model names
289      */
290     public List<ValueItem> getBpmnNames() {
291         String sql = "SELECT model_name FROM model ORDER BY 1;";
292         return jdbcTemplateObject.query(sql, new ValueItemMapper());
293     }
294
295     /**
296      * Update template in the database using parameter values and return updated
297      * template object.
298      *
299      * @param template
300      * @param userid
301      */
302     public void setTemplate(CldsTemplate template, String userid) {
303         SqlParameterSource in = new MapSqlParameterSource().addValue("v_template_name", template.getName())
304                 .addValue("v_user_id", userid).addValue("v_template_bpmn_text", template.getBpmnText())
305                 .addValue("v_template_image_text", template.getImageText())
306                 .addValue("v_template_doc_text", template.getPropText());
307         Map<String, Object> out = logSqlExecution(procSetTemplate, in);
308         template.setId((String) (out.get("v_template_id")));
309         template.setBpmnUserid((String) (out.get("v_template_bpmn_user_id")));
310         template.setBpmnId((String) (out.get("v_template_bpmn_id")));
311         template.setBpmnText((String) (out.get("v_template_bpmn_text")));
312         template.setImageId((String) (out.get("v_template_image_id")));
313         template.setImageUserid((String) out.get("v_template_image_user_id"));
314         template.setImageText((String) out.get("v_template_image_text"));
315         template.setPropId((String) (out.get("v_template_doc_id")));
316         template.setPropUserid((String) out.get("v_template_doc_user_id"));
317         template.setPropText((String) out.get("v_template_doc_text"));
318     }
319
320     /**
321      * Return list of template names
322      *
323      * @return template names
324      */
325     public List<ValueItem> getTemplateNames() {
326         String sql = "SELECT template_name FROM template ORDER BY 1;";
327         return jdbcTemplateObject.query(sql, new ValueItemMapper());
328     }
329
330     /**
331      * Get a template from the database given the model name.
332      *
333      * @param templateName
334      * @return model
335      */
336     public CldsTemplate getTemplate(String templateName) {
337         CldsTemplate template = new CldsTemplate();
338         template.setName(templateName);
339         SqlParameterSource in = new MapSqlParameterSource().addValue("v_template_name", templateName);
340         Map<String, Object> out = logSqlExecution(procGetTemplate, in);
341         template.setId((String) (out.get("v_template_id")));
342         template.setBpmnUserid((String) (out.get("v_template_bpmn_user_id")));
343         template.setBpmnId((String) (out.get("v_template_bpmn_id")));
344         template.setBpmnText((String) (out.get("v_template_bpmn_text")));
345         template.setImageId((String) (out.get("v_template_image_id")));
346         template.setImageUserid((String) out.get("v_template_image_user_id"));
347         template.setImageText((String) out.get("v_template_image_text"));
348         template.setPropId((String) (out.get("v_template_doc_id")));
349         template.setPropUserid((String) out.get("v_template_doc_user_id"));
350         template.setPropText((String) out.get("v_template_doc_text"));
351         return template;
352     }
353
354     public CldsServiceData getCldsServiceCache(String invariantUUID) {
355         CldsServiceData cldsServiceData = null;
356         List<CldsServiceData> cldsServiceDataList = new ArrayList<>();
357         try {
358             String getCldsServiceSQL = "SELECT * , TIMESTAMPDIFF(SECOND, timestamp, CURRENT_TIMESTAMP()) FROM clds_service_cache where invariant_service_id  = ? ";
359             cldsServiceData = jdbcTemplateObject.queryForObject(getCldsServiceSQL, new Object[] {
360                     invariantUUID
361             }, new CldsServiceDataMapper());
362             logger.info("value of cldsServiceDataList: {}", cldsServiceDataList);
363         } catch (EmptyResultDataAccessException e) {
364             logger.warn("cache row not found for invariantUUID: " + invariantUUID, e);
365         }
366         return cldsServiceData;
367     }
368
369     public void setCldsServiceCache(CldsDBServiceCache cldsDBServiceCache) {
370         if (cldsDBServiceCache != null && cldsDBServiceCache.getInvariantId() != null
371                 && cldsDBServiceCache.getServiceId() != null) {
372             String invariantUuid = cldsDBServiceCache.getInvariantId();
373             String serviceUuid = cldsDBServiceCache.getServiceId();
374             InputStream is = cldsDBServiceCache.getCldsDataInstream();
375             String insertCldsServiceCacheSql = "INSERT INTO clds_service_cache"
376                     + "(invariant_service_id,service_id,timestamp,object_data) VALUES"
377                     + "(?,?,CURRENT_TIMESTAMP,?) ON DUPLICATE KEY UPDATE invariant_service_id = VALUES(invariant_service_id) , timestamp = CURRENT_TIMESTAMP , object_data = VALUES(object_data) ";
378             jdbcTemplateObject.update(insertCldsServiceCacheSql, invariantUuid, serviceUuid, is);
379         }
380     }
381
382     private static Map<String, Object> logSqlExecution(SimpleJdbcCall call, SqlParameterSource source) {
383         try {
384             return call.execute(source);
385         } catch (Exception e) {
386             logger.error("Exception occured in " + source.getClass().getCanonicalName() + ": " + e);
387             throw e;
388         }
389     }
390
391     public void doHealthCheck() {
392         jdbcTemplateObject.execute(HEALTHCHECK);
393     }
394
395     /**
396      * Method to get deployed/active models with model properties.
397      * 
398      * @return list of CldsModelProp
399      */
400     public List<CldsModelProp> getDeployedModelProperties() {
401         List<CldsModelProp> cldsModelPropList = new ArrayList<CldsModelProp>();
402         String modelsSql = "select m.model_id, m.model_name, mp.model_prop_id, mp.model_prop_text FROM model m, model_properties mp, event e "
403                 + "WHERE m.model_prop_id = mp.model_prop_id and m.event_id = e.event_id and e.action_cd = 'DEPLOY'";
404         List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(modelsSql);
405         CldsModelProp cldsModelProp = null;
406         for (Map<String, Object> row : rows) {
407             cldsModelProp = new CldsModelProp();
408             cldsModelProp.setId((String) row.get("model_id"));
409             cldsModelProp.setName((String) row.get("model_name"));
410             cldsModelProp.setPropId((String) row.get("model_prop_id"));
411             cldsModelProp.setPropText((String) row.get("model_prop_text"));
412             cldsModelPropList.add(cldsModelProp);
413         }
414         return cldsModelPropList;
415     }
416 }