Rework some sonar critical and major bugs
[clamp.git] / src / main / java / org / onap / clamp / clds / service / CldsService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23
24 package org.onap.clamp.clds.service;
25
26 import com.att.ajsc.common.AjscService;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.fasterxml.jackson.databind.node.ObjectNode;
30
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.util.Date;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Properties;
38 import java.util.UUID;
39 import java.util.concurrent.TimeUnit;
40
41 import javax.annotation.PostConstruct;
42 import javax.ws.rs.Consumes;
43 import javax.ws.rs.DefaultValue;
44 import javax.ws.rs.GET;
45 import javax.ws.rs.NotAuthorizedException;
46 import javax.ws.rs.POST;
47 import javax.ws.rs.PUT;
48 import javax.ws.rs.Path;
49 import javax.ws.rs.PathParam;
50 import javax.ws.rs.Produces;
51 import javax.ws.rs.QueryParam;
52 import javax.ws.rs.core.MediaType;
53 import javax.xml.transform.TransformerException;
54
55 import org.apache.commons.lang3.StringUtils;
56 import org.camunda.bpm.engine.RuntimeService;
57 import org.camunda.bpm.engine.runtime.ProcessInstance;
58 import org.json.simple.parser.ParseException;
59 import org.onap.clamp.clds.client.DcaeDispatcherServices;
60 import org.onap.clamp.clds.client.DcaeInventoryServices;
61 import org.onap.clamp.clds.client.SdcCatalogServices;
62 import org.onap.clamp.clds.dao.CldsDao;
63 import org.onap.clamp.clds.exception.CldsConfigException;
64 import org.onap.clamp.clds.exception.SdcCommunicationException;
65 import org.onap.clamp.clds.model.CldsDBServiceCache;
66 import org.onap.clamp.clds.model.CldsEvent;
67 import org.onap.clamp.clds.model.CldsHealthCheck;
68 import org.onap.clamp.clds.model.CldsInfo;
69 import org.onap.clamp.clds.model.CldsModel;
70 import org.onap.clamp.clds.model.CldsSdcResource;
71 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
72 import org.onap.clamp.clds.model.CldsSdcServiceInfo;
73 import org.onap.clamp.clds.model.CldsServiceData;
74 import org.onap.clamp.clds.model.CldsTemplate;
75 import org.onap.clamp.clds.model.DcaeEvent;
76 import org.onap.clamp.clds.model.ValueItem;
77 import org.onap.clamp.clds.model.prop.ModelProperties;
78 import org.onap.clamp.clds.model.refprop.RefProp;
79 import org.onap.clamp.clds.transform.XslTransformer;
80 import org.onap.clamp.clds.util.LoggingUtils;
81 import org.springframework.beans.factory.annotation.Autowired;
82 import org.springframework.beans.factory.annotation.Value;
83 import org.springframework.context.ApplicationContext;
84 import org.springframework.http.HttpStatus;
85 import org.springframework.web.client.HttpClientErrorException;
86
87 import io.swagger.annotations.Api;
88 import io.swagger.annotations.ApiOperation;
89
90 /**
91  * Service to save and retrieve the CLDS model attributes.
92  */
93 @AjscService
94 @Api(value = "/clds")
95 @Path("/clds")
96 public class CldsService extends SecureServiceBase {
97
98     @Autowired
99     private ApplicationContext      appContext;
100
101     private static final String     RESOURCE_NAME = "clds-version.properties";
102
103     @Value("${CLDS_PERMISSION_TYPE_CL:permission-type-cl}")
104     private String                  cldsPersmissionTypeCl;
105
106     @Value("${CLDS_PERMISSION_TYPE_CL_MANAGE:permission-type-cl-manage}")
107     private String                  cldsPermissionTypeClManage;
108
109     @Value("${CLDS_PERMISSION_TYPE_CL_EVENT:permission-type-cl-event}")
110     private String                  cldsPermissionTypeClEvent;
111
112     @Value("${CLDS_PERMISSION_TYPE_FILTER_VF:permission-type-filter-vf}")
113     private String                  cldsPermissionTypeFilterVf;
114
115     @Value("${CLDS_PERMISSION_TYPE_TEMPLATE:permission-type-template}")
116     private String                  cldsPermissionTypeTemplate;
117
118     @Value("${CLDS_PERMISSION_INSTANCE:dev}")
119     private String                  cldsPermissionInstance;
120
121     private SecureServicePermission permissionReadCl;
122
123     private SecureServicePermission permissionUpdateCl;
124
125     private SecureServicePermission permissionReadTemplate;
126
127     private SecureServicePermission permissionUpdateTemplate;
128
129     @PostConstruct
130     private final void afterConstruction() {
131         permissionReadCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "read");
132         permissionUpdateCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "update");
133         permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
134                 "read");
135         permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
136                 "update");
137     }
138
139     @Value("${org.onap.clamp.config.files.globalClds:'classpath:/clds/globalClds.properties'}")
140     private String                 globalClds;
141
142     private Properties             globalCldsProperties;
143
144     @Autowired
145     private CldsDao                cldsDao;
146     @Autowired
147     private RuntimeService         runtimeService;
148     @Autowired
149     private XslTransformer         cldsBpmnTransformer;
150
151     @Autowired
152     private RefProp                refProp;
153
154     @Autowired
155     private SdcCatalogServices     sdcCatalogServices;
156
157     @Autowired
158     private DcaeDispatcherServices dcaeDispatcherServices;
159
160     @Autowired
161     private DcaeInventoryServices  dcaeInventoryServices;
162
163     public CldsService() {
164     }
165
166     public CldsService(RefProp refProp) {
167         this.refProp = refProp;
168     }
169
170     /*
171      *
172      * CLDS IFO service will return 3 things 1. User Name 2. CLDS code version
173      * that is currently installed from pom.xml file 3. User permissions
174      *
175      */
176
177     @GET
178     @Path("/cldsInfo")
179     @Produces(MediaType.APPLICATION_JSON)
180     public CldsInfo getCldsInfo() {
181
182         CldsInfo cldsInfo = new CldsInfo();
183
184         // Get the user info
185         cldsInfo.setUserName(getUserName());
186
187         // Get CLDS application version
188         String cldsVersion = "";
189         Properties props = new Properties();
190
191         ClassLoader loader = Thread.currentThread().getContextClassLoader();
192
193         try (InputStream resourceStream = loader.getResourceAsStream(RESOURCE_NAME)) {
194             props.load(resourceStream);
195             cldsVersion = props.getProperty("clds.version");
196         } catch (Exception ex) {
197             logger.error("Exception caught during the clds.version reading", ex);
198         }
199         cldsInfo.setCldsVersion(cldsVersion);
200
201         // Get the user list of permissions
202         cldsInfo.setPermissionReadCl(isAuthorizedNoException(permissionReadCl));
203         cldsInfo.setPermissionUpdateCl(isAuthorizedNoException(permissionUpdateCl));
204         cldsInfo.setPermissionReadTemplate(isAuthorizedNoException(permissionReadTemplate));
205         cldsInfo.setPermissionUpdateTemplate(isAuthorizedNoException(permissionUpdateTemplate));
206         return cldsInfo;
207     }
208
209     @GET
210     @Path("/healthcheck")
211     @Produces(MediaType.APPLICATION_JSON)
212     public CldsHealthCheck gethealthcheck() {
213
214         CldsHealthCheck cldsHealthCheck = new CldsHealthCheck();
215
216         try {
217             cldsDao.doHealthCheck();
218             cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
219             cldsHealthCheck.setHealthCheckStatus("UP");
220             cldsHealthCheck.setDescription("OK");
221         } catch (Exception e) {
222             logger.error("CLAMP application DB Error", e);
223             cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
224             cldsHealthCheck.setHealthCheckStatus("DOWN");
225             cldsHealthCheck.setDescription("NOT-OK");
226         }
227         return cldsHealthCheck;
228
229     }
230
231     /**
232      * REST service that retrieves BPMN for a CLDS model name from the database.
233      * This is subset of the json getModel. This is only expected to be used for
234      * testing purposes, not by the UI.
235      *
236      * @param modelName
237      * @return bpmn xml text - content of bpmn given name
238      */
239     @ApiOperation(value = "Retrieves BPMN for a CLDS model name from the database", notes = "This is only expected to be used for testing purposes, not by the UI", response = String.class)
240     @GET
241     @Path("/model/bpmn/{modelName}")
242     @Produces(MediaType.TEXT_XML)
243     public String getBpmnXml(@PathParam("modelName") String modelName) {
244         Date startTime = new Date();
245         LoggingUtils.setRequestContext("CldsService: GET model bpmn", getPrincipalName());
246         isAuthorized(permissionReadCl);
247         logger.info("GET bpmnText for modelName={}", modelName);
248         CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
249         // audit log
250         LoggingUtils.setTimeContext(startTime, new Date());
251         LoggingUtils.setResponseContext("0", "Get model bpmn success", this.getClass().getName());
252         auditLogger.info("GET model bpmn completed");
253         return model.getBpmnText();
254     }
255
256     /**
257      * REST service that saves BPMN for a CLDS model by name in the database.
258      * This is subset of the json putModel. This is only expected to be used for
259      * testing purposes, not by the UI.
260      *
261      * @param modelName
262      */
263     @ApiOperation(value = "Saves BPMN for a CLDS model by name in the database", notes = "This is only expected to be used for testing purposes, not by the UI", response = String.class)
264     @PUT
265     @Path("/model/bpmn/{modelName}")
266     @Consumes(MediaType.TEXT_XML)
267     public String putBpmnXml(@PathParam("modelName") String modelName, String bpmnText) {
268         LoggingUtils.setRequestContext("CldsService: PUT model bpmn", getPrincipalName());
269         isAuthorized(permissionUpdateCl);
270         logger.info("PUT bpmnText for modelName={}", modelName);
271         logger.info("PUT bpmnText={}", bpmnText);
272         CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, true);
273         cldsModel.setBpmnText(bpmnText);
274         cldsModel.save(cldsDao, getUserId());
275         // audit log
276         LoggingUtils.setTimeContext(new Date(), new Date());
277         LoggingUtils.setResponseContext("0", "Put model bpmn success", this.getClass().getName());
278         auditLogger.info("PUT model bpmn completed");
279         return "wrote bpmnText for modelName=" + modelName;
280     }
281
282     /**
283      * REST service that retrieves image for a CLDS model name from the
284      * database. This is subset of the json getModel. This is only expected to
285      * be used for testing purposes, not by the UI.
286      *
287      * @param modelName
288      * @return image xml text - content of image given name
289      */
290     @ApiOperation(value = "Retrieves image for a CLDS model name from the database", notes = "This is only expected to be used for testing purposes, not by the UI", response = String.class)
291     @GET
292     @Path("/model/image/{modelName}")
293     @Produces(MediaType.TEXT_XML)
294     public String getImageXml(@PathParam("modelName") String modelName) {
295         Date startTime = new Date();
296         LoggingUtils.setRequestContext("CldsService: GET model image", getPrincipalName());
297         isAuthorized(permissionReadCl);
298         logger.info("GET imageText for modelName={}", modelName);
299         CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
300         // audit log
301         LoggingUtils.setTimeContext(startTime, new Date());
302         LoggingUtils.setResponseContext("0", "Get model image success", this.getClass().getName());
303         auditLogger.info("GET model image completed");
304         return model.getImageText();
305     }
306
307     /**
308      * REST service that saves image for a CLDS model by name in the database.
309      * This is subset of the json putModel. This is only expected to be used for
310      * testing purposes, not by the UI.
311      *
312      * @param modelName
313      */
314     @ApiOperation(value = "Saves image for a CLDS model by name in the database", notes = "This is only expected to be used for testing purposes, not by the UI", response = String.class)
315     @PUT
316     @Path("/model/image/{modelName}")
317     @Consumes(MediaType.TEXT_XML)
318     public String putImageXml(@PathParam("modelName") String modelName, String imageText) {
319         Date startTime = new Date();
320         LoggingUtils.setRequestContext("CldsService: PUT model image", getPrincipalName());
321         isAuthorized(permissionUpdateCl);
322         logger.info("PUT iamgeText for modelName={}", modelName);
323         logger.info("PUT imageText={}", imageText);
324         CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, true);
325         cldsModel.setImageText(imageText);
326         cldsModel.save(cldsDao, getUserId());
327         // audit log
328         LoggingUtils.setTimeContext(startTime, new Date());
329         LoggingUtils.setResponseContext("0", "Put model image success", this.getClass().getName());
330         auditLogger.info("PUT model image completed");
331         return "wrote imageText for modelName=" + modelName;
332     }
333
334     /**
335      * REST service that retrieves a CLDS model by name from the database.
336      *
337      * @param modelName
338      * @return clds model - clds model for the given model name
339      */
340     @ApiOperation(value = "Retrieves a CLDS model by name from the database", notes = "", response = String.class)
341     @GET
342     @Path("/model/{modelName}")
343     @Produces(MediaType.APPLICATION_JSON)
344     public CldsModel getModel(@PathParam("modelName") String modelName) {
345         Date startTime = new Date();
346         LoggingUtils.setRequestContext("CldsService: GET model", getPrincipalName());
347         isAuthorized(permissionReadCl);
348         logger.debug("GET model for  modelName={}", modelName);
349         CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false);
350         isAuthorizedForVf(cldsModel);
351         cldsModel.setUserAuthorizedToUpdate(isAuthorizedNoException(permissionUpdateCl));
352
353         /**
354          * Checking condition whether our CLDS model can call INventory Method
355          */
356         if (cldsModel.canInventoryCall()) {
357             try {
358                 /*
359                  * Below is the method to for inventory call and DB insert for
360                  * event methods
361                  */
362                 dcaeInventoryServices.setEventInventory(cldsModel, getUserId());
363             } catch (Exception e) {
364                 LoggingUtils.setErrorContext("900", "Set event inventory error");
365                 logger.error("getModel set event Inventory error:" + e);
366             }
367         }
368         // audit log
369         LoggingUtils.setTimeContext(startTime, new Date());
370         LoggingUtils.setResponseContext("0", "Get model success", this.getClass().getName());
371         auditLogger.info("GET model completed");
372         return cldsModel;
373     }
374
375     /**
376      * REST service that saves a CLDS model by name in the database.
377      *
378      * @param modelName
379      */
380     @ApiOperation(value = "Saves a CLDS model by name in the database", notes = "", response = String.class)
381     @PUT
382     @Path("/model/{modelName}")
383     @Consumes(MediaType.APPLICATION_JSON)
384     @Produces(MediaType.APPLICATION_JSON)
385     public CldsModel putModel(@PathParam("modelName") String modelName, CldsModel cldsModel) {
386         Date startTime = new Date();
387         LoggingUtils.setRequestContext("CldsService: PUT model", getPrincipalName());
388         isAuthorized(permissionUpdateCl);
389         isAuthorizedForVf(cldsModel);
390         logger.info("PUT model for  modelName={}", modelName);
391         logger.info("PUT bpmnText={}", cldsModel.getBpmnText());
392         logger.info("PUT propText={}", cldsModel.getPropText());
393         logger.info("PUT imageText={}", cldsModel.getImageText());
394         cldsModel.setName(modelName);
395
396         if (cldsModel.getTemplateName() != null) {
397             CldsTemplate template = cldsDao.getTemplate(cldsModel.getTemplateName());
398             if (template != null) {
399                 cldsModel.setTemplateId(template.getId());
400                 cldsModel.setDocText(template.getPropText());
401                 cldsModel.setDocId(template.getPropId());
402             }
403         }
404         cldsModel.save(cldsDao, getUserId());
405         cldsModel.save(cldsDao, getUserId());
406         // audit log
407         LoggingUtils.setTimeContext(startTime, new Date());
408         LoggingUtils.setResponseContext("0", "Put model success", this.getClass().getName());
409         auditLogger.info("PUT model completed");
410         return cldsModel;
411     }
412
413     /**
414      * REST service that retrieves a list of CLDS model names.
415      *
416      * @return model names in JSON
417      */
418     @ApiOperation(value = "Retrieves a list of CLDS model names", notes = "", response = String.class)
419     @GET
420     @Path("/model-names")
421     @Produces(MediaType.APPLICATION_JSON)
422     public List<ValueItem> getModelNames() {
423         Date startTime = new Date();
424         LoggingUtils.setRequestContext("CldsService: GET model names", getPrincipalName());
425         isAuthorized(permissionReadCl);
426         logger.info("GET list of model names");
427         List<ValueItem> names = cldsDao.getBpmnNames();
428         // audit log
429         LoggingUtils.setTimeContext(startTime, new Date());
430         LoggingUtils.setResponseContext("0", "Get model names success", this.getClass().getName());
431         auditLogger.info("GET model names completed");
432         return names;
433     }
434
435     /**
436      * REST service that saves and processes an action for a CLDS model by name.
437      *
438      * @param action
439      * @param modelName
440      * @param test
441      * @param model
442      * @return
443      * @throws TransformerException
444      * @throws ParseException
445      */
446     @ApiOperation(value = "Saves and processes an action for a CLDS model by name", notes = "", response = String.class)
447     @PUT
448     @Path("/action/{action}/{modelName}")
449     @Consumes(MediaType.APPLICATION_JSON)
450     @Produces(MediaType.APPLICATION_JSON)
451     public CldsModel putModelAndProcessAction(@PathParam("action") String action,
452             @PathParam("modelName") String modelName, @QueryParam("test") String test, CldsModel model)
453             throws TransformerException, ParseException {
454         Date startTime = new Date();
455         LoggingUtils.setRequestContext("CldsService: Process model action", getPrincipalName());
456         String actionCd = action.toUpperCase();
457         SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
458                 cldsPermissionInstance, actionCd);
459         isAuthorized(permisionManage);
460         isAuthorizedForVf(model);
461         String userid = getUserId();
462         String actionStateCd = CldsEvent.ACTION_STATE_INITIATED;
463         String processDefinitionKey = "clds-process-action-wf";
464
465         logger.info("PUT actionCd={}", actionCd);
466         logger.info("PUT actionStateCd={}", actionStateCd);
467         logger.info("PUT processDefinitionKey={}", processDefinitionKey);
468         logger.info("PUT modelName={}", modelName);
469         logger.info("PUT test={}", test);
470         logger.info("PUT bpmnText={}", model.getBpmnText());
471         logger.info("PUT propText={}", model.getPropText());
472         logger.info("PUT userid={}", userid);
473         logger.info("PUT getTypeId={}", model.getTypeId());
474         logger.info("PUT deploymentId={}", model.getDeploymentId());
475
476         if (model.getTemplateName() != null) {
477             CldsTemplate template = cldsDao.getTemplate(model.getTemplateName());
478             if (template != null) {
479                 model.setTemplateId(template.getId());
480                 model.setDocText(template.getPropText());
481                 model.setDocId(template.getPropId());
482             }
483         }
484         // save model to db
485         model.setName(modelName);
486         model.save(cldsDao, getUserId());
487
488         // get vars and format if necessary
489         String prop = model.getPropText();
490         String bpmn = model.getBpmnText();
491         String docText = model.getDocText();
492         String controlName = model.getControlName();
493
494         String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn);
495         logger.info("PUT bpmnJson={}", bpmnJson);
496
497         // Flag indicates whether it is triggered by Validation Test button from
498         // UI
499         boolean isTest = false;
500         if (test != null && test.equalsIgnoreCase("true")) {
501             isTest = true;
502         } else {
503             String actionTestOverride = refProp.getStringValue("action.test.override");
504             if (actionTestOverride != null && actionTestOverride.equalsIgnoreCase("true")) {
505                 logger.info("PUT actionTestOverride={}", actionTestOverride);
506                 logger.info("PUT override test indicator and setting it to true");
507                 isTest = true;
508             }
509         }
510         logger.info("PUT isTest={}", isTest);
511
512         boolean isInsertTestEvent = false;
513         String insertTestEvent = refProp.getStringValue("action.insert.test.event");
514         if (insertTestEvent != null && insertTestEvent.equalsIgnoreCase("true")) {
515             isInsertTestEvent = true;
516         }
517         logger.info("PUT isInsertTestEvent={}", isInsertTestEvent);
518
519         // determine if requested action is permitted
520         model.validateAction(actionCd);
521
522         // input variables to camunda process
523         Map<String, Object> variables = new HashMap<>();
524         variables.put("actionCd", actionCd);
525         variables.put("modelProp", prop.getBytes());
526         variables.put("modelBpmnProp", bpmnJson);
527         variables.put("modelName", modelName);
528         variables.put("controlName", controlName);
529         variables.put("docText", docText.getBytes());
530         variables.put("isTest", isTest);
531         variables.put("userid", userid);
532         variables.put("isInsertTestEvent", isInsertTestEvent);
533         logger.info("modelProp - " + prop);
534         logger.info("docText - " + docText);
535
536         // start camunda process
537         ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinitionKey, variables);
538
539         // log process info
540         logger.info("Started processDefinitionId={}, processInstanceId={}", pi.getProcessDefinitionId(),
541                 pi.getProcessInstanceId());
542
543         // refresh model info from db (get fresh event info)
544         CldsModel retreivedModel = CldsModel.retrieve(cldsDao, modelName, false);
545
546         if (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT)
547                 || actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT)) {
548             // To verify inventory status and modify model status to distribute
549             dcaeInventoryServices.setEventInventory(retreivedModel, getUserId());
550             retreivedModel.save(cldsDao, getUserId());
551         }
552         // audit log
553         LoggingUtils.setTimeContext(startTime, new Date());
554         LoggingUtils.setResponseContext("0", "Process model action success", this.getClass().getName());
555         auditLogger.info("Process model action completed");
556
557         return retreivedModel;
558     }
559
560     /**
561      * REST service that accepts events for a model.
562      *
563      * @param test
564      * @param dcaeEvent
565      */
566     @ApiOperation(value = "Accepts events for a model", notes = "", response = String.class)
567     @POST
568     @Path("/dcae/event")
569     @Consumes(MediaType.APPLICATION_JSON)
570     @Produces(MediaType.APPLICATION_JSON)
571     public String postDcaeEvent(@QueryParam("test") String test, DcaeEvent dcaeEvent) {
572         Date startTime = new Date();
573         LoggingUtils.setRequestContext("CldsService: Post dcae event", getPrincipalName());
574         String userid = null;
575         // TODO: allow auth checking to be turned off by removing the permission
576         // type property
577         if (cldsPermissionTypeClEvent != null && cldsPermissionTypeClEvent.length() > 0) {
578             SecureServicePermission permissionEvent = SecureServicePermission.create(cldsPermissionTypeClEvent,
579                     cldsPermissionInstance, dcaeEvent.getEvent());
580             isAuthorized(permissionEvent);
581             userid = getUserId();
582         }
583
584         // Flag indicates whether it is triggered by Validation Test button from
585         // UI
586         boolean isTest = false;
587         if (test != null && test.equalsIgnoreCase("true")) {
588             isTest = true;
589         }
590
591         int instanceCount = 0;
592         if (dcaeEvent.getInstances() != null) {
593             instanceCount = dcaeEvent.getInstances().size();
594         }
595         String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID()
596                 + " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName()
597                 + " instance count=" + instanceCount + " isTest=" + isTest;
598         logger.info("POST dcae event {}", msgInfo);
599
600         if (isTest) {
601             logger.warn("Ignorning test event from DCAE");
602         } else {
603             if (DcaeEvent.EVENT_DEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent())) {
604                 CldsModel.insertModelInstance(cldsDao, dcaeEvent, userid);
605             } else {
606                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(),
607                         CldsEvent.ACTION_STATE_RECEIVED, null);
608             }
609         }
610         // audit log
611         LoggingUtils.setTimeContext(startTime, new Date());
612         LoggingUtils.setResponseContext("0", "Post dcae event success", this.getClass().getName());
613         auditLogger.info("Post dcae event completed");
614
615         return msgInfo;
616     }
617
618     /**
619      * REST service that retrieves sdc services
620      *
621      * @throws Exception
622      */
623     @ApiOperation(value = "Retrieves sdc services", notes = "", response = String.class)
624     @GET
625     @Path("/sdc/services")
626     @Produces(MediaType.APPLICATION_JSON)
627     public String getSdcServices() {
628         Date startTime = new Date();
629         LoggingUtils.setRequestContext("CldsService: GET sdc services", getPrincipalName());
630         String retStr;
631
632         String responseStr = sdcCatalogServices.getSdcServicesInformation(null);
633         try {
634             retStr = createUiServiceFormatJson(responseStr);
635         } catch (IOException e) {
636             logger.error("IOException during SDC communication", e);
637             throw new SdcCommunicationException("IOException during SDC communication", e);
638         }
639
640         logger.info("value of sdcServices : {}", retStr);
641         // audit log
642         LoggingUtils.setTimeContext(startTime, new Date());
643         LoggingUtils.setResponseContext("0", "Get sdc services success", this.getClass().getName());
644         auditLogger.info("GET sdc services completed");
645         return retStr;
646     }
647
648     /**
649      * REST service that retrieves total properties required by UI
650      * 
651      * @throws IOException
652      *             In case of issues
653      *
654      */
655     @ApiOperation(value = "Retrieves total properties required by UI", notes = "", response = String.class)
656     @GET
657     @Path("/properties")
658     @Produces(MediaType.APPLICATION_JSON)
659     public String getSdcProperties() throws IOException {
660         return createPropertiesObjectByUUID(getGlobalCldsString(), "{}");
661     }
662
663     /**
664      * REST service that retrieves total properties by using invariantUUID based
665      * on refresh and non refresh
666      * 
667      */
668     @ApiOperation(value = "Retrieves total properties by using invariantUUID based on refresh and non refresh", notes = "", response = String.class)
669     @GET
670     @Path("/properties/{serviceInvariantUUID}")
671     @Produces(MediaType.APPLICATION_JSON)
672     public String getSdcPropertiesByServiceUUIDForRefresh(
673             @PathParam("serviceInvariantUUID") String serviceInvariantUUID,
674             @DefaultValue("false") @QueryParam("refresh") String refresh) {
675         Date startTime = new Date();
676         LoggingUtils.setRequestContext("CldsService: GET sdc properties by uuid", getPrincipalName());
677         CldsServiceData cldsServiceData = new CldsServiceData();
678         cldsServiceData.setServiceInvariantUUID(serviceInvariantUUID);
679
680         boolean isCldsSdcDataExpired = true;
681         // To getcldsService information from database cache using invariantUUID
682         // only when refresh = false
683         if (refresh != null && refresh.equalsIgnoreCase("false")) {
684             cldsServiceData = cldsServiceData.getCldsServiceCache(cldsDao, serviceInvariantUUID);
685             // If cldsService is available in database Cache , verify is data
686             // expired or not
687             if (cldsServiceData != null) {
688                 isCldsSdcDataExpired = sdcCatalogServices.isCldsSdcCacheDataExpired(cldsServiceData);
689             }
690         }
691         // If user Requested for refresh or database cache expired , get all
692         // data from sdc api.
693         if ((refresh != null && refresh.equalsIgnoreCase("true")) || isCldsSdcDataExpired) {
694             cldsServiceData = sdcCatalogServices.getCldsServiceDataWithAlarmConditions(serviceInvariantUUID);
695             CldsDBServiceCache cldsDBServiceCache = sdcCatalogServices
696                     .getCldsDbServiceCacheUsingCldsServiceData(cldsServiceData);
697             if (cldsDBServiceCache != null && cldsDBServiceCache.getInvariantId() != null
698                     && cldsDBServiceCache.getServiceId() != null) {
699                 cldsServiceData.setCldsServiceCache(cldsDao, cldsDBServiceCache);
700             }
701         }
702
703         // filter out VFs the user is not authorized for
704         cldsServiceData.filterVfs(this);
705
706         // audit log
707         LoggingUtils.setTimeContext(startTime, new Date());
708         LoggingUtils.setResponseContext("0", "Get sdc properties by uuid success", this.getClass().getName());
709         auditLogger.info("GET sdc properties by uuid completed");
710
711         // format retrieved data into properties json
712         return sdcCatalogServices.createPropertiesObjectByUUID(getGlobalCldsString(), cldsServiceData);
713     }
714
715     /**
716      * Determine if the user is authorized for a particular VF by its invariant
717      * UUID.
718      *
719      * @param vfInvariantUuid
720      * @throws NotAuthorizedException
721      * @return
722      */
723     public boolean isAuthorizedForVf(String vfInvariantUuid) {
724         if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) {
725             SecureServicePermission permission = SecureServicePermission.create(cldsPermissionTypeFilterVf,
726                     cldsPermissionInstance, vfInvariantUuid);
727             return isAuthorized(permission);
728         } else {
729             // if CLDS_PERMISSION_TYPE_FILTER_VF property is not provided, then
730             // VF filtering is turned off
731             logger.warn("VF filtering turned off");
732             return true;
733         }
734     }
735
736     /**
737      * Determine if the user is authorized for a particular VF by its invariant
738      * UUID. If not authorized, then NotAuthorizedException is thrown.
739      *
740      * @param model
741      * @return
742      */
743     private boolean isAuthorizedForVf(CldsModel model) {
744         String vf = ModelProperties.getVf(model);
745         if (vf == null || vf.length() == 0) {
746             logger.info("VF not found in model");
747             return true;
748         } else {
749             return isAuthorizedForVf(vf);
750         }
751     }
752
753     private String createUiServiceFormatJson(String responseStr) throws IOException {
754         if (StringUtils.isBlank(responseStr)) {
755             return "";
756         }
757         ObjectMapper objectMapper = new ObjectMapper();
758         List<CldsSdcServiceInfo> rawList = objectMapper.readValue(responseStr,
759                 objectMapper.getTypeFactory().constructCollectionType(List.class, CldsSdcServiceInfo.class));
760         ObjectNode invariantIdServiceNode = objectMapper.createObjectNode();
761         ObjectNode serviceNode = objectMapper.createObjectNode();
762         logger.info("value of cldsserviceiNfolist: {}", rawList);
763         if (rawList != null && !rawList.isEmpty()) {
764             List<CldsSdcServiceInfo> cldsSdcServiceInfoList = sdcCatalogServices.removeDuplicateServices(rawList);
765
766             for (CldsSdcServiceInfo currCldsSdcServiceInfo : cldsSdcServiceInfoList) {
767                 if (currCldsSdcServiceInfo != null) {
768                     invariantIdServiceNode.put(currCldsSdcServiceInfo.getInvariantUUID(),
769                             currCldsSdcServiceInfo.getName());
770                 }
771             }
772             serviceNode.putPOJO("service", invariantIdServiceNode);
773         }
774         return serviceNode.toString();
775     }
776
777     private String createPropertiesObjectByUUID(String globalProps, String cldsResponseStr) throws IOException {
778         ObjectMapper mapper = new ObjectMapper();
779         CldsSdcServiceDetail cldsSdcServiceDetail = mapper.readValue(cldsResponseStr, CldsSdcServiceDetail.class);
780         ObjectNode globalPropsJson = null;
781         if (cldsSdcServiceDetail != null && cldsSdcServiceDetail.getUuid() != null) {
782             /**
783              * to create json with vf, alarm and locations
784              */
785             ObjectNode serviceObjectNode = createEmptyVfAlarmObject(mapper);
786             ObjectNode vfObjectNode = mapper.createObjectNode();
787
788             /**
789              * to create json with vf and vfresourceId
790              */
791             createVfObjectNode(vfObjectNode, mapper, cldsSdcServiceDetail.getResources());
792             serviceObjectNode.putPOJO(cldsSdcServiceDetail.getInvariantUUID(), vfObjectNode);
793             ObjectNode byServiceBasicObjetNode = mapper.createObjectNode();
794             byServiceBasicObjetNode.putPOJO("byService", serviceObjectNode);
795
796             /**
797              * to create json with VFC Node
798              */
799             ObjectNode emptyvfcobjectNode = createByVFCObjectNode(mapper, cldsSdcServiceDetail.getResources());
800             byServiceBasicObjetNode.putPOJO("byVf", emptyvfcobjectNode);
801             globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
802             globalPropsJson.putPOJO("shared", byServiceBasicObjetNode);
803             logger.info("valuie of objNode: {}", globalPropsJson);
804         } else {
805             /**
806              * to create json with total properties when no serviceUUID passed
807              */
808             globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
809         }
810         return globalPropsJson.toString();
811     }
812
813     private ObjectNode createEmptyVfAlarmObject(ObjectMapper mapper) {
814         ObjectNode emptyObjectNode = mapper.createObjectNode();
815         emptyObjectNode.put("", "");
816         ObjectNode vfObjectNode = mapper.createObjectNode();
817         vfObjectNode.putPOJO("vf", emptyObjectNode);
818         vfObjectNode.putPOJO("location", emptyObjectNode);
819         vfObjectNode.putPOJO("alarmCondition", emptyObjectNode);
820         ObjectNode emptyServiceObjectNode = mapper.createObjectNode();
821         emptyServiceObjectNode.putPOJO("", vfObjectNode);
822         return emptyServiceObjectNode;
823     }
824
825     private void createVfObjectNode(ObjectNode vfObjectNode2, ObjectMapper mapper,
826             List<CldsSdcResource> rawCldsSdcResourceList) {
827         ObjectNode vfNode = mapper.createObjectNode();
828         vfNode.put("", "");
829
830         // To remove repeated resource instance name from
831         // resourceInstanceList
832         List<CldsSdcResource> cldsSdcResourceList = sdcCatalogServices
833                 .removeDuplicateSdcResourceInstances(rawCldsSdcResourceList);
834         /**
835          * Creating vf resource node using cldsSdcResource Object
836          */
837         if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
838             for (CldsSdcResource cldsSdcResource : cldsSdcResourceList) {
839                 if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
840                     vfNode.put(cldsSdcResource.getResourceUUID(), cldsSdcResource.getResourceName());
841                 }
842             }
843         }
844         vfObjectNode2.putPOJO("vf", vfNode);
845
846         /**
847          * creating location json object using properties file value
848          */
849         ObjectNode locationJsonNode;
850         try {
851             locationJsonNode = (ObjectNode) mapper.readValue(refProp.getStringValue("ui.location.default"),
852                     JsonNode.class);
853         } catch (IOException e) {
854             logger.error("Unable to load ui.location.default JSON in clds-references.properties properly", e);
855             throw new CldsConfigException(
856                     "Unable to load ui.location.default JSON in clds-references.properties properly", e);
857         }
858         vfObjectNode2.putPOJO("location", locationJsonNode);
859
860         /**
861          * creating alarm json object using properties file value
862          */
863         String alarmStringValue = refProp.getStringValue("ui.alarm.default");
864         logger.info("value of alarm: {}", alarmStringValue);
865         ObjectNode alarmStringJsonNode;
866         try {
867             alarmStringJsonNode = (ObjectNode) mapper.readValue(alarmStringValue, JsonNode.class);
868         } catch (IOException e) {
869             logger.error("Unable to ui.alarm.default JSON in clds-references.properties properly", e);
870             throw new CldsConfigException("Unable to load ui.alarm.default JSON in clds-references.properties properly",
871                     e);
872         }
873         vfObjectNode2.putPOJO("alarmCondition", alarmStringJsonNode);
874
875     }
876
877     private ObjectNode createByVFCObjectNode(ObjectMapper mapper, List<CldsSdcResource> cldsSdcResourceList) {
878         ObjectNode emptyObjectNode = mapper.createObjectNode();
879         ObjectNode emptyvfcobjectNode = mapper.createObjectNode();
880         ObjectNode vfCObjectNode = mapper.createObjectNode();
881         vfCObjectNode.putPOJO("vfC", emptyObjectNode);
882         ObjectNode subVfCObjectNode = mapper.createObjectNode();
883         subVfCObjectNode.putPOJO("vfc", emptyObjectNode);
884         if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
885             for (CldsSdcResource cldsSdcResource : cldsSdcResourceList) {
886                 if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
887                     vfCObjectNode.putPOJO(cldsSdcResource.getResourceUUID(), subVfCObjectNode);
888                 }
889             }
890         }
891         emptyvfcobjectNode.putPOJO("", vfCObjectNode);
892         return emptyvfcobjectNode;
893     }
894
895     @PUT
896     @Path("/deploy/{modelName}")
897     @Consumes(MediaType.APPLICATION_JSON)
898     @Produces(MediaType.APPLICATION_JSON)
899     public CldsModel deployModel(@PathParam("action") String action, @PathParam("modelName") String modelName,
900             @QueryParam("test") String test, CldsModel model) throws IOException {
901         Date startTime = new Date();
902         LoggingUtils.setRequestContext("CldsService: Deploy model", getPrincipalName());
903         String deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId";
904         String createNewDeploymentStatusUrl = dcaeDispatcherServices.createNewDeployment(deploymentId,
905                 model.getTypeId());
906         String operationStatus = "processing";
907         long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10);
908         while ("processing".equalsIgnoreCase(operationStatus)) {
909             // Break the loop if waiting for more than 10 mins
910             if (waitingTime < System.nanoTime()) {
911                 break;
912             }
913             operationStatus = dcaeDispatcherServices.getOperationStatus(createNewDeploymentStatusUrl);
914         }
915         if ("succeeded".equalsIgnoreCase(operationStatus)) {
916             String artifactName = model.getControlName();
917             if (artifactName != null) {
918                 artifactName = artifactName + ".yml";
919             }
920             DcaeEvent dcaeEvent = new DcaeEvent();
921             /* set dcae events */
922             dcaeEvent.setArtifactName(artifactName);
923             dcaeEvent.setEvent(DcaeEvent.EVENT_DEPLOYMENT);
924             CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(),
925                     CldsEvent.ACTION_STATE_RECEIVED, null);
926             model.setDeploymentId(deploymentId);
927             model.save(cldsDao, getUserId());
928         } else {
929             logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
930             throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
931                     "Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
932         }
933         logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId);
934         // audit log
935         LoggingUtils.setTimeContext(startTime, new Date());
936         LoggingUtils.setResponseContext("0", "Deploy model success", this.getClass().getName());
937         auditLogger.info("Deploy model completed");
938         return model;
939     }
940
941     @PUT
942     @Path("/undeploy/{modelName}")
943     @Consumes(MediaType.APPLICATION_JSON)
944     @Produces(MediaType.APPLICATION_JSON)
945     public CldsModel unDeployModel(@PathParam("action") String action, @PathParam("modelName") String modelName,
946             @QueryParam("test") String test, CldsModel model) throws IOException {
947         Date startTime = new Date();
948         LoggingUtils.setRequestContext("CldsService: Undeploy model", getPrincipalName());
949         String operationStatusUndeployUrl = dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(),
950                 model.getTypeId());
951         String operationStatus = "processing";
952         long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10);
953         while ("processing".equalsIgnoreCase(operationStatus)) {
954             if (waitingTime < System.nanoTime()) {
955                 break;
956             }
957             operationStatus = dcaeDispatcherServices.getOperationStatus(operationStatusUndeployUrl);
958         }
959         if ("succeeded".equalsIgnoreCase(operationStatus)) {
960             String artifactName = model.getControlName();
961             if (artifactName != null) {
962                 artifactName = artifactName + ".yml";
963             }
964             DcaeEvent dcaeEvent = new DcaeEvent();
965             // set dcae events
966             dcaeEvent.setArtifactName(artifactName);
967             dcaeEvent.setEvent(DcaeEvent.EVENT_UNDEPLOYMENT);
968             CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(),
969                     CldsEvent.ACTION_STATE_RECEIVED, null);
970             model.setDeploymentId(null);
971             model.save(cldsDao, getUserId());
972         } else {
973             logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
974             throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
975                     "Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
976         }
977         logger.info("Undeploy model (" + modelName + ") succeeded.");
978         // audit log
979         LoggingUtils.setTimeContext(startTime, new Date());
980         LoggingUtils.setResponseContext("0", "Undeploy model success", this.getClass().getName());
981         auditLogger.info("Undeploy model completed");
982         return model;
983     }
984
985     private String getGlobalCldsString() {
986         try {
987             if (null == globalCldsProperties) {
988                 globalCldsProperties = new Properties();
989                 globalCldsProperties.load(appContext.getResource(globalClds).getInputStream());
990             }
991             return (String) globalCldsProperties.get("globalCldsProps");
992         } catch (IOException e) {
993             logger.error("Unable to load the globalClds due to an exception", e);
994             throw new CldsConfigException("Unable to load the globalClds due to an exception", e);
995         }
996     }
997 }