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