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