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