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