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