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