Merge "Improve tests"
[clamp.git] / src / main / java / org / onap / clamp / clds / service / CldsService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * Modifications copyright (c) 2018 Nokia
21  * ===================================================================
22  *
23  */
24
25 package org.onap.clamp.clds.service;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29
30 import com.google.gson.JsonElement;
31 import com.google.gson.JsonObject;
32 import com.google.gson.reflect.TypeToken;
33 import java.io.IOException;
34 import java.lang.reflect.Type;
35 import java.security.GeneralSecurityException;
36 import java.util.Date;
37 import java.util.List;
38 import java.util.UUID;
39
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.BadRequestException;
42 import javax.ws.rs.NotAuthorizedException;
43 import javax.xml.transform.TransformerException;
44
45 import org.apache.camel.Produce;
46 import org.apache.commons.codec.DecoderException;
47 import org.json.simple.parser.ParseException;
48 import org.onap.clamp.clds.camel.CamelProxy;
49 import org.onap.clamp.clds.client.DcaeDispatcherServices;
50 import org.onap.clamp.clds.client.DcaeInventoryServices;
51 import org.onap.clamp.clds.config.ClampProperties;
52 import org.onap.clamp.clds.dao.CldsDao;
53 import org.onap.clamp.clds.exception.policy.PolicyClientException;
54 import org.onap.clamp.clds.exception.sdc.SdcCommunicationException;
55 import org.onap.clamp.clds.model.CldsEvent;
56 import org.onap.clamp.clds.model.CldsInfo;
57 import org.onap.clamp.clds.model.CldsModel;
58 import org.onap.clamp.clds.model.CldsModelProp;
59 import org.onap.clamp.clds.model.CldsMonitoringDetails;
60 import org.onap.clamp.clds.model.CldsTemplate;
61 import org.onap.clamp.clds.model.DcaeEvent;
62 import org.onap.clamp.clds.model.ValueItem;
63 import org.onap.clamp.clds.model.properties.ModelProperties;
64 import org.onap.clamp.clds.model.sdc.SdcServiceInfo;
65 import org.onap.clamp.clds.sdc.controller.installer.CsarInstallerImpl;
66 import org.onap.clamp.clds.transform.XslTransformer;
67 import org.onap.clamp.clds.util.JsonUtils;
68 import org.onap.clamp.clds.util.LoggingUtils;
69 import org.onap.clamp.clds.util.ONAPLogConstants;
70 import org.slf4j.event.Level;
71 import org.springframework.beans.factory.annotation.Autowired;
72 import org.springframework.beans.factory.annotation.Value;
73 import org.springframework.http.HttpStatus;
74 import org.springframework.http.ResponseEntity;
75 import org.springframework.stereotype.Component;
76 import org.springframework.web.client.HttpClientErrorException;
77
78 /**
79  * Service to save and retrieve the CLDS model attributes.
80  */
81 @Component
82 public class CldsService extends SecureServiceBase {
83
84     public static final Type LIST_OF_SDC_SERVICE_INFO_TYPE = new TypeToken<List<SdcServiceInfo>>() {
85     }.getType();
86     @Produce(uri = "direct:processSubmit")
87     private CamelProxy camelProxy;
88     protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger();
89     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsService.class);
90
91     public static final String GLOBAL_PROPERTIES_KEY = "files.globalProperties";
92     private final String cldsPermissionTypeClManage;
93     private final String cldsPermissionTypeClEvent;
94     private final String cldsPermissionTypeFilterVf;
95     private final String cldsPermissionInstance;
96     final SecureServicePermission permissionReadCl;
97     final SecureServicePermission permissionUpdateCl;
98     final SecureServicePermission permissionReadTemplate;
99     final SecureServicePermission permissionUpdateTemplate;
100     final SecureServicePermission permissionReadTosca;
101     final SecureServicePermission permissionUpdateTosca;
102
103     private final CldsDao cldsDao;
104     private final XslTransformer cldsBpmnTransformer;
105     private final ClampProperties refProp;
106     private final DcaeDispatcherServices dcaeDispatcherServices;
107     private final DcaeInventoryServices dcaeInventoryServices;
108     private LoggingUtils util = new LoggingUtils(logger);
109
110     @Autowired
111     private HttpServletRequest request;
112
113     @Autowired
114     public CldsService(CldsDao cldsDao, XslTransformer cldsBpmnTransformer, ClampProperties refProp,
115         DcaeDispatcherServices dcaeDispatcherServices,
116         DcaeInventoryServices dcaeInventoryServices,
117         @Value("${clamp.config.security.permission.type.cl:permission-type-cl}") String cldsPersmissionTypeCl,
118         @Value("${clamp.config.security.permission.type.cl.manage:permission-type-cl-manage}") String cldsPermissionTypeClManage,
119         @Value("${clamp.config.security.permission.type.cl.event:permission-type-cl-event}") String cldsPermissionTypeClEvent,
120         @Value("${clamp.config.security.permission.type.filter.vf:permission-type-filter-vf}") String cldsPermissionTypeFilterVf,
121         @Value("${clamp.config.security.permission.type.template:permission-type-template}") String cldsPermissionTypeTemplate,
122         @Value("${clamp.config.security.permission.type.tosca:permission-type-tosca}") String cldsPermissionTypeTosca,
123         @Value("${clamp.config.security.permission.instance:dev}") String cldsPermissionInstance) {
124         this.cldsDao = cldsDao;
125         this.cldsBpmnTransformer = cldsBpmnTransformer;
126         this.refProp = refProp;
127         this.dcaeDispatcherServices = dcaeDispatcherServices;
128         this.dcaeInventoryServices = dcaeInventoryServices;
129         this.cldsPermissionTypeClManage = cldsPermissionTypeClManage;
130         this.cldsPermissionTypeClEvent = cldsPermissionTypeClEvent;
131         this.cldsPermissionTypeFilterVf = cldsPermissionTypeFilterVf;
132         this.cldsPermissionInstance = cldsPermissionInstance;
133         permissionReadCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "read");
134         permissionUpdateCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "update");
135         permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
136             "read");
137         permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
138             "update");
139         permissionReadTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "read");
140         permissionUpdateTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance,
141             "update");
142     }
143
144     /*
145      * @return list of CLDS-Monitoring-Details: CLOSELOOP_NAME | Close loop name
146      * used in the CLDS application (prefix: ClosedLoop- + unique ClosedLoop ID)
147      * MODEL_NAME | Model Name in CLDS application SERVICE_TYPE_ID | TypeId returned
148      * from the DCAE application when the ClosedLoop is submitted
149      * (DCAEServiceTypeRequest generated in DCAE application). DEPLOYMENT_ID | Id
150      * generated when the ClosedLoop is deployed in DCAE. TEMPLATE_NAME | Template
151      * used to generate the ClosedLoop model. ACTION_CD | Current state of the
152      * ClosedLoop in CLDS application.
153      */
154     public List<CldsMonitoringDetails> getCldsDetails() {
155         util.entering(request, "CldsService: GET model details");
156         Date startTime = new Date();
157         List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCLDSMonitoringDetails();
158         // audit log
159         LoggingUtils.setTimeContext(startTime, new Date());
160         auditLogger.info("GET cldsDetails completed");
161         util.exiting("200", "Get cldsDetails success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
162         return cldsMonitoringDetailsList;
163     }
164
165     /*
166      * CLDS IFO service will return 3 things 1. User Name 2. CLDS code version that
167      * is currently installed from pom.xml file 3. User permissions
168      */
169     public CldsInfo getCldsInfo() {
170         util.entering(request, "CldsService: GET cldsInfo");
171         Date startTime = new Date();
172         LoggingUtils.setTimeContext(startTime, new Date());
173
174         CldsInfoProvider cldsInfoProvider = new CldsInfoProvider(this);
175         CldsInfo cldsInfo = cldsInfoProvider.getCldsInfo();
176
177         // audit log
178         LoggingUtils.setTimeContext(startTime, new Date());
179         securityLogger.info("GET cldsInfo completed");
180         util.exiting("200", "Get cldsInfo success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
181         return cldsInfo;
182     }
183
184     /**
185      * REST service that retrieves BPMN for a CLDS model name from the database.
186      * This is subset of the json getModel. This is only expected to be used for
187      * testing purposes, not by the UI.
188      *
189      * @param modelName
190      * @return bpmn xml text - content of bpmn given name
191      */
192     public String getBpmnXml(String modelName) {
193         util.entering(request, "CldsService: GET model bpmn");
194         Date startTime = new Date();
195         isAuthorized(permissionReadCl);
196         logger.info("GET bpmnText for modelName={}", modelName);
197         CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
198         // audit log
199         LoggingUtils.setTimeContext(startTime, new Date());
200         auditLogger.info("GET model bpmn completed");
201         util.exiting("200", "Get model bpmn success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
202         return model.getBpmnText();
203     }
204
205     /**
206      * REST service that retrieves image for a CLDS model name from the database.
207      * This is subset of the json getModel. This is only expected to be used for
208      * testing purposes, not by the UI.
209      *
210      * @param modelName
211      * @return image xml text - content of image given name
212      */
213     public String getImageXml(String modelName) {
214         util.entering(request, "CldsService: GET model image");
215         Date startTime = new Date();
216         isAuthorized(permissionReadCl);
217         logger.info("GET imageText for modelName={}", modelName);
218         CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
219         // audit log
220         LoggingUtils.setTimeContext(startTime, new Date());
221         auditLogger.info("GET model image completed");
222         util.exiting("200", "Get model image success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
223         return model.getImageText();
224     }
225
226     /**
227      * REST service that retrieves a CLDS model by name from the database.
228      *
229      * @param modelName
230      * @return clds model - clds model for the given model name
231      */
232     public CldsModel getModel(String modelName) {
233         util.entering(request, "CldsService: GET model");
234         Date startTime = new Date();
235         isAuthorized(permissionReadCl);
236         logger.debug("GET model for  modelName={}", modelName);
237         CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false);
238         isAuthorizedForVf(cldsModel);
239         // Try an update for DCAE status
240         // Checking condition whether our CLDS model can call Inventory Method
241         try {
242             // Method to call dcae inventory and invoke insert event method
243             if (cldsModel.canDcaeInventoryCall()
244                 && !cldsModel.getTemplateName().startsWith(CsarInstallerImpl.TEMPLATE_NAME_PREFIX)) {
245                 dcaeInventoryServices.setEventInventory(cldsModel, getUserId());
246             }
247             // This is a blocking call
248             if (cldsModel.getEvent().isActionCd(CldsEvent.ACTION_DEPLOY)
249                 && !CldsModel.STATUS_ACTIVE.equals(cldsModel.getStatus()) && cldsModel.getDeploymentId() != null
250                 && cldsModel.getDeploymentStatusUrl() != null) {
251                 checkDcaeDeploymentStatus(cldsModel, CldsEvent.ACTION_DEPLOY, false);
252                 // Refresh the model object in any cases for new event
253                 cldsModel = CldsModel.retrieve(cldsDao, cldsModel.getName(), false);
254             }
255         } catch (Exception e) {
256             LoggingUtils.setErrorContext("900", "Set event inventory error");
257             logger.error("getModel set event Inventory error:" + e);
258         }
259         // audit log
260         LoggingUtils.setTimeContext(startTime, new Date());
261         auditLogger.info("GET model completed");
262         util.exiting("200", "Get model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
263         return cldsModel;
264     }
265
266     /**
267      * REST service that saves a CLDS model by name in the database.
268      *
269      * @param modelName
270      */
271     public CldsModel putModel(String modelName, CldsModel cldsModel) {
272         util.entering(request, "CldsService: PUT model");
273         Date startTime = new Date();
274         isAuthorized(permissionUpdateCl);
275         isAuthorizedForVf(cldsModel);
276         logger.info("PUT model for  modelName={}", modelName);
277         logger.info("PUT bpmnText={}", cldsModel.getBpmnText());
278         logger.info("PUT propText={}", cldsModel.getPropText());
279         logger.info("PUT imageText={}", cldsModel.getImageText());
280         fillInCldsModel(cldsModel);
281         cldsModel.save(cldsDao, getUserId());
282
283         // audit log
284         LoggingUtils.setTimeContext(startTime, new Date());
285         auditLogger.info("PUT model completed");
286         util.exiting("200", "Put model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
287         return cldsModel;
288     }
289
290     /**
291      * REST service that retrieves a list of CLDS model names.
292      *
293      * @return model names in JSON
294      */
295     public List<ValueItem> getModelNames() {
296         util.entering(request, "CldsService: GET model names");
297         Date startTime = new Date();
298         isAuthorized(permissionReadCl);
299         logger.info("GET list of model names");
300         List<ValueItem> names = cldsDao.getModelNames();
301         // audit log
302         LoggingUtils.setTimeContext(startTime, new Date());
303         auditLogger.info("GET model names completed");
304         util.exiting("200", "Get model names success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
305         return names;
306     }
307
308     private void fillInCldsModel(CldsModel model) {
309         if (model.getTemplateName() != null) {
310             CldsTemplate template = cldsDao.getTemplate(model.getTemplateName());
311             if (template != null) {
312                 model.setTemplateId(template.getId());
313                 model.setDocText(template.getPropText());
314                 // This is to provide the Bpmn XML when Template part in UI
315                 // is
316                 // disabled
317                 model.setBpmnText(template.getBpmnText());
318             }
319         }
320     }
321
322     /**
323      * REST service that saves and processes an action for a CLDS model by name.
324      *
325      * @param action
326      * @param modelName
327      * @param test
328      * @param model
329      * @return
330      * @throws TransformerException
331      *         In case of issues when doing the XSLT of the BPMN flow
332      * @throws ParseException
333      *         In case of issues when parsing the JSON
334      * @throws GeneralSecurityException
335      *         In case of issues when decrypting the password
336      * @throws DecoderException
337      *         In case of issues with the Hex String decoding
338      */
339     public ResponseEntity<?> putModelAndProcessAction(String action, String modelName, String test, CldsModel model)
340         throws TransformerException, ParseException {
341         util.entering(request, "CldsService: Process model action");
342         Date startTime = new Date();
343         String errorMessage = "";
344         String actionCd = "";
345         try {
346             actionCd = action.toUpperCase();
347             SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
348                 cldsPermissionInstance, actionCd);
349             isAuthorized(permisionManage);
350             isAuthorizedForVf(model);
351             String userId = getUserId();
352             logger.info("PUT actionCd={}", actionCd);
353             logger.info("PUT modelName={}", modelName);
354             logger.info("PUT test={}", test);
355             logger.info("PUT bpmnText={}", model.getBpmnText());
356             logger.info("PUT propText={}", model.getPropText());
357             logger.info("PUT userId={}", userId);
358             logger.info("PUT getTypeId={}", model.getTypeId());
359             logger.info("PUT deploymentId={}", model.getDeploymentId());
360             this.fillInCldsModel(model);
361             // save model to db just in case
362             model.save(cldsDao, getUserId());
363
364             // get vars and format if necessary
365             String prop = model.getPropText();
366             String bpmn = model.getBpmnText();
367             String docText = model.getDocText();
368             String controlName = model.getControlName();
369             String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn);
370             logger.info("PUT bpmnJson={}", bpmnJson);
371             // Test flag coming from UI or from Clamp config
372             boolean isTest = Boolean.parseBoolean(test)
373                 || Boolean.parseBoolean(refProp.getStringValue("action.test.override"));
374             logger.info("PUT isTest={}", isTest);
375             boolean isInsertTestEvent = Boolean.parseBoolean(refProp.getStringValue("action.insert.test.event"));
376             logger.info("PUT isInsertTestEvent={}", isInsertTestEvent);
377             // determine if requested action is permitted
378             model.validateAction(actionCd);
379             logger.info("modelProp - " + prop);
380             logger.info("docText - " + docText);
381             try {
382                 String result = camelProxy.executeAction(actionCd, prop, bpmnJson, modelName, controlName, docText,
383                     isTest, userId, isInsertTestEvent, model.getEvent().getActionCd());
384                 logger.info("Starting Camel flow on request, result is: ", result);
385             } catch (SdcCommunicationException | PolicyClientException | BadRequestException e) {
386                 logger.error("Exception occured during invoking Camel process", e);
387                 errorMessage = e.getMessage();
388             }
389             // audit log
390             LoggingUtils.setTimeContext(startTime, new Date());
391             auditLogger.info("Process model action completed");
392         } catch (Exception e) {
393             logger.error("Exception occured during putModelAndProcessAction", e);
394             errorMessage = e.getMessage();
395         }
396
397         if (null == errorMessage || (null != errorMessage && !errorMessage.isEmpty())) {
398             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), actionCd, CldsEvent.ACTION_STATE_ERROR,
399                 null);
400             // Need a refresh as new events have been inserted
401             model = CldsModel.retrieve(cldsDao, modelName, false);
402             if (null == errorMessage) {
403                 errorMessage = "No response from Policy";
404             }
405             model.setErrorMessageForUi(errorMessage);
406             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "putModelAndProcessAction failed", Level.INFO,
407                 ONAPLogConstants.ResponseStatus.ERROR);
408             return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR);
409         } else {
410             // Need a refresh as new events have been inserted, could have been deleted so
411             // not blocking call
412             model = CldsModel.retrieve(cldsDao, modelName, true);
413             util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
414             return new ResponseEntity<>(model, HttpStatus.OK);
415         }
416     }
417
418     /**
419      * REST service that accepts events for a model.
420      *
421      * @param test
422      * @param dcaeEvent
423      */
424     public String postDcaeEvent(String test, DcaeEvent dcaeEvent) {
425         util.entering(request, "CldsService: Post dcae event");
426         Date startTime = new Date();
427         String userid = null;
428         // TODO: allow auth checking to be turned off by removing the permission
429         // type property
430         if (cldsPermissionTypeClEvent != null && cldsPermissionTypeClEvent.length() > 0) {
431             SecureServicePermission permissionEvent = SecureServicePermission.create(cldsPermissionTypeClEvent,
432                 cldsPermissionInstance, dcaeEvent.getEvent());
433             isAuthorized(permissionEvent);
434             userid = getUserId();
435         }
436         // Flag indicates whether it is triggered by Validation Test button from
437         // UI
438         boolean isTest = Boolean.parseBoolean(test);
439         int instanceCount = 0;
440         if (dcaeEvent.getInstances() != null) {
441             instanceCount = dcaeEvent.getInstances().size();
442         }
443         String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID()
444             + " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName()
445             + " instance count=" + instanceCount + " isTest=" + isTest;
446         logger.info("POST dcae event {}", msgInfo);
447         if (isTest) {
448             logger.warn("Ignorning test event from DCAE");
449         } else {
450             if (DcaeEvent.EVENT_DEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent())) {
451                 CldsModel.insertModelInstance(cldsDao, dcaeEvent, userid);
452             } else {
453                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(),
454                     CldsEvent.ACTION_STATE_RECEIVED, null);
455             }
456         }
457         // audit log
458         LoggingUtils.setTimeContext(startTime, new Date());
459         auditLogger.info("Post dcae event completed");
460         util.exiting("200", "Post dcae event success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
461         return msgInfo;
462     }
463
464     /**
465      * REST service that retrieves total properties required by UI
466      *
467      * @throws IOException
468      *         In case of issues
469      */
470     public String getSdcProperties() throws IOException {
471         return refProp.getJsonTemplate(GLOBAL_PROPERTIES_KEY).toString();
472     }
473
474
475     /**
476      * Determine if the user is authorized for a particular VF by its invariant
477      * UUID.
478      *
479      * @param vfInvariantUuid
480      * @throws NotAuthorizedException
481      * @return
482      */
483     public boolean isAuthorizedForVf(String vfInvariantUuid) {
484         if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) {
485             SecureServicePermission permission = SecureServicePermission.create(cldsPermissionTypeFilterVf,
486                 cldsPermissionInstance, vfInvariantUuid);
487             return isAuthorized(permission);
488         } else {
489             // if CLDS_PERMISSION_TYPE_FILTER_VF property is not provided, then
490             // VF filtering is turned off
491             logger.warn("VF filtering turned off");
492             return true;
493         }
494     }
495
496     /**
497      * Determine if the user is authorized for a particular VF by its invariant
498      * UUID. If not authorized, then NotAuthorizedException is thrown.
499      *
500      * @param model
501      * @return
502      */
503     private boolean isAuthorizedForVf(CldsModel model) {
504         String vf = ModelProperties.getVf(model);
505         if (vf == null || vf.length() == 0) {
506             logger.info("VF not found in model");
507             return true;
508         } else {
509             return isAuthorizedForVf(vf);
510         }
511     }
512
513     public ResponseEntity<CldsModel> deployModel(String modelName, CldsModel model) {
514         util.entering(request, "CldsService: Deploy model");
515         Date startTime = new Date();
516         String errorMessage = "";
517         try {
518             fillInCldsModel(model);
519             String bpmnJson = cldsBpmnTransformer.doXslTransformToString(model.getBpmnText());
520             logger.info("PUT bpmnJson={}", bpmnJson);
521             SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
522                 cldsPermissionInstance, CldsEvent.ACTION_DEPLOY);
523             isAuthorized(permisionManage);
524             isAuthorizedForVf(model);
525             ModelProperties modelProp = new ModelProperties(modelName, model.getControlName(), CldsEvent.ACTION_DEPLOY,
526                 false, bpmnJson, model.getPropText());
527             checkForDuplicateServiceVf(modelName, model.getPropText());
528             String deploymentId = "";
529             // If model is already deployed then pass same deployment id
530             if (model.getDeploymentId() != null && !model.getDeploymentId().isEmpty()) {
531                 deploymentId = model.getDeploymentId();
532             } else {
533                 model.setDeploymentId(deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId");
534             }
535             model.setDeploymentStatusUrl(dcaeDispatcherServices.createNewDeployment(deploymentId, model.getTypeId(),
536                 modelProp.getGlobal().getDeployParameters()));
537             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), CldsEvent.ACTION_DEPLOY,
538                 CldsEvent.ACTION_STATE_INITIATED, null);
539             model.save(cldsDao, getUserId());
540             // This is a blocking call
541             checkDcaeDeploymentStatus(model, CldsEvent.ACTION_DEPLOY, true);
542             // Refresh the model object in any cases for new event
543             model = CldsModel.retrieve(cldsDao, model.getName(), false);
544             // audit log
545             LoggingUtils.setTimeContext(startTime, new Date());
546             auditLogger.info("Deploy model completed");
547         } catch (Exception e) {
548             errorMessage = e.getMessage();
549             logger.error("Exception occured during deployModel", e);
550         }
551         if (!errorMessage.isEmpty()) {
552             model.setErrorMessageForUi(errorMessage);
553             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DeployModel failed", Level.INFO,
554                 ONAPLogConstants.ResponseStatus.ERROR);
555             return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR);
556         } else {
557             util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
558             return new ResponseEntity<>(model, HttpStatus.OK);
559         }
560     }
561
562     public ResponseEntity<CldsModel> unDeployModel(String modelName, CldsModel model) {
563         util.entering(request, "CldsService: Undeploy model");
564         Date startTime = new Date();
565         String errorMessage = "";
566         try {
567             SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
568                 cldsPermissionInstance, CldsEvent.ACTION_UNDEPLOY);
569             isAuthorized(permisionManage);
570             isAuthorizedForVf(model);
571             model.setDeploymentStatusUrl(
572                 dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(), model.getTypeId()));
573             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), CldsEvent.ACTION_UNDEPLOY,
574                 CldsEvent.ACTION_STATE_INITIATED, null);
575             // clean the deployment ID
576             model.setDeploymentId(null);
577             model.save(cldsDao, getUserId());
578             // This is a blocking call
579             checkDcaeDeploymentStatus(model, CldsEvent.ACTION_UNDEPLOY, true);
580             // Refresh the model object in any cases for new event
581             model = CldsModel.retrieve(cldsDao, model.getName(), false);
582             // audit log
583             LoggingUtils.setTimeContext(startTime, new Date());
584             auditLogger.info("Undeploy model completed");
585         } catch (Exception e) {
586             errorMessage = e.getMessage();
587             logger.error("Exception occured during unDeployModel", e);
588         }
589         if (!errorMessage.isEmpty()) {
590             model.setErrorMessageForUi(errorMessage);
591             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "UndeployModel failed", Level.INFO,
592                 ONAPLogConstants.ResponseStatus.ERROR);
593             return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR);
594         } else {
595             util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
596             return new ResponseEntity<>(model, HttpStatus.OK);
597         }
598     }
599
600     private void checkDcaeDeploymentStatus(CldsModel model, String cldsEvent, boolean withRetry)
601         throws InterruptedException {
602         String operationStatus = withRetry
603             ? dcaeDispatcherServices.getOperationStatusWithRetry(model.getDeploymentStatusUrl())
604             : dcaeDispatcherServices.getOperationStatus(model.getDeploymentStatusUrl());
605         if ("succeeded".equalsIgnoreCase(operationStatus)) {
606             logger.info(cldsEvent + " model (" + model.getName() + ") succeeded...Deployment Id is - "
607                 + model.getDeploymentId());
608             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), cldsEvent,
609                 CldsEvent.ACTION_STATE_COMPLETED, null);
610         } else {
611             String info = "DCAE " + cldsEvent + " (" + model.getName() + ") failed...Operation Status is - "
612                 + operationStatus;
613             logger.info(info);
614             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), cldsEvent, CldsEvent.ACTION_STATE_ERROR,
615                 null);
616             util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DCAE operation(" + cldsEvent + ") failed",
617                 Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
618             throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, info);
619         }
620     }
621
622     private void checkForDuplicateServiceVf(String modelName, String modelPropText) throws IOException {
623         JsonElement globalNode = JsonUtils.GSON.fromJson(modelPropText, JsonObject.class).get("global");
624         String service = JsonUtils.getStringValueByName(globalNode, "service");
625         List<String> resourceVf = JsonUtils.getStringValuesByName(globalNode, "vf");
626         if (service != null && resourceVf != null && !resourceVf.isEmpty()) {
627             List<CldsModelProp> cldsModelPropList = cldsDao.getDeployedModelProperties();
628             for (CldsModelProp cldsModelProp : cldsModelPropList) {
629                 JsonElement currentNode = JsonUtils.GSON
630                     .fromJson(cldsModelProp.getPropText(), JsonObject.class)
631                     .get("global");
632                 String currentService = JsonUtils.getStringValueByName(currentNode, "service");
633                 List<String> currentVf = JsonUtils.getStringValuesByName(currentNode, "vf");
634                 if (currentVf != null && !currentVf.isEmpty()) {
635                     if (!modelName.equalsIgnoreCase(cldsModelProp.getName()) && service.equalsIgnoreCase(currentService)
636                         && resourceVf.get(0).equalsIgnoreCase(currentVf.get(0))) {
637                         throw new BadRequestException("Same Service/VF already exists in " + cldsModelProp.getName()
638                             + " model, please select different Service/VF.");
639                     }
640                 }
641             }
642         }
643     }
644
645     // Created for the integration test
646     public void setLoggingUtil(LoggingUtils utilP) {
647         util = utilP;
648     }
649 }