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