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