Additional tosca method
[clamp.git] / src / main / java / org / onap / clamp / clds / dao / CldsDao.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 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  *
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.text.SimpleDateFormat;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.stream.Collectors;
36
37 import javax.sql.DataSource;
38
39 import org.onap.clamp.clds.model.CldsDbServiceCache;
40 import org.onap.clamp.clds.model.CldsDictionary;
41 import org.onap.clamp.clds.model.CldsDictionaryItem;
42 import org.onap.clamp.clds.model.CldsEvent;
43 import org.onap.clamp.clds.model.CldsModel;
44 import org.onap.clamp.clds.model.CldsModelInstance;
45 import org.onap.clamp.clds.model.CldsModelProp;
46 import org.onap.clamp.clds.model.CldsMonitoringDetails;
47 import org.onap.clamp.clds.model.CldsServiceData;
48 import org.onap.clamp.clds.model.CldsTemplate;
49 import org.onap.clamp.clds.model.CldsToscaModel;
50 import org.onap.clamp.clds.model.CldsToscaModelDetails;
51 import org.onap.clamp.clds.model.CldsToscaModelRevision;
52 import org.onap.clamp.clds.model.ValueItem;
53 import org.springframework.dao.EmptyResultDataAccessException;
54 import org.springframework.jdbc.core.JdbcTemplate;
55 import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
56 import org.springframework.jdbc.core.namedparam.SqlParameterSource;
57 import org.springframework.jdbc.core.simple.SimpleJdbcCall;
58 import org.springframework.stereotype.Repository;
59
60 /**
61  * Data Access for CLDS Model tables.
62  */
63 @Repository("cldsDao")
64 public class CldsDao {
65
66     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsDao.class);
67     private JdbcTemplate jdbcTemplateObject;
68     private SimpleJdbcCall procGetModel;
69     private SimpleJdbcCall procGetModelTemplate;
70     private SimpleJdbcCall procSetModel;
71     private SimpleJdbcCall procInsEvent;
72     private SimpleJdbcCall procUpdEvent;
73     private SimpleJdbcCall procSetTemplate;
74     private SimpleJdbcCall procGetTemplate;
75     private SimpleJdbcCall procDelAllModelInstances;
76     private SimpleJdbcCall procInsModelInstance;
77     private SimpleJdbcCall procDeleteModel;
78     private static final String HEALTHCHECK = "Select 1";
79     private static final String V_CONTROL_NAME_PREFIX = "v_control_name_prefix";
80     private static final String V_CONTROL_NAME_UUID = "v_control_name_uuid";
81
82     private SimpleJdbcCall procInsertToscaModel;
83     private SimpleJdbcCall procInsertNewToscaModelVersion;
84     private SimpleJdbcCall procInsertDictionary;
85     private SimpleJdbcCall procInsertDictionaryElement;
86
87     private static final String DATE_FORMAT = "MM-dd-yyyy HH:mm:ss";
88
89     /**
90      * Log message when instantiating
91      */
92     public CldsDao() {
93         logger.info("CldsDao instantiating...");
94     }
95
96     /**
97      * When dataSource is provided, instantiate spring jdbc objects.
98      */
99     public void setDataSource(DataSource dataSource) {
100         this.jdbcTemplateObject = new JdbcTemplate(dataSource);
101         this.procGetModel = new SimpleJdbcCall(dataSource).withProcedureName("get_model");
102         this.procGetModelTemplate = new SimpleJdbcCall(dataSource).withProcedureName("get_model_template");
103         this.procSetModel = new SimpleJdbcCall(dataSource).withProcedureName("set_model");
104         this.procInsEvent = new SimpleJdbcCall(dataSource).withProcedureName("ins_event");
105         this.procUpdEvent = new SimpleJdbcCall(dataSource).withProcedureName("upd_event");
106         this.procGetTemplate = new SimpleJdbcCall(dataSource).withProcedureName("get_template");
107         this.procSetTemplate = new SimpleJdbcCall(dataSource).withProcedureName("set_template");
108         this.procInsModelInstance = new SimpleJdbcCall(dataSource).withProcedureName("ins_model_instance");
109         this.procDelAllModelInstances = new SimpleJdbcCall(dataSource).withProcedureName("del_all_model_instances");
110         this.procDeleteModel = new SimpleJdbcCall(dataSource).withProcedureName("del_model");
111         this.procInsertToscaModel = new SimpleJdbcCall(dataSource).withProcedureName("set_tosca_model");
112         this.procInsertNewToscaModelVersion = new SimpleJdbcCall(dataSource)
113             .withProcedureName("set_new_tosca_model_version");
114         this.procInsertDictionary = new SimpleJdbcCall(dataSource).withProcedureName("set_dictionary");
115         this.procInsertDictionaryElement = new SimpleJdbcCall(dataSource).withProcedureName("set_dictionary_elements");
116     }
117
118     /**
119      * Get a model from the database given the model name.
120      */
121     public CldsModel getModel(String modelName) {
122         return getModel(modelName, null);
123     }
124
125     /**
126      * Get a model from the database given the controlNameUuid.
127      */
128     public CldsModel getModelByUuid(String controlNameUuid) {
129         return getModel(null, controlNameUuid);
130     }
131
132     // Get a model from the database given the model name or a controlNameUuid.
133     private CldsModel getModel(String modelName, String controlNameUuid) {
134         CldsModel model = new CldsModel();
135         model.setName(modelName);
136         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName)
137             .addValue(V_CONTROL_NAME_UUID, controlNameUuid);
138         Map<String, Object> out = logSqlExecution(procGetModel, in);
139         populateModelProperties(model, out);
140         return model;
141     }
142
143     /**
144      * Get a model and template information from the database given the model name.
145      *
146      * @param modelName
147      * @return model
148      */
149     public CldsModel getModelTemplate(String modelName) {
150         CldsModel model = new CldsModel();
151         model.setName(modelName);
152         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName);
153         Map<String, Object> out = logSqlExecution(procGetModelTemplate, in);
154         populateModelProperties(model, out);
155         Map<String, Object> modelResults = logSqlExecution(procGetModel, in);
156         Object modelResultObject = modelResults.get("#result-set-1");
157         if (modelResultObject instanceof ArrayList) {
158             for (Object currModelInstance : (List<Object>) modelResultObject) {
159                 if (currModelInstance instanceof HashMap) {
160                     HashMap<String, String> modelInstanceMap = (HashMap<String, String>) currModelInstance;
161                     CldsModelInstance modelInstance = new CldsModelInstance();
162                     modelInstance.setModelInstanceId(modelInstanceMap.get("model_instance_id"));
163                     modelInstance.setVmName(modelInstanceMap.get("vm_name"));
164                     modelInstance.setLocation(modelInstanceMap.get("location"));
165                     model.getCldsModelInstanceList().add(modelInstance);
166                     logger.info("value of currModel: {}", currModelInstance);
167                 }
168             }
169         }
170         return model;
171     }
172
173     /**
174      * Update model in the database using parameter values and return updated model
175      * object.
176      *
177      * @param model
178      * @param userid
179      * @return
180      */
181     public CldsModel setModel(CldsModel model, String userid) {
182         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", model.getName())
183             .addValue("v_template_id", model.getTemplateId()).addValue("v_user_id", userid)
184             .addValue("v_model_prop_text", model.getPropText())
185             .addValue("v_model_blueprint_text", model.getBlueprintText())
186             .addValue("v_service_type_id", model.getTypeId()).addValue("v_deployment_id", model.getDeploymentId())
187             .addValue("v_deployment_status_url", model.getDeploymentStatusUrl())
188             .addValue("v_control_name_prefix", model.getControlNamePrefix())
189             .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid());
190         Map<String, Object> out = logSqlExecution(procSetModel, in);
191         model.setControlNamePrefix((String) out.get(V_CONTROL_NAME_PREFIX));
192         model.setControlNameUuid((String) out.get(V_CONTROL_NAME_UUID));
193         model.setId((String) (out.get("v_model_id")));
194         model.getEvent().setId((String) (out.get("v_event_id")));
195         model.getEvent().setActionCd((String) out.get("v_action_cd"));
196         model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
197         model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
198         model.getEvent().setUserid((String) out.get("v_event_user_id"));
199         return model;
200     }
201
202     /**
203      * Inserts new modelInstance in the database using parameter values and return
204      * updated model object.
205      *
206      * @param model
207      * @param modelInstancesList
208      * @return
209      */
210     public void insModelInstance(CldsModel model, List<CldsModelInstance> modelInstancesList) {
211         // Delete all existing model instances for given controlNameUUID
212         logger.debug("deleting instances for: {}", model.getControlNameUuid());
213         delAllModelInstances(model.getControlNameUuid());
214         if (modelInstancesList == null) {
215             logger.debug("modelInstancesList == null");
216         } else {
217             for (CldsModelInstance currModelInstance : modelInstancesList) {
218                 logger.debug("v_control_name_uuid={}", model.getControlNameUuid());
219                 logger.debug("v_vm_name={}", currModelInstance.getVmName());
220                 logger.debug("v_location={}", currModelInstance.getLocation());
221                 SqlParameterSource in = new MapSqlParameterSource()
222                     .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid())
223                     .addValue("v_vm_name", currModelInstance.getVmName())
224                     .addValue("v_location", currModelInstance.getLocation());
225                 Map<String, Object> out = logSqlExecution(procInsModelInstance, in);
226                 model.setId((String) (out.get("v_model_id")));
227                 CldsModelInstance modelInstance = new CldsModelInstance();
228                 modelInstance.setLocation(currModelInstance.getLocation());
229                 modelInstance.setVmName(currModelInstance.getVmName());
230                 modelInstance.setModelInstanceId((String) (out.get("v_model_instance_id")));
231                 model.getCldsModelInstanceList().add(modelInstance);
232             }
233         }
234     }
235
236     /**
237      * Insert an event in the database - require either modelName or
238      * controlNamePrefix/controlNameUuid.
239      *
240      * @param modelName
241      * @param controlNamePrefix
242      * @param controlNameUuid
243      * @param cldsEvent
244      * @return
245      */
246     public CldsEvent insEvent(String modelName, String controlNamePrefix, String controlNameUuid, CldsEvent cldsEvent) {
247         CldsEvent event = new CldsEvent();
248         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName)
249             .addValue(V_CONTROL_NAME_PREFIX, controlNamePrefix).addValue(V_CONTROL_NAME_UUID, controlNameUuid)
250             .addValue("v_user_id", cldsEvent.getUserid()).addValue("v_action_cd", cldsEvent.getActionCd())
251             .addValue("v_action_state_cd", cldsEvent.getActionStateCd())
252             .addValue("v_process_instance_id", cldsEvent.getProcessInstanceId());
253         Map<String, Object> out = logSqlExecution(procInsEvent, in);
254         event.setId((String) (out.get("v_event_id")));
255         return event;
256     }
257
258     private String delAllModelInstances(String controlNameUUid) {
259         SqlParameterSource in = new MapSqlParameterSource().addValue(V_CONTROL_NAME_UUID, controlNameUUid);
260         Map<String, Object> out = logSqlExecution(procDelAllModelInstances, in);
261         return (String) (out.get("v_model_id"));
262     }
263
264     /**
265      * Update event with process instance id.
266      *
267      * @param eventId
268      * @param processInstanceId
269      */
270     public void updEvent(String eventId, String processInstanceId) {
271         SqlParameterSource in = new MapSqlParameterSource().addValue("v_event_id", eventId)
272             .addValue("v_process_instance_id", processInstanceId);
273         logSqlExecution(procUpdEvent, in);
274     }
275
276     /**
277      * Return list of model names
278      *
279      * @return model names
280      */
281     public List<ValueItem> getModelNames() {
282         String sql = "SELECT model_name FROM model ORDER BY 1;";
283         return jdbcTemplateObject.query(sql, new ValueItemMapper());
284     }
285
286     /**
287      * Update template in the database using parameter values and return updated
288      * template object.
289      *
290      * @param template
291      * @param userid
292      */
293     public void setTemplate(CldsTemplate template, String userid) {
294         SqlParameterSource in = new MapSqlParameterSource().addValue("v_template_name", template.getName())
295             .addValue("v_user_id", userid).addValue("v_template_bpmn_text", template.getBpmnText())
296             .addValue("v_template_image_text", template.getImageText())
297             .addValue("v_template_doc_text", template.getPropText());
298         Map<String, Object> out = logSqlExecution(procSetTemplate, in);
299         template.setId((String) (out.get("v_template_id")));
300         template.setBpmnUserid((String) (out.get("v_template_bpmn_user_id")));
301         template.setBpmnId((String) (out.get("v_template_bpmn_id")));
302         template.setImageId((String) (out.get("v_template_image_id")));
303         template.setImageUserid((String) out.get("v_template_image_user_id"));
304         template.setPropId((String) (out.get("v_template_doc_id")));
305         template.setPropUserid((String) out.get("v_template_doc_user_id"));
306     }
307
308     /**
309      * Return list of template names
310      *
311      * @return template names
312      */
313     public List<ValueItem> getTemplateNames() {
314         String sql = "SELECT template_name FROM template ORDER BY 1;";
315         return jdbcTemplateObject.query(sql, new ValueItemMapper());
316     }
317
318     /**
319      * Get a template from the database given the model name.
320      *
321      * @param templateName
322      * @return model
323      */
324     public CldsTemplate getTemplate(String templateName) {
325         CldsTemplate template = new CldsTemplate();
326         template.setName(templateName);
327         SqlParameterSource in = new MapSqlParameterSource().addValue("v_template_name", templateName);
328         Map<String, Object> out = logSqlExecution(procGetTemplate, in);
329         template.setId((String) (out.get("v_template_id")));
330         template.setBpmnUserid((String) (out.get("v_template_bpmn_user_id")));
331         template.setBpmnId((String) (out.get("v_template_bpmn_id")));
332         template.setBpmnText((String) (out.get("v_template_bpmn_text")));
333         template.setImageId((String) (out.get("v_template_image_id")));
334         template.setImageUserid((String) out.get("v_template_image_user_id"));
335         template.setImageText((String) out.get("v_template_image_text"));
336         template.setPropId((String) (out.get("v_template_doc_id")));
337         template.setPropUserid((String) out.get("v_template_doc_user_id"));
338         template.setPropText((String) out.get("v_template_doc_text"));
339         return template;
340     }
341
342     public void clearServiceCache() {
343         String clearCldsServiceCacheSql = "TRUNCATE clds_service_cache";
344         jdbcTemplateObject.execute(clearCldsServiceCacheSql);
345     }
346
347     public CldsServiceData getCldsServiceCache(String invariantUUID) {
348         CldsServiceData cldsServiceData = null;
349         try {
350             String getCldsServiceSQL = "SELECT * , TIMESTAMPDIFF(SECOND, timestamp, CURRENT_TIMESTAMP()) FROM clds_service_cache where invariant_service_id  = ? ";
351             cldsServiceData = jdbcTemplateObject.queryForObject(getCldsServiceSQL, new Object[] { invariantUUID },
352                 new CldsServiceDataMapper());
353             if (cldsServiceData != null) {
354                 logger.info("CldsServiceData found in cache for Service Invariant ID:"
355                     + cldsServiceData.getServiceInvariantUUID());
356                 return cldsServiceData;
357             } else {
358                 logger.warn("CldsServiceData not found in cache for Service Invariant ID:" + invariantUUID);
359                 return null;
360             }
361         } catch (EmptyResultDataAccessException e) {
362             logger.info("CldsServiceData not found in cache for Service Invariant ID: " + invariantUUID);
363             logger.debug("CldsServiceData not found in cache for Service Invariant ID: " + invariantUUID, e);
364             return null;
365         }
366     }
367
368     public void setCldsServiceCache(CldsDbServiceCache cldsDBServiceCache) {
369         if (cldsDBServiceCache != null && cldsDBServiceCache.getInvariantId() != null
370             && cldsDBServiceCache.getServiceId() != null) {
371             String invariantUuid = cldsDBServiceCache.getInvariantId();
372             String serviceUuid = cldsDBServiceCache.getServiceId();
373             InputStream is = cldsDBServiceCache.getCldsDataInstream();
374             String insertCldsServiceCacheSql = "INSERT INTO clds_service_cache"
375                 + "(invariant_service_id,service_id,timestamp,object_data) VALUES"
376                 + "(?,?,CURRENT_TIMESTAMP,?) ON DUPLICATE KEY UPDATE invariant_service_id = VALUES(invariant_service_id) , timestamp = CURRENT_TIMESTAMP , object_data = VALUES(object_data) ";
377             jdbcTemplateObject.update(insertCldsServiceCacheSql, invariantUuid, serviceUuid, is);
378         }
379     }
380
381     private static Map<String, Object> logSqlExecution(SimpleJdbcCall call, SqlParameterSource source) {
382         try {
383             return call.execute(source);
384         } catch (Exception e) {
385             logger.error("Exception occured in " + source.getClass().getCanonicalName() + ": " + e);
386             throw e;
387         }
388     }
389
390     public void doHealthCheck() {
391         jdbcTemplateObject.execute(HEALTHCHECK);
392     }
393
394     /**
395      * Method to get deployed/active models with model properties.
396      *
397      * @return list of CldsModelProp
398      */
399     public List<CldsModelProp> getDeployedModelProperties() {
400         List<CldsModelProp> cldsModelPropList = new ArrayList<>();
401         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 "
402             + "WHERE m.model_prop_id = mp.model_prop_id and m.event_id = e.event_id and e.action_cd = 'DEPLOY'";
403         List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(modelsSql);
404         CldsModelProp cldsModelProp = null;
405         for (Map<String, Object> row : rows) {
406             cldsModelProp = new CldsModelProp();
407             cldsModelProp.setId((String) row.get("model_id"));
408             cldsModelProp.setName((String) row.get("model_name"));
409             cldsModelProp.setPropId((String) row.get("model_prop_id"));
410             cldsModelProp.setPropText((String) row.get("model_prop_text"));
411             cldsModelPropList.add(cldsModelProp);
412         }
413         return cldsModelPropList;
414     }
415
416     /**
417      * Method to get deployed/active models with model properties.
418      *
419      * @return list of CLDS-Monitoring-Details: CLOSELOOP_NAME | Close loop name
420      *         used in the CLDS application (prefix: ClosedLoop- + unique ClosedLoop
421      *         ID) MODEL_NAME | Model Name in CLDS application SERVICE_TYPE_ID |
422      *         TypeId returned from the DCAE application when the ClosedLoop is
423      *         submitted (DCAEServiceTypeRequest generated in DCAE application).
424      *         DEPLOYMENT_ID | Id generated when the ClosedLoop is deployed in DCAE.
425      *         TEMPLATE_NAME | Template used to generate the ClosedLoop model.
426      *         ACTION_CD | Current state of the ClosedLoop in CLDS application.
427      */
428     public List<CldsMonitoringDetails> getCLDSMonitoringDetails() {
429         SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
430         List<CldsMonitoringDetails> cldsMonitoringDetailsList = new ArrayList<>();
431         String modelsSql = "SELECT CONCAT(M.CONTROL_NAME_PREFIX, M.CONTROL_NAME_UUID) AS CLOSELOOP_NAME , M.MODEL_NAME, M.SERVICE_TYPE_ID, M.DEPLOYMENT_ID, T.TEMPLATE_NAME, E.ACTION_CD, E.USER_ID, E.TIMESTAMP "
432             + "FROM MODEL M, TEMPLATE T, EVENT E " + "WHERE M.TEMPLATE_ID = T.TEMPLATE_ID AND M.EVENT_ID = E.EVENT_ID "
433             + "ORDER BY ACTION_CD";
434         List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(modelsSql);
435         CldsMonitoringDetails cldsMonitoringDetails = null;
436         for (Map<String, Object> row : rows) {
437             cldsMonitoringDetails = new CldsMonitoringDetails();
438             cldsMonitoringDetails.setCloseloopName((String) row.get("CLOSELOOP_NAME"));
439             cldsMonitoringDetails.setModelName((String) row.get("MODEL_NAME"));
440             cldsMonitoringDetails.setServiceTypeId((String) row.get("SERVICE_TYPE_ID"));
441             cldsMonitoringDetails.setDeploymentId((String) row.get("DEPLOYMENT_ID"));
442             cldsMonitoringDetails.setTemplateName((String) row.get("TEMPLATE_NAME"));
443             cldsMonitoringDetails.setAction((String) row.get("ACTION_CD"));
444             cldsMonitoringDetails.setUserid((String) row.get("USER_ID"));
445             cldsMonitoringDetails.setTimestamp(sdf.format(row.get("TIMESTAMP")));
446             cldsMonitoringDetailsList.add(cldsMonitoringDetails);
447         }
448         return cldsMonitoringDetailsList;
449     }
450
451     /**
452      * Method to delete model from database.
453      *
454      * @param modelName
455      */
456     public void deleteModel(String modelName) {
457         SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName);
458         logSqlExecution(procDeleteModel, in);
459     }
460
461     private void populateModelProperties(CldsModel model, Map out) {
462         model.setControlNamePrefix((String) out.get(V_CONTROL_NAME_PREFIX));
463         model.setControlNameUuid((String) out.get(V_CONTROL_NAME_UUID));
464         model.setId((String) (out.get("v_model_id")));
465         model.setTemplateId((String) (out.get("v_template_id")));
466         model.setTemplateName((String) (out.get("v_template_name")));
467         model.setBpmnText((String) out.get("v_template_bpmn_text"));
468         model.setPropText((String) out.get("v_model_prop_text"));
469         model.setImageText((String) out.get("v_template_image_text"));
470         model.setDocText((String) out.get("v_template_doc_text"));
471         model.setBlueprintText((String) out.get("v_model_blueprint_text"));
472         model.getEvent().setId((String) (out.get("v_event_id")));
473         model.getEvent().setActionCd((String) out.get("v_action_cd"));
474         model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
475         model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
476         model.getEvent().setUserid((String) out.get("v_event_user_id"));
477         model.setTypeId((String) out.get("v_service_type_id"));
478         model.setDeploymentId((String) out.get("v_deployment_id"));
479         model.setDeploymentStatusUrl((String) out.get("v_deployment_status_url"));
480     }
481
482     /**
483      * Method to retrieve a tosca models by Policy Type from database.
484      *
485      * @param policyType
486      * @return List of CldsToscaModel
487      */
488     public List<CldsToscaModel> getAllToscaModels() {
489         return getToscaModel(null, null);
490     }
491
492     /**
493      * Method to retrieve a tosca models by Policy Type from database.
494      *
495      * @param policyType
496      * @return List of CldsToscaModel
497      */
498     public List<CldsToscaModel> getToscaModelByPolicyType(String policyType) {
499         return getToscaModel(null, policyType);
500     }
501
502     /**
503      * Method to retrieve a tosca models by toscaModelName, version from database.
504      *
505      * @param policyType
506      * @return List of CldsToscaModel
507      */
508     public List<CldsToscaModel> getToscaModelByName(String toscaModelName) {
509         return getToscaModel(toscaModelName, null);
510     }
511
512     // Retrieve the latest tosca model for a policy type or by tosca model name
513
514     private List<CldsToscaModel> getToscaModel(String toscaModelName, String policyType) {
515         SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
516         List<CldsToscaModel> cldsToscaModels = new ArrayList<>();
517
518         String toscaModelSql = "SELECT tm.tosca_model_name, tm.tosca_model_id, tm.policy_type, tmr.tosca_model_revision_id, tmr.tosca_model_json, tmr.version, tmr.user_id, tmr.createdTimestamp, tmr.lastUpdatedTimestamp "
519             + ((toscaModelName != null) ? (", tmr.tosca_model_yaml ") : " ")
520             + "FROM tosca_model tm, tosca_model_revision tmr WHERE tm.tosca_model_id = tmr.tosca_model_id "
521             + ((toscaModelName != null) ? (" AND tm.tosca_model_name = '" + toscaModelName + "'") : " ")
522             + ((policyType != null) ? (" AND tm.policy_type = '" + policyType + "'") : " ")
523             + "AND tmr.version = (select max(version) from tosca_model_revision st where tmr.tosca_model_id=st.tosca_model_id)";
524
525         List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(toscaModelSql);
526
527         if (rows != null) {
528             rows.forEach(row -> {
529                 CldsToscaModel cldsToscaModel = new CldsToscaModel();
530                 cldsToscaModel.setId((String) row.get("tosca_model_id"));
531                 cldsToscaModel.setPolicyType((String) row.get("policy_type"));
532                 cldsToscaModel.setToscaModelName((String) row.get("tosca_model_name"));
533                 cldsToscaModel.setUserId((String) row.get("user_id"));
534                 cldsToscaModel.setRevisionId((String) row.get("tosca_model_revision_id"));
535                 cldsToscaModel.setToscaModelJson((String) row.get("tosca_model_json"));
536                 cldsToscaModel.setVersion(((Double) row.get("version")));
537                 cldsToscaModel.setCreatedDate(sdf.format(row.get("createdTimestamp")));
538                 cldsToscaModel.setLastUpdatedDate(sdf.format(row.get("lastUpdatedTimestamp")));
539                 if (toscaModelName != null) {
540                     cldsToscaModel.setToscaModelYaml((String) row.get("tosca_model_yaml"));
541                 }
542                 cldsToscaModels.add(cldsToscaModel);
543             });
544         }
545         return cldsToscaModels;
546     }
547
548     // Retrieve Tosca Models & its revisions by policy Type.
549     private List<CldsToscaModelDetails> getAllToscaModelVersion(String toscaModelName, String policyType,
550         String version) {
551         SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
552         List<CldsToscaModelDetails> cldsToscaModelDetailsList = new ArrayList<>();
553         String toscaModelSql = "SELECT tm.tosca_model_name, tm.tosca_model_id, tm.policy_type, tmr.tosca_model_revision_id, tmr.version, tmr.user_id, tmr.createdTimestamp, tmr.lastUpdatedTimestamp "
554             + "FROM tosca_model tm, tosca_model_revision tmr " + "WHERE tmr.tosca_model_id = tm.tosca_model_id "
555             + ((policyType != null) ? (" AND tm.policy_type = '" + policyType + "'") : " ")
556             + ((toscaModelName != null) ? (" AND tm.tosca_model_name = '" + toscaModelName + "'") : " ")
557             + ((version != null) ? (" AND tmr.version = '" + version + "'") : "");
558
559         List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(toscaModelSql);
560
561         if (rows != null && !rows.isEmpty()) {
562             // Get list of all available modelIds
563             List<String> listofModelIds = new ArrayList<>();
564             for (Map<String, Object> r : rows) {
565                 if (r != null) {
566                     listofModelIds.add((String) r.get("tosca_model_id"));
567                 }
568             }
569             // Filter Distinct elements using streams
570             listofModelIds = listofModelIds.stream().distinct().collect(Collectors.toList());
571
572             // TODO change logic using java8
573             for (String modelId : listofModelIds) {
574                 CldsToscaModelDetails cldsToscaModelDetails = new CldsToscaModelDetails();
575                 List<CldsToscaModelRevision> revisions = new ArrayList<>();
576                 for (Map<String, Object> row : rows) {
577                     String id = (String) row.get("tosca_model_id");
578                     if (modelId.equalsIgnoreCase(id)) {
579                         cldsToscaModelDetails.setId(id);
580                         cldsToscaModelDetails.setPolicyType((String) row.get("policy_type"));
581                         cldsToscaModelDetails.setToscaModelName((String) row.get("tosca_model_name"));
582                         cldsToscaModelDetails.setUserId((String) row.get("user_id"));
583
584                         CldsToscaModelRevision modelRevision = new CldsToscaModelRevision();
585                         modelRevision.setRevisionId((String) row.get("tosca_model_revision_id"));
586                         modelRevision.setVersion(((Double) row.get("version")));
587                         modelRevision.setUserId((String) row.get("user_id"));
588                         modelRevision.setCreatedDate(sdf.format(row.get("createdTimestamp")));
589                         modelRevision.setLastUpdatedDate(sdf.format(row.get("lastUpdatedTimestamp")));
590                         revisions.add(modelRevision);
591                     }
592                 }
593                 cldsToscaModelDetails.setToscaModelRevisions(revisions);
594                 cldsToscaModelDetailsList.add(cldsToscaModelDetails);
595             }
596         }
597         return cldsToscaModelDetailsList;
598     }
599
600     /**
601      * Method to upload a new version of Tosca Model Yaml in Database
602      *
603      * @param cldsToscaModel
604      * @param userId
605      * @return CldsToscaModel
606      *
607      */
608     public CldsToscaModel updateToscaModelWithNewVersion(CldsToscaModel cldsToscaModel, String userId) {
609         SqlParameterSource in = new MapSqlParameterSource().addValue("v_tosca_model_id", cldsToscaModel.getId())
610             .addValue("v_version", cldsToscaModel.getVersion())
611             .addValue("v_tosca_model_yaml", cldsToscaModel.getToscaModelYaml())
612             .addValue("v_tosca_model_json", cldsToscaModel.getToscaModelJson()).addValue("v_user_id", userId);
613         Map<String, Object> out = logSqlExecution(procInsertNewToscaModelVersion, in);
614         cldsToscaModel.setRevisionId((String) (out.get("v_revision_id")));
615         return cldsToscaModel;
616     }
617
618     /**
619      * Method to upload a new Tosca model Yaml in DB. Default version is 1.0
620      *
621      * @param cldsToscaModel
622      * @param userId
623      * @return CldsToscaModel
624      */
625     public CldsToscaModel insToscaModel(CldsToscaModel cldsToscaModel, String userId) {
626         SqlParameterSource in = new MapSqlParameterSource()
627             .addValue("v_tosca_model_name", cldsToscaModel.getToscaModelName())
628             .addValue("v_policy_type", cldsToscaModel.getPolicyType())
629             .addValue("v_tosca_model_yaml", cldsToscaModel.getToscaModelYaml())
630             .addValue("v_tosca_model_json", cldsToscaModel.getToscaModelJson())
631             .addValue("v_version", cldsToscaModel.getVersion()).addValue("v_user_id", userId);
632         Map<String, Object> out = logSqlExecution(procInsertToscaModel, in);
633         cldsToscaModel.setId((String) (out.get("v_tosca_model_id")));
634         cldsToscaModel.setRevisionId((String) (out.get("v_revision_id")));
635         cldsToscaModel.setUserId((String) out.get("v_user_id"));
636         return cldsToscaModel;
637     }
638
639     /**
640      * Method to insert a new Dictionary in Database
641      *
642      * @param cldsDictionary
643      */
644     public void insDictionary(CldsDictionary cldsDictionary) {
645         SqlParameterSource in = new MapSqlParameterSource()
646             .addValue("v_dictionary_name", cldsDictionary.getDictionaryName())
647             .addValue("v_user_id", cldsDictionary.getCreatedBy());
648         Map<String, Object> out = logSqlExecution(procInsertDictionary, in);
649         cldsDictionary.setDictionaryId((String) (out.get("v_dictionary_id")));
650     }
651
652     /**
653      * Method to update Dictionary with new info in Database
654      *
655      * @param dictionaryId
656      * @param cldsDictionary
657      * @param userId
658      */
659     public void updateDictionary(String dictionaryId, CldsDictionary cldsDictionary, String userId) {
660
661         String dictionarySql = "UPDATE dictionary " + "SET dictionary_name = '" + cldsDictionary.getDictionaryName()
662             + "', modified_by = '" + userId + "'" + "WHERE dictionary_id = '" + dictionaryId + "'";
663         jdbcTemplateObject.update(dictionarySql);
664         cldsDictionary.setUpdatedBy(userId);
665     }
666
667     /**
668      * Method to get list of Dictionaries from the Database
669      *
670      * @param dictionaryId
671      * @param dictionaryName
672      * @return
673      */
674     public List<CldsDictionary> getDictionary(String dictionaryId, String dictionaryName) {
675         SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
676         List<CldsDictionary> dictionaries = new ArrayList<>();
677         String dictionarySql = "SELECT dictionary_id, dictionary_name, created_by, modified_by, timestamp FROM dictionary"
678             + ((dictionaryId != null || dictionaryName != null)
679                 ? (" WHERE " + ((dictionaryName != null) ? ("dictionary_name = '" + dictionaryName + "'") : "")
680                     + ((dictionaryId != null && dictionaryName != null) ? (" AND ") : "")
681                     + ((dictionaryId != null) ? ("dictionary_id = '" + dictionaryId + "'") : ""))
682                 : "");
683
684         List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql);
685
686         if (rows != null) {
687             rows.forEach(row -> {
688                 CldsDictionary cldsDictionary = new CldsDictionary();
689                 cldsDictionary.setDictionaryId((String) row.get("dictionary_id"));
690                 cldsDictionary.setDictionaryName((String) row.get("dictionary_name"));
691                 cldsDictionary.setCreatedBy((String) row.get("created_by"));
692                 cldsDictionary.setUpdatedBy((String) row.get("modified_by"));
693                 cldsDictionary.setLastUpdatedDate(sdf.format(row.get("timestamp")));
694                 dictionaries.add(cldsDictionary);
695             });
696         }
697         return dictionaries;
698     }
699
700     /**
701      * Method to insert a new Dictionary Element for given dictionary in Database
702      *
703      * @param cldsDictionaryItem
704      * @param userId
705      */
706     public void insDictionarElements(CldsDictionaryItem cldsDictionaryItem, String userId) {
707         SqlParameterSource in = new MapSqlParameterSource()
708             .addValue("v_dictionary_id", cldsDictionaryItem.getDictionaryId())
709             .addValue("v_dict_element_name", cldsDictionaryItem.getDictElementName())
710             .addValue("v_dict_element_short_name", cldsDictionaryItem.getDictElementShortName())
711             .addValue("v_dict_element_description", cldsDictionaryItem.getDictElementDesc())
712             .addValue("v_dict_element_type", cldsDictionaryItem.getDictElementType()).addValue("v_user_id", userId);
713         Map<String, Object> out = logSqlExecution(procInsertDictionaryElement, in);
714         cldsDictionaryItem.setDictElementId((String) (out.get("v_dict_element_id")));
715     }
716
717     /**
718      * Method to update Dictionary Elements with new info for a given dictionary in
719      * Database
720      *
721      * @param dictionaryElementId
722      * @param cldsDictionaryItem
723      * @param userId
724      */
725     public void updateDictionaryElements(String dictionaryElementId, CldsDictionaryItem cldsDictionaryItem,
726         String userId) {
727
728         String dictionarySql = "UPDATE dictionary_elements SET dict_element_name = '"
729             + cldsDictionaryItem.getDictElementName() + "', dict_element_short_name = '"
730             + cldsDictionaryItem.getDictElementShortName() + "', dict_element_description= '"
731             + cldsDictionaryItem.getDictElementDesc() + "', dict_element_type = '"
732             + cldsDictionaryItem.getDictElementType() + "', modified_by = '" + userId + "' "
733             + "WHERE dict_element_id = '" + dictionaryElementId + "'";
734         jdbcTemplateObject.update(dictionarySql);
735         cldsDictionaryItem.setUpdatedBy(userId);
736     }
737
738     /**
739      * Method to get list of all dictionary elements for a given dictionary in the
740      * Database
741      *
742      * @param dictionaryName
743      * @param dictionaryId
744      * @param dictElementShortName
745      * @return
746      */
747     public List<CldsDictionaryItem> getDictionaryElements(String dictionaryName, String dictionaryId,
748         String dictElementShortName) {
749         SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
750         List<CldsDictionaryItem> dictionaryItems = new ArrayList<>();
751         String dictionarySql = "SELECT de.dict_element_id, de.dictionary_id, de.dict_element_name, de.dict_element_short_name, de.dict_element_description, de.dict_element_type, de.created_by, de.modified_by, de.timestamp  "
752             + "FROM dictionary_elements de, dictionary d WHERE de.dictionary_id = d.dictionary_id "
753             + ((dictionaryId != null) ? (" AND d.dictionary_id = '" + dictionaryId + "'") : "")
754             + ((dictElementShortName != null) ? (" AND de.dict_element_short_name = '" + dictElementShortName + "'")
755                 : "")
756             + ((dictionaryName != null) ? (" AND dictionary_name = '" + dictionaryName + "'") : "");
757
758         List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql);
759
760         if (rows != null) {
761             rows.forEach(row -> {
762                 CldsDictionaryItem dictionaryItem = new CldsDictionaryItem();
763                 dictionaryItem.setDictElementId((String) row.get("dict_element_id"));
764                 dictionaryItem.setDictionaryId((String) row.get("dictionary_id"));
765                 dictionaryItem.setDictElementName((String) row.get("dict_element_name"));
766                 dictionaryItem.setDictElementShortName((String) row.get("dict_element_short_name"));
767                 dictionaryItem.setDictElementDesc((String) row.get("dict_element_description"));
768                 dictionaryItem.setDictElementType((String) row.get("dict_element_type"));
769                 dictionaryItem.setCreatedBy((String) row.get("created_by"));
770                 dictionaryItem.setUpdatedBy((String) row.get("modified_by"));
771                 dictionaryItem.setLastUpdatedDate(sdf.format(row.get("timestamp")));
772                 dictionaryItems.add(dictionaryItem);
773             });
774         }
775         return dictionaryItems;
776     }
777
778     /**
779      * Method to get Map of all dictionary elements with key as dictionary short
780      * name and value as the full name
781      *
782      * @param dictionaryElementType
783      * @return Map of dictionary elements as key value pair
784      */
785     public Map<String, String> getDictionaryElementsByType(String dictionaryElementType) {
786         Map<String, String> dictionaryItems = new HashMap<>();
787         String dictionarySql = "SELECT dict_element_name, dict_element_short_name " + "FROM dictionary_elements "
788             + "WHERE dict_element_type = '" + dictionaryElementType + "'";
789
790         List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql);
791
792         if (rows != null) {
793             rows.forEach(row -> {
794                 dictionaryItems.put(((String) row.get("dict_element_short_name")),
795                     ((String) row.get("dict_element_name")));
796             });
797         }
798         return dictionaryItems;
799     }
800 }