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