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