a63d0218554baa99a3c833d50e7f34379c3a8a60
[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 (retrievedModel != null) {
472                 if (!isTest && (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT)
473                     || actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT)
474                     || actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE))) {
475                     if (retrievedModel.getTemplateName().startsWith(CsarInstallerImpl.TEMPLATE_NAME_PREFIX)) {
476                         // SDC artifact case
477                         logger.info("Skipping DCAE inventory call as closed loop has been created from SDC notification");
478                         DcaeEvent dcaeEvent = new DcaeEvent();
479                         dcaeEvent.setArtifactName(retrievedModel.getControlName() + ".yml");
480                         dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);
481                         CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(),
482                             CldsEvent.ACTION_STATE_RECEIVED, null);
483                     } else {
484                         // This should be done only when the call to DCAE
485                         // has not yet been done. When CL comes from SDC
486                         // this is not required as the DCAE inventory call is done
487                         // during the CL deployment.
488                         dcaeInventoryServices.setEventInventory(retrievedModel, getUserId());
489                     }
490                     retrievedModel.save(cldsDao, getUserId());
491                 }
492                 // audit log
493                 LoggingUtils.setTimeContext(startTime, new Date());
494                 LoggingUtils.setResponseContext("0", "Process model action success", this.getClass().getName());
495                 auditLogger.info("Process model action completed");
496             } else {
497                 logger.error("CldsModel not found in database with modelName: " + modelName);
498                 return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("CldsModel not found in database with modelName: \" + modelName").build();
499             }
500         } catch (Exception e) {
501             errorCase = true;
502             logger.error("Exception occured during putModelAndProcessAction", e);
503         }
504         if (errorCase) {
505             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(retrievedModel).build();
506         }
507         return Response.status(Response.Status.OK).entity(retrievedModel).build();
508     }
509
510     /**
511      * REST service that accepts events for a model.
512      *
513      * @param test
514      * @param dcaeEvent
515      */
516     @POST
517     @Path("/dcae/event")
518     @Consumes(MediaType.APPLICATION_JSON)
519     @Produces(MediaType.APPLICATION_JSON)
520     public String postDcaeEvent(@QueryParam("test") String test, DcaeEvent dcaeEvent) {
521         Date startTime = new Date();
522         LoggingUtils.setRequestContext("CldsService: Post dcae event", getPrincipalName());
523         String userid = null;
524         // TODO: allow auth checking to be turned off by removing the permission
525         // type property
526         if (cldsPermissionTypeClEvent != null && cldsPermissionTypeClEvent.length() > 0) {
527             SecureServicePermission permissionEvent = SecureServicePermission.create(cldsPermissionTypeClEvent,
528                 cldsPermissionInstance, dcaeEvent.getEvent());
529             isAuthorized(permissionEvent);
530             userid = getUserId();
531         }
532         // Flag indicates whether it is triggered by Validation Test button from
533         // UI
534         boolean isTest = Boolean.valueOf(test);
535         int instanceCount = 0;
536         if (dcaeEvent.getInstances() != null) {
537             instanceCount = dcaeEvent.getInstances().size();
538         }
539         String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID()
540         + " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName()
541         + " instance count=" + instanceCount + " isTest=" + isTest;
542         logger.info("POST dcae event {}", msgInfo);
543         if (isTest) {
544             logger.warn("Ignorning test event from DCAE");
545         } else {
546             if (DcaeEvent.EVENT_DEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent())) {
547                 CldsModel.insertModelInstance(cldsDao, dcaeEvent, userid);
548             } else {
549                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(),
550                     CldsEvent.ACTION_STATE_RECEIVED, null);
551             }
552         }
553         // audit log
554         LoggingUtils.setTimeContext(startTime, new Date());
555         LoggingUtils.setResponseContext("0", "Post dcae event success", this.getClass().getName());
556         auditLogger.info("Post dcae event completed");
557         return msgInfo;
558     }
559
560     /**
561      * REST service that retrieves sdc services
562      *
563      * @throws GeneralSecurityException
564      *         In case of issue when decryting the SDC password
565      * @throws DecoderException
566      *         In case of issues with the decoding of the Hex String
567      */
568     @GET
569     @Path("/sdc/services")
570     @Produces(MediaType.APPLICATION_JSON)
571     public String getSdcServices() throws GeneralSecurityException, DecoderException {
572         Date startTime = new Date();
573         LoggingUtils.setRequestContext("CldsService: GET sdc services", getPrincipalName());
574         String retStr;
575         try {
576             retStr = createUiServiceFormatJson(sdcCatalogServices.getSdcServicesInformation(null));
577         } catch (IOException e) {
578             logger.error("IOException during SDC communication", e);
579             throw new SdcCommunicationException("IOException during SDC communication", e);
580         }
581         logger.info("value of sdcServices : {}", retStr);
582         // audit log
583         LoggingUtils.setTimeContext(startTime, new Date());
584         LoggingUtils.setResponseContext("0", "Get sdc services success", this.getClass().getName());
585         auditLogger.info("GET sdc services completed");
586         return retStr;
587     }
588
589     /**
590      * REST service that retrieves total properties required by UI
591      *
592      * @throws IOException
593      *         In case of issues
594      */
595     @GET
596     @Path("/properties")
597     @Produces(MediaType.APPLICATION_JSON)
598     public String getSdcProperties() throws IOException {
599         return createPropertiesObjectByUUID("{}");
600     }
601
602     /**
603      * REST service that retrieves total properties by using invariantUUID based on
604      * refresh and non refresh
605      *
606      * @throws GeneralSecurityException
607      *         In case of issues with the decryting the encrypted password
608      * @throws DecoderException
609      *         In case of issues with the decoding of the Hex String
610      * @throws IOException
611      *         In case of issue to convert CldsServiceCache to InputStream
612      */
613     @GET
614     @Path("/properties/{serviceInvariantUUID}")
615     @Produces(MediaType.APPLICATION_JSON)
616     public String getSdcPropertiesByServiceUUIDForRefresh(
617         @PathParam("serviceInvariantUUID") String serviceInvariantUUID,
618         @DefaultValue("false") @QueryParam("refresh") boolean refresh)
619             throws GeneralSecurityException, DecoderException, IOException {
620         Date startTime = new Date();
621         LoggingUtils.setRequestContext("CldsService: GET sdc properties by uuid", getPrincipalName());
622         CldsServiceData cldsServiceData = new CldsServiceData();
623         cldsServiceData.setServiceInvariantUUID(serviceInvariantUUID);
624         if (!refresh) {
625             cldsServiceData = cldsDao.getCldsServiceCache(serviceInvariantUUID);
626         }
627         if (sdcCatalogServices.isCldsSdcCacheDataExpired(cldsServiceData)) {
628             cldsServiceData = sdcCatalogServices.getCldsServiceDataWithAlarmConditions(serviceInvariantUUID);
629             cldsDao.setCldsServiceCache(new CldsDbServiceCache(cldsServiceData));
630         }
631         // filter out VFs the user is not authorized for
632         cldsServiceData.filterVfs(this);
633         // format retrieved data into properties json
634         String sdcProperties = sdcCatalogServices.createPropertiesObjectByUUID(cldsServiceData);
635         // audit log
636         LoggingUtils.setTimeContext(startTime, new Date());
637         LoggingUtils.setResponseContext("0", "Get sdc properties by uuid success", this.getClass().getName());
638         auditLogger.info("GET sdc properties by uuid completed");
639         return sdcProperties;
640     }
641
642     /**
643      * Determine if the user is authorized for a particular VF by its invariant
644      * UUID.
645      *
646      * @param vfInvariantUuid
647      * @throws NotAuthorizedException
648      * @return
649      */
650     public boolean isAuthorizedForVf(String vfInvariantUuid) {
651         if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) {
652             SecureServicePermission permission = SecureServicePermission.create(cldsPermissionTypeFilterVf,
653                 cldsPermissionInstance, vfInvariantUuid);
654             return isAuthorized(permission);
655         } else {
656             // if CLDS_PERMISSION_TYPE_FILTER_VF property is not provided, then
657             // VF filtering is turned off
658             logger.warn("VF filtering turned off");
659             return true;
660         }
661     }
662
663     /**
664      * Determine if the user is authorized for a particular VF by its invariant
665      * UUID. If not authorized, then NotAuthorizedException is thrown.
666      *
667      * @param model
668      * @return
669      */
670     private boolean isAuthorizedForVf(CldsModel model) {
671         String vf = ModelProperties.getVf(model);
672         if (vf == null || vf.length() == 0) {
673             logger.info("VF not found in model");
674             return true;
675         } else {
676             return isAuthorizedForVf(vf);
677         }
678     }
679
680     private String createUiServiceFormatJson(String responseStr) throws IOException {
681         if (StringUtils.isBlank(responseStr)) {
682             return "";
683         }
684         ObjectMapper objectMapper = JacksonUtils.getObjectMapperInstance();
685         List<SdcServiceInfo> rawList = objectMapper.readValue(responseStr,
686             objectMapper.getTypeFactory().constructCollectionType(List.class, SdcServiceInfo.class));
687         ObjectNode invariantIdServiceNode = objectMapper.createObjectNode();
688         ObjectNode serviceNode = objectMapper.createObjectNode();
689         logger.info("value of cldsserviceiNfolist: {}", rawList);
690         if (rawList != null && !rawList.isEmpty()) {
691             List<SdcServiceInfo> cldsSdcServiceInfoList = sdcCatalogServices.removeDuplicateServices(rawList);
692             for (SdcServiceInfo currCldsSdcServiceInfo : cldsSdcServiceInfoList) {
693                 if (currCldsSdcServiceInfo != null) {
694                     invariantIdServiceNode.put(currCldsSdcServiceInfo.getInvariantUUID(),
695                         currCldsSdcServiceInfo.getName());
696                 }
697             }
698             serviceNode.putPOJO("service", invariantIdServiceNode);
699         }
700         return serviceNode.toString();
701     }
702
703     private String createPropertiesObjectByUUID(String cldsResponseStr) throws IOException {
704         ObjectMapper mapper = JacksonUtils.getObjectMapperInstance();
705         SdcServiceDetail cldsSdcServiceDetail = mapper.readValue(cldsResponseStr, SdcServiceDetail.class);
706         ObjectNode globalPropsJson = (ObjectNode) refProp.getJsonTemplate(GLOBAL_PROPERTIES_KEY);
707         if (cldsSdcServiceDetail != null && cldsSdcServiceDetail.getUuid() != null) {
708             /**
709              * to create json with vf, alarm and locations
710              */
711             ObjectNode serviceObjectNode = createEmptyVfAlarmObject();
712             ObjectNode vfObjectNode = mapper.createObjectNode();
713             /**
714              * to create json with vf and vfresourceId
715              */
716             createVfObjectNode(vfObjectNode, cldsSdcServiceDetail.getResources());
717             serviceObjectNode.putPOJO(cldsSdcServiceDetail.getInvariantUUID(), vfObjectNode);
718             ObjectNode byServiceBasicObjetNode = mapper.createObjectNode();
719             byServiceBasicObjetNode.putPOJO("byService", serviceObjectNode);
720             /**
721              * to create json with VFC Node
722              */
723             ObjectNode emptyvfcobjectNode = createByVFCObjectNode(cldsSdcServiceDetail.getResources());
724             byServiceBasicObjetNode.putPOJO("byVf", emptyvfcobjectNode);
725             globalPropsJson.putPOJO("shared", byServiceBasicObjetNode);
726             logger.info("valuie of objNode: {}", globalPropsJson);
727         }
728         return globalPropsJson.toString();
729     }
730
731     private ObjectNode createEmptyVfAlarmObject() {
732         ObjectMapper mapper = JacksonUtils.getObjectMapperInstance();
733         ObjectNode emptyObjectNode = mapper.createObjectNode();
734         emptyObjectNode.put("", "");
735         ObjectNode vfObjectNode = mapper.createObjectNode();
736         vfObjectNode.putPOJO("vf", emptyObjectNode);
737         vfObjectNode.putPOJO("location", emptyObjectNode);
738         vfObjectNode.putPOJO("alarmCondition", emptyObjectNode);
739         ObjectNode emptyServiceObjectNode = mapper.createObjectNode();
740         emptyServiceObjectNode.putPOJO("", vfObjectNode);
741         return emptyServiceObjectNode;
742     }
743
744     private void createVfObjectNode(ObjectNode vfObjectNode2, List<SdcResource> rawCldsSdcResourceList) {
745         ObjectMapper mapper = JacksonUtils.getObjectMapperInstance();
746         ObjectNode vfNode = mapper.createObjectNode();
747         vfNode.put("", "");
748         // To remove repeated resource instance name from
749         // resourceInstanceList
750         List<SdcResource> cldsSdcResourceList = sdcCatalogServices
751             .removeDuplicateSdcResourceInstances(rawCldsSdcResourceList);
752         /**
753          * Creating vf resource node using cldsSdcResource Object
754          */
755         if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
756             for (SdcResource cldsSdcResource : cldsSdcResourceList) {
757                 if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
758                     vfNode.put(cldsSdcResource.getResourceUUID(), cldsSdcResource.getResourceName());
759                 }
760             }
761         }
762         vfObjectNode2.putPOJO("vf", vfNode);
763         /**
764          * creating location json object using properties file value
765          */
766         ObjectNode locationJsonNode;
767         try {
768             locationJsonNode = (ObjectNode) mapper.readValue(refProp.getStringValue("ui.location.default"),
769                 JsonNode.class);
770         } catch (IOException e) {
771             logger.error("Unable to load ui.location.default JSON in clds-references.properties properly", e);
772             throw new CldsConfigException(
773                 "Unable to load ui.location.default JSON in clds-references.properties properly", e);
774         }
775         vfObjectNode2.putPOJO("location", locationJsonNode);
776         /**
777          * creating alarm json object using properties file value
778          */
779         String alarmStringValue = refProp.getStringValue("ui.alarm.default");
780         logger.info("value of alarm: {}", alarmStringValue);
781         ObjectNode alarmStringJsonNode;
782         try {
783             alarmStringJsonNode = (ObjectNode) mapper.readValue(alarmStringValue, JsonNode.class);
784         } catch (IOException e) {
785             logger.error("Unable to ui.alarm.default JSON in clds-references.properties properly", e);
786             throw new CldsConfigException("Unable to load ui.alarm.default JSON in clds-references.properties properly",
787                 e);
788         }
789         vfObjectNode2.putPOJO("alarmCondition", alarmStringJsonNode);
790     }
791
792     private ObjectNode createByVFCObjectNode(List<SdcResource> cldsSdcResourceList) {
793         ObjectMapper mapper = JacksonUtils.getObjectMapperInstance();
794         ObjectNode emptyObjectNode = mapper.createObjectNode();
795         ObjectNode emptyvfcobjectNode = mapper.createObjectNode();
796         ObjectNode vfCObjectNode = mapper.createObjectNode();
797         vfCObjectNode.putPOJO("vfC", emptyObjectNode);
798         ObjectNode subVfCObjectNode = mapper.createObjectNode();
799         subVfCObjectNode.putPOJO("vfc", emptyObjectNode);
800         if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
801             for (SdcResource cldsSdcResource : cldsSdcResourceList) {
802                 if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
803                     vfCObjectNode.putPOJO(cldsSdcResource.getResourceUUID(), subVfCObjectNode);
804                 }
805             }
806         }
807         emptyvfcobjectNode.putPOJO("", vfCObjectNode);
808         return emptyvfcobjectNode;
809     }
810
811     @PUT
812     @Path("/deploy/{modelName}")
813     @Consumes(MediaType.APPLICATION_JSON)
814     @Produces(MediaType.APPLICATION_JSON)
815     public Response deployModel(@PathParam("modelName") String modelName, CldsModel model) {
816         Date startTime = new Date();
817         LoggingUtils.setRequestContext("CldsService: Deploy model", getPrincipalName());
818         Boolean errorCase = false;
819         try {
820             fillInCldsModel(model);
821             String bpmnJson = cldsBpmnTransformer.doXslTransformToString(model.getBpmnText());
822             logger.info("PUT bpmnJson={}", bpmnJson);
823             SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
824                 cldsPermissionInstance, CldsEvent.ACTION_DEPLOY);
825             isAuthorized(permisionManage);
826             isAuthorizedForVf(model);
827             ModelProperties modelProp = new ModelProperties(modelName, model.getControlName(), CldsEvent.ACTION_DEPLOY,
828                 false, bpmnJson, model.getPropText());
829             checkForDuplicateServiceVf(modelName, model.getPropText());
830             String deploymentId = "";
831             // If model is already deployed then pass same deployment id
832             if (model.getDeploymentId() != null && !model.getDeploymentId().isEmpty()) {
833                 deploymentId = model.getDeploymentId();
834             } else {
835                 deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId";
836             }
837             String createNewDeploymentStatusUrl = dcaeDispatcherServices.createNewDeployment(deploymentId,
838                 model.getTypeId(), modelProp.getGlobal().getDeployParameters());
839             String operationStatus = dcaeDispatcherServices.getOperationStatusWithRetry(createNewDeploymentStatusUrl);
840             if ("succeeded".equalsIgnoreCase(operationStatus)) {
841                 String artifactName = model.getControlName();
842                 if (artifactName != null) {
843                     artifactName = artifactName + ".yml";
844                 }
845                 DcaeEvent dcaeEvent = new DcaeEvent();
846                 /* set dcae events */
847                 dcaeEvent.setArtifactName(artifactName);
848                 dcaeEvent.setEvent(DcaeEvent.EVENT_DEPLOYMENT);
849                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(),
850                     CldsEvent.ACTION_STATE_RECEIVED, null);
851                 model.setDeploymentId(deploymentId);
852                 model.save(cldsDao, getUserId());
853             } else {
854                 logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
855                 throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
856                     "Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
857             }
858             logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId);
859             // audit log
860             LoggingUtils.setTimeContext(startTime, new Date());
861             LoggingUtils.setResponseContext("0", "Deploy model success", this.getClass().getName());
862             auditLogger.info("Deploy model completed");
863         } catch (Exception e) {
864             errorCase = true;
865             logger.error("Exception occured during deployModel", e);
866         }
867         if (errorCase) {
868             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(model).build();
869         }
870         return Response.status(Response.Status.OK).entity(model).build();
871     }
872
873     @PUT
874     @Path("/undeploy/{modelName}")
875     @Consumes(MediaType.APPLICATION_JSON)
876     @Produces(MediaType.APPLICATION_JSON)
877     public Response unDeployModel(@PathParam("modelName") String modelName, CldsModel model) {
878         Date startTime = new Date();
879         LoggingUtils.setRequestContext("CldsService: Undeploy model", getPrincipalName());
880         Boolean errorCase = false;
881         try {
882             SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
883                 cldsPermissionInstance, CldsEvent.ACTION_UNDEPLOY);
884             isAuthorized(permisionManage);
885             isAuthorizedForVf(model);
886             String operationStatusUndeployUrl = dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(),
887                 model.getTypeId());
888             String operationStatus = dcaeDispatcherServices.getOperationStatusWithRetry(operationStatusUndeployUrl);
889             if ("succeeded".equalsIgnoreCase(operationStatus)) {
890                 String artifactName = model.getControlName();
891                 if (artifactName != null) {
892                     artifactName = artifactName + ".yml";
893                 }
894                 DcaeEvent dcaeEvent = new DcaeEvent();
895                 // set dcae events
896                 dcaeEvent.setArtifactName(artifactName);
897                 dcaeEvent.setEvent(DcaeEvent.EVENT_UNDEPLOYMENT);
898                 CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(),
899                     CldsEvent.ACTION_STATE_RECEIVED, null);
900                 model.setDeploymentId(null);
901                 model.save(cldsDao, getUserId());
902             } else {
903                 logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
904                 throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
905                     "Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
906             }
907             logger.info("Undeploy model (" + modelName + ") succeeded.");
908             // audit log
909             LoggingUtils.setTimeContext(startTime, new Date());
910             LoggingUtils.setResponseContext("0", "Undeploy model success", this.getClass().getName());
911             auditLogger.info("Undeploy model completed");
912         } catch (Exception e) {
913             errorCase = true;
914             logger.error("Exception occured during unDeployModel", e);
915         }
916         if (errorCase) {
917             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(model).build();
918         }
919         return Response.status(Response.Status.OK).entity(model).build();
920     }
921
922     private void checkForDuplicateServiceVf(String modelName, String modelPropText) throws IOException {
923         JsonNode globalNode = JacksonUtils.getObjectMapperInstance().readTree(modelPropText).get("global");
924         String service = AbstractModelElement.getValueByName(globalNode, "service");
925         List<String> resourceVf = AbstractModelElement.getValuesByName(globalNode, "vf");
926         if (service != null && resourceVf != null && !resourceVf.isEmpty()) {
927             List<CldsModelProp> cldsModelPropList = cldsDao.getDeployedModelProperties();
928             for (CldsModelProp cldsModelProp : cldsModelPropList) {
929                 JsonNode currentNode = JacksonUtils.getObjectMapperInstance().readTree(cldsModelProp.getPropText())
930                     .get("global");
931                 String currentService = AbstractModelElement.getValueByName(currentNode, "service");
932                 List<String> currentVf = AbstractModelElement.getValuesByName(currentNode, "vf");
933                 if (currentVf != null && !currentVf.isEmpty()) {
934                     if (!modelName.equalsIgnoreCase(cldsModelProp.getName()) && service.equalsIgnoreCase(currentService)
935                         && resourceVf.get(0).equalsIgnoreCase(currentVf.get(0))) {
936                         throw new BadRequestException("Same Service/VF already exists in " + cldsModelProp.getName()
937                         + " model, please select different Service/VF.");
938                     }
939                 }
940             }
941         }
942     }
943
944     private void updateAndInsertNewEvent(String cldsModelName, String cldsControlNamePrfx, CldsEvent event,
945         String newAction) {
946         // If model action is in submit/resubmit/distributed and user try
947         // to save then we are changing action back to create.
948         if (event != null && (CldsEvent.ACTION_SUBMIT.equalsIgnoreCase(event.getActionCd())
949             || CldsEvent.ACTION_RESUBMIT.equalsIgnoreCase(event.getActionCd())
950             || CldsEvent.ACTION_DISTRIBUTE.equalsIgnoreCase(event.getActionCd()))) {
951             CldsEvent newEvent = new CldsEvent();
952             newEvent.setUserid(getUserId());
953             newEvent.setActionCd(newAction);
954             newEvent.setActionStateCd(CldsEvent.ACTION_STATE_COMPLETED);
955             cldsDao.insEvent(cldsModelName, cldsControlNamePrfx, null, newEvent);
956         }
957     }
958 }