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