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