2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 package org.onap.clamp.clds.service;
26 import com.att.ajsc.common.AjscService;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.fasterxml.jackson.databind.node.ObjectNode;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.util.Date;
34 import java.util.HashMap;
35 import java.util.List;
37 import java.util.Properties;
38 import java.util.UUID;
39 import java.util.concurrent.TimeUnit;
41 import javax.annotation.PostConstruct;
42 import javax.ws.rs.Consumes;
43 import javax.ws.rs.DefaultValue;
44 import javax.ws.rs.GET;
45 import javax.ws.rs.NotAuthorizedException;
46 import javax.ws.rs.POST;
47 import javax.ws.rs.PUT;
48 import javax.ws.rs.Path;
49 import javax.ws.rs.PathParam;
50 import javax.ws.rs.Produces;
51 import javax.ws.rs.QueryParam;
52 import javax.ws.rs.core.MediaType;
53 import javax.xml.transform.TransformerException;
55 import org.apache.commons.lang3.StringUtils;
56 import org.camunda.bpm.engine.RuntimeService;
57 import org.camunda.bpm.engine.runtime.ProcessInstance;
58 import org.json.simple.parser.ParseException;
59 import org.onap.clamp.clds.client.DcaeDispatcherServices;
60 import org.onap.clamp.clds.client.DcaeInventoryServices;
61 import org.onap.clamp.clds.client.SdcCatalogServices;
62 import org.onap.clamp.clds.dao.CldsDao;
63 import org.onap.clamp.clds.exception.CldsConfigException;
64 import org.onap.clamp.clds.exception.SdcCommunicationException;
65 import org.onap.clamp.clds.model.CldsDBServiceCache;
66 import org.onap.clamp.clds.model.CldsEvent;
67 import org.onap.clamp.clds.model.CldsHealthCheck;
68 import org.onap.clamp.clds.model.CldsInfo;
69 import org.onap.clamp.clds.model.CldsModel;
70 import org.onap.clamp.clds.model.CldsSdcResource;
71 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
72 import org.onap.clamp.clds.model.CldsSdcServiceInfo;
73 import org.onap.clamp.clds.model.CldsServiceData;
74 import org.onap.clamp.clds.model.CldsTemplate;
75 import org.onap.clamp.clds.model.DcaeEvent;
76 import org.onap.clamp.clds.model.ValueItem;
77 import org.onap.clamp.clds.model.prop.ModelProperties;
78 import org.onap.clamp.clds.model.refprop.RefProp;
79 import org.onap.clamp.clds.transform.XslTransformer;
80 import org.onap.clamp.clds.util.LoggingUtils;
81 import org.springframework.beans.factory.annotation.Autowired;
82 import org.springframework.beans.factory.annotation.Value;
83 import org.springframework.context.ApplicationContext;
84 import org.springframework.http.HttpStatus;
85 import org.springframework.web.client.HttpClientErrorException;
87 import io.swagger.annotations.Api;
88 import io.swagger.annotations.ApiOperation;
91 * Service to save and retrieve the CLDS model attributes.
96 public class CldsService extends SecureServiceBase {
99 private ApplicationContext appContext;
101 private static final String RESOURCE_NAME = "clds-version.properties";
103 @Value("${CLDS_PERMISSION_TYPE_CL:permission-type-cl}")
104 private String cldsPersmissionTypeCl;
106 @Value("${CLDS_PERMISSION_TYPE_CL_MANAGE:permission-type-cl-manage}")
107 private String cldsPermissionTypeClManage;
109 @Value("${CLDS_PERMISSION_TYPE_CL_EVENT:permission-type-cl-event}")
110 private String cldsPermissionTypeClEvent;
112 @Value("${CLDS_PERMISSION_TYPE_FILTER_VF:permission-type-filter-vf}")
113 private String cldsPermissionTypeFilterVf;
115 @Value("${CLDS_PERMISSION_TYPE_TEMPLATE:permission-type-template}")
116 private String cldsPermissionTypeTemplate;
118 @Value("${CLDS_PERMISSION_INSTANCE:dev}")
119 private String cldsPermissionInstance;
121 private SecureServicePermission permissionReadCl;
123 private SecureServicePermission permissionUpdateCl;
125 private SecureServicePermission permissionReadTemplate;
127 private SecureServicePermission permissionUpdateTemplate;
130 private final void afterConstruction() {
131 permissionReadCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "read");
132 permissionUpdateCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "update");
133 permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
135 permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
139 @Value("${org.onap.clamp.config.files.globalClds:'classpath:/clds/globalClds.properties'}")
140 private String globalClds;
142 private Properties globalCldsProperties;
145 private CldsDao cldsDao;
147 private RuntimeService runtimeService;
149 private XslTransformer cldsBpmnTransformer;
152 private RefProp refProp;
155 private SdcCatalogServices sdcCatalogServices;
158 private DcaeDispatcherServices dcaeDispatcherServices;
161 private DcaeInventoryServices dcaeInventoryServices;
163 public CldsService() {
166 public CldsService(RefProp refProp) {
167 this.refProp = refProp;
172 * CLDS IFO service will return 3 things 1. User Name 2. CLDS code version
173 * that is currently installed from pom.xml file 3. User permissions
179 @Produces(MediaType.APPLICATION_JSON)
180 public CldsInfo getCldsInfo() {
182 CldsInfo cldsInfo = new CldsInfo();
185 cldsInfo.setUserName(getUserName());
187 // Get CLDS application version
188 String cldsVersion = "";
189 Properties props = new Properties();
191 ClassLoader loader = Thread.currentThread().getContextClassLoader();
193 try (InputStream resourceStream = loader.getResourceAsStream(RESOURCE_NAME)) {
194 props.load(resourceStream);
195 cldsVersion = props.getProperty("clds.version");
196 } catch (Exception ex) {
197 logger.error("Exception caught during the clds.version reading", ex);
199 cldsInfo.setCldsVersion(cldsVersion);
201 // Get the user list of permissions
202 cldsInfo.setPermissionReadCl(isAuthorizedNoException(permissionReadCl));
203 cldsInfo.setPermissionUpdateCl(isAuthorizedNoException(permissionUpdateCl));
204 cldsInfo.setPermissionReadTemplate(isAuthorizedNoException(permissionReadTemplate));
205 cldsInfo.setPermissionUpdateTemplate(isAuthorizedNoException(permissionUpdateTemplate));
210 @Path("/healthcheck")
211 @Produces(MediaType.APPLICATION_JSON)
212 public CldsHealthCheck gethealthcheck() {
214 CldsHealthCheck cldsHealthCheck = new CldsHealthCheck();
217 cldsDao.doHealthCheck();
218 cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
219 cldsHealthCheck.setHealthCheckStatus("UP");
220 cldsHealthCheck.setDescription("OK");
221 } catch (Exception e) {
222 logger.error("CLAMP application DB Error", e);
223 cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
224 cldsHealthCheck.setHealthCheckStatus("DOWN");
225 cldsHealthCheck.setDescription("NOT-OK");
227 return cldsHealthCheck;
232 * REST service that retrieves BPMN for a CLDS model name from the database.
233 * This is subset of the json getModel. This is only expected to be used for
234 * testing purposes, not by the UI.
237 * @return bpmn xml text - content of bpmn given name
239 @ApiOperation(value = "Retrieves BPMN for a CLDS model name from the database", notes = "This is only expected to be used for testing purposes, not by the UI", response = String.class)
241 @Path("/model/bpmn/{modelName}")
242 @Produces(MediaType.TEXT_XML)
243 public String getBpmnXml(@PathParam("modelName") String modelName) {
244 Date startTime = new Date();
245 LoggingUtils.setRequestContext("CldsService: GET model bpmn", getPrincipalName());
246 isAuthorized(permissionReadCl);
247 logger.info("GET bpmnText for modelName={}", modelName);
248 CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
250 LoggingUtils.setTimeContext(startTime, new Date());
251 LoggingUtils.setResponseContext("0", "Get model bpmn success", this.getClass().getName());
252 auditLogger.info("GET model bpmn completed");
253 return model.getBpmnText();
257 * REST service that saves BPMN for a CLDS model by name in the database.
258 * This is subset of the json putModel. This is only expected to be used for
259 * testing purposes, not by the UI.
263 @ApiOperation(value = "Saves BPMN for a CLDS model by name in the database", notes = "This is only expected to be used for testing purposes, not by the UI", response = String.class)
265 @Path("/model/bpmn/{modelName}")
266 @Consumes(MediaType.TEXT_XML)
267 public String putBpmnXml(@PathParam("modelName") String modelName, String bpmnText) {
268 LoggingUtils.setRequestContext("CldsService: PUT model bpmn", getPrincipalName());
269 isAuthorized(permissionUpdateCl);
270 logger.info("PUT bpmnText for modelName={}", modelName);
271 logger.info("PUT bpmnText={}", bpmnText);
272 CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, true);
273 cldsModel.setBpmnText(bpmnText);
274 cldsModel.save(cldsDao, getUserId());
276 LoggingUtils.setTimeContext(new Date(), new Date());
277 LoggingUtils.setResponseContext("0", "Put model bpmn success", this.getClass().getName());
278 auditLogger.info("PUT model bpmn completed");
279 return "wrote bpmnText for modelName=" + modelName;
283 * REST service that retrieves image for a CLDS model name from the
284 * database. This is subset of the json getModel. This is only expected to
285 * be used for testing purposes, not by the UI.
288 * @return image xml text - content of image given name
290 @ApiOperation(value = "Retrieves image for a CLDS model name from the database", notes = "This is only expected to be used for testing purposes, not by the UI", response = String.class)
292 @Path("/model/image/{modelName}")
293 @Produces(MediaType.TEXT_XML)
294 public String getImageXml(@PathParam("modelName") String modelName) {
295 Date startTime = new Date();
296 LoggingUtils.setRequestContext("CldsService: GET model image", getPrincipalName());
297 isAuthorized(permissionReadCl);
298 logger.info("GET imageText for modelName={}", modelName);
299 CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
301 LoggingUtils.setTimeContext(startTime, new Date());
302 LoggingUtils.setResponseContext("0", "Get model image success", this.getClass().getName());
303 auditLogger.info("GET model image completed");
304 return model.getImageText();
308 * REST service that saves image for a CLDS model by name in the database.
309 * This is subset of the json putModel. This is only expected to be used for
310 * testing purposes, not by the UI.
314 @ApiOperation(value = "Saves image for a CLDS model by name in the database", notes = "This is only expected to be used for testing purposes, not by the UI", response = String.class)
316 @Path("/model/image/{modelName}")
317 @Consumes(MediaType.TEXT_XML)
318 public String putImageXml(@PathParam("modelName") String modelName, String imageText) {
319 Date startTime = new Date();
320 LoggingUtils.setRequestContext("CldsService: PUT model image", getPrincipalName());
321 isAuthorized(permissionUpdateCl);
322 logger.info("PUT iamgeText for modelName={}", modelName);
323 logger.info("PUT imageText={}", imageText);
324 CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, true);
325 cldsModel.setImageText(imageText);
326 cldsModel.save(cldsDao, getUserId());
328 LoggingUtils.setTimeContext(startTime, new Date());
329 LoggingUtils.setResponseContext("0", "Put model image success", this.getClass().getName());
330 auditLogger.info("PUT model image completed");
331 return "wrote imageText for modelName=" + modelName;
335 * REST service that retrieves a CLDS model by name from the database.
338 * @return clds model - clds model for the given model name
340 @ApiOperation(value = "Retrieves a CLDS model by name from the database", notes = "", response = String.class)
342 @Path("/model/{modelName}")
343 @Produces(MediaType.APPLICATION_JSON)
344 public CldsModel getModel(@PathParam("modelName") String modelName) {
345 Date startTime = new Date();
346 LoggingUtils.setRequestContext("CldsService: GET model", getPrincipalName());
347 isAuthorized(permissionReadCl);
348 logger.debug("GET model for modelName={}", modelName);
349 CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false);
350 isAuthorizedForVf(cldsModel);
351 cldsModel.setUserAuthorizedToUpdate(isAuthorizedNoException(permissionUpdateCl));
354 * Checking condition whether our CLDS model can call INventory Method
356 if (cldsModel.canInventoryCall()) {
359 * Below is the method to for inventory call and DB insert for
362 dcaeInventoryServices.setEventInventory(cldsModel, getUserId());
363 } catch (Exception e) {
364 LoggingUtils.setErrorContext("900", "Set event inventory error");
365 logger.error("getModel set event Inventory error:" + e);
369 LoggingUtils.setTimeContext(startTime, new Date());
370 LoggingUtils.setResponseContext("0", "Get model success", this.getClass().getName());
371 auditLogger.info("GET model completed");
376 * REST service that saves a CLDS model by name in the database.
380 @ApiOperation(value = "Saves a CLDS model by name in the database", notes = "", response = String.class)
382 @Path("/model/{modelName}")
383 @Consumes(MediaType.APPLICATION_JSON)
384 @Produces(MediaType.APPLICATION_JSON)
385 public CldsModel putModel(@PathParam("modelName") String modelName, CldsModel cldsModel) {
386 Date startTime = new Date();
387 LoggingUtils.setRequestContext("CldsService: PUT model", getPrincipalName());
388 isAuthorized(permissionUpdateCl);
389 isAuthorizedForVf(cldsModel);
390 logger.info("PUT model for modelName={}", modelName);
391 logger.info("PUT bpmnText={}", cldsModel.getBpmnText());
392 logger.info("PUT propText={}", cldsModel.getPropText());
393 logger.info("PUT imageText={}", cldsModel.getImageText());
394 cldsModel.setName(modelName);
396 if (cldsModel.getTemplateName() != null) {
397 CldsTemplate template = cldsDao.getTemplate(cldsModel.getTemplateName());
398 if (template != null) {
399 cldsModel.setTemplateId(template.getId());
400 cldsModel.setDocText(template.getPropText());
401 cldsModel.setDocId(template.getPropId());
404 cldsModel.save(cldsDao, getUserId());
405 cldsModel.save(cldsDao, getUserId());
407 LoggingUtils.setTimeContext(startTime, new Date());
408 LoggingUtils.setResponseContext("0", "Put model success", this.getClass().getName());
409 auditLogger.info("PUT model completed");
414 * REST service that retrieves a list of CLDS model names.
416 * @return model names in JSON
418 @ApiOperation(value = "Retrieves a list of CLDS model names", notes = "", response = String.class)
420 @Path("/model-names")
421 @Produces(MediaType.APPLICATION_JSON)
422 public List<ValueItem> getModelNames() {
423 Date startTime = new Date();
424 LoggingUtils.setRequestContext("CldsService: GET model names", getPrincipalName());
425 isAuthorized(permissionReadCl);
426 logger.info("GET list of model names");
427 List<ValueItem> names = cldsDao.getBpmnNames();
429 LoggingUtils.setTimeContext(startTime, new Date());
430 LoggingUtils.setResponseContext("0", "Get model names success", this.getClass().getName());
431 auditLogger.info("GET model names completed");
436 * REST service that saves and processes an action for a CLDS model by name.
443 * @throws TransformerException
444 * @throws ParseException
446 @ApiOperation(value = "Saves and processes an action for a CLDS model by name", notes = "", response = String.class)
448 @Path("/action/{action}/{modelName}")
449 @Consumes(MediaType.APPLICATION_JSON)
450 @Produces(MediaType.APPLICATION_JSON)
451 public CldsModel putModelAndProcessAction(@PathParam("action") String action,
452 @PathParam("modelName") String modelName, @QueryParam("test") String test, CldsModel model)
453 throws TransformerException, ParseException {
454 Date startTime = new Date();
455 LoggingUtils.setRequestContext("CldsService: Process model action", getPrincipalName());
456 String actionCd = action.toUpperCase();
457 SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage,
458 cldsPermissionInstance, actionCd);
459 isAuthorized(permisionManage);
460 isAuthorizedForVf(model);
461 String userid = getUserId();
462 String actionStateCd = CldsEvent.ACTION_STATE_INITIATED;
463 String processDefinitionKey = "clds-process-action-wf";
465 logger.info("PUT actionCd={}", actionCd);
466 logger.info("PUT actionStateCd={}", actionStateCd);
467 logger.info("PUT processDefinitionKey={}", processDefinitionKey);
468 logger.info("PUT modelName={}", modelName);
469 logger.info("PUT test={}", test);
470 logger.info("PUT bpmnText={}", model.getBpmnText());
471 logger.info("PUT propText={}", model.getPropText());
472 logger.info("PUT userid={}", userid);
473 logger.info("PUT getTypeId={}", model.getTypeId());
474 logger.info("PUT deploymentId={}", model.getDeploymentId());
476 if (model.getTemplateName() != null) {
477 CldsTemplate template = cldsDao.getTemplate(model.getTemplateName());
478 if (template != null) {
479 model.setTemplateId(template.getId());
480 model.setDocText(template.getPropText());
481 model.setDocId(template.getPropId());
485 model.setName(modelName);
486 model.save(cldsDao, getUserId());
488 // get vars and format if necessary
489 String prop = model.getPropText();
490 String bpmn = model.getBpmnText();
491 String docText = model.getDocText();
492 String controlName = model.getControlName();
494 String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn);
495 logger.info("PUT bpmnJson={}", bpmnJson);
497 // Flag indicates whether it is triggered by Validation Test button from
499 boolean isTest = false;
500 if (test != null && test.equalsIgnoreCase("true")) {
503 // if action.test.override is true, then any action will be marked
504 // as test=true (even if incoming action request had test=false);
505 // otherwise, test flag will be unchanged on the action request
506 String actionTestOverride = refProp.getStringValue("action.test.override");
507 if (actionTestOverride != null && actionTestOverride.equalsIgnoreCase("true")) {
508 logger.info("PUT actionTestOverride={}", actionTestOverride);
509 logger.info("PUT override test indicator and setting it to true");
513 logger.info("PUT isTest={}", isTest);
515 boolean isInsertTestEvent = false;
516 String insertTestEvent = refProp.getStringValue("action.insert.test.event");
517 if (insertTestEvent != null && insertTestEvent.equalsIgnoreCase("true")) {
518 isInsertTestEvent = true;
520 logger.info("PUT isInsertTestEvent={}", isInsertTestEvent);
522 // determine if requested action is permitted
523 model.validateAction(actionCd);
525 // input variables to camunda process
526 Map<String, Object> variables = new HashMap<>();
527 variables.put("actionCd", actionCd);
528 variables.put("modelProp", prop.getBytes());
529 variables.put("modelBpmnProp", bpmnJson);
530 variables.put("modelName", modelName);
531 variables.put("controlName", controlName);
532 variables.put("docText", docText.getBytes());
533 variables.put("isTest", isTest);
534 variables.put("userid", userid);
535 variables.put("isInsertTestEvent", isInsertTestEvent);
536 logger.info("modelProp - " + prop);
537 logger.info("docText - " + docText);
539 // start camunda process
540 ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinitionKey, variables);
543 logger.info("Started processDefinitionId={}, processInstanceId={}", pi.getProcessDefinitionId(),
544 pi.getProcessInstanceId());
546 // refresh model info from db (get fresh event info)
547 CldsModel retreivedModel = CldsModel.retrieve(cldsDao, modelName, false);
549 if (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT)
550 || actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT)) {
551 // To verify inventory status and modify model status to distribute
552 dcaeInventoryServices.setEventInventory(retreivedModel, getUserId());
553 retreivedModel.save(cldsDao, getUserId());
556 LoggingUtils.setTimeContext(startTime, new Date());
557 LoggingUtils.setResponseContext("0", "Process model action success", this.getClass().getName());
558 auditLogger.info("Process model action completed");
560 return retreivedModel;
564 * REST service that accepts events for a model.
569 @ApiOperation(value = "Accepts events for a model", notes = "", response = String.class)
572 @Consumes(MediaType.APPLICATION_JSON)
573 @Produces(MediaType.APPLICATION_JSON)
574 public String postDcaeEvent(@QueryParam("test") String test, DcaeEvent dcaeEvent) {
575 Date startTime = new Date();
576 LoggingUtils.setRequestContext("CldsService: Post dcae event", getPrincipalName());
577 String userid = null;
578 // TODO: allow auth checking to be turned off by removing the permission
580 if (cldsPermissionTypeClEvent != null && cldsPermissionTypeClEvent.length() > 0) {
581 SecureServicePermission permissionEvent = SecureServicePermission.create(cldsPermissionTypeClEvent,
582 cldsPermissionInstance, dcaeEvent.getEvent());
583 isAuthorized(permissionEvent);
584 userid = getUserId();
587 // Flag indicates whether it is triggered by Validation Test button from
589 boolean isTest = false;
590 if (test != null && test.equalsIgnoreCase("true")) {
594 int instanceCount = 0;
595 if (dcaeEvent.getInstances() != null) {
596 instanceCount = dcaeEvent.getInstances().size();
598 String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID()
599 + " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName()
600 + " instance count=" + instanceCount + " isTest=" + isTest;
601 logger.info("POST dcae event {}", msgInfo);
604 logger.warn("Ignorning test event from DCAE");
606 if (DcaeEvent.EVENT_DEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent())) {
607 CldsModel.insertModelInstance(cldsDao, dcaeEvent, userid);
609 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(),
610 CldsEvent.ACTION_STATE_RECEIVED, null);
614 LoggingUtils.setTimeContext(startTime, new Date());
615 LoggingUtils.setResponseContext("0", "Post dcae event success", this.getClass().getName());
616 auditLogger.info("Post dcae event completed");
622 * REST service that retrieves sdc services
626 @ApiOperation(value = "Retrieves sdc services", notes = "", response = String.class)
628 @Path("/sdc/services")
629 @Produces(MediaType.APPLICATION_JSON)
630 public String getSdcServices() {
631 Date startTime = new Date();
632 LoggingUtils.setRequestContext("CldsService: GET sdc services", getPrincipalName());
635 String responseStr = sdcCatalogServices.getSdcServicesInformation(null);
637 retStr = createUiServiceFormatJson(responseStr);
638 } catch (IOException e) {
639 logger.error("IOException during SDC communication", e);
640 throw new SdcCommunicationException("IOException during SDC communication", e);
643 logger.info("value of sdcServices : {}", retStr);
645 LoggingUtils.setTimeContext(startTime, new Date());
646 LoggingUtils.setResponseContext("0", "Get sdc services success", this.getClass().getName());
647 auditLogger.info("GET sdc services completed");
652 * REST service that retrieves total properties required by UI
654 * @throws IOException
658 @ApiOperation(value = "Retrieves total properties required by UI", notes = "", response = String.class)
661 @Produces(MediaType.APPLICATION_JSON)
662 public String getSdcProperties() throws IOException {
663 return createPropertiesObjectByUUID(getGlobalCldsString(), "{}");
667 * REST service that retrieves total properties by using invariantUUID based
668 * on refresh and non refresh
672 @ApiOperation(value = "Retrieves total properties by using invariantUUID based on refresh and non refresh", notes = "", response = String.class)
674 @Path("/properties/{serviceInvariantUUID}")
675 @Produces(MediaType.APPLICATION_JSON)
676 public String getSdcPropertiesByServiceUUIDForRefresh(
677 @PathParam("serviceInvariantUUID") String serviceInvariantUUID,
678 @DefaultValue("false") @QueryParam("refresh") String refresh) throws Exception {
679 Date startTime = new Date();
680 LoggingUtils.setRequestContext("CldsService: GET sdc properties by uuid", getPrincipalName());
681 CldsServiceData cldsServiceData = new CldsServiceData();
682 cldsServiceData.setServiceInvariantUUID(serviceInvariantUUID);
684 boolean isCldsSdcDataExpired = true;
685 // To getcldsService information from database cache using invariantUUID
686 // only when refresh = false
687 if (refresh != null && refresh.equalsIgnoreCase("false")) {
688 cldsServiceData = cldsServiceData.getCldsServiceCache(cldsDao, serviceInvariantUUID);
689 // If cldsService is available in database Cache , verify is data
691 if (cldsServiceData != null) {
692 isCldsSdcDataExpired = sdcCatalogServices.isCldsSdcCacheDataExpired(cldsServiceData);
695 // If user Requested for refresh or database cache expired , get all
696 // data from sdc api.
697 if ((refresh != null && refresh.equalsIgnoreCase("true")) || isCldsSdcDataExpired) {
698 cldsServiceData = sdcCatalogServices.getCldsServiceDataWithAlarmConditions(serviceInvariantUUID);
699 CldsDBServiceCache cldsDBServiceCache = sdcCatalogServices
700 .getCldsDbServiceCacheUsingCldsServiceData(cldsServiceData);
701 if (cldsDBServiceCache != null && cldsDBServiceCache.getInvariantId() != null
702 && cldsDBServiceCache.getServiceId() != null) {
703 cldsServiceData.setCldsServiceCache(cldsDao, cldsDBServiceCache);
707 // filter out VFs the user is not authorized for
708 cldsServiceData.filterVfs(this);
711 LoggingUtils.setTimeContext(startTime, new Date());
712 LoggingUtils.setResponseContext("0", "Get sdc properties by uuid success", this.getClass().getName());
713 auditLogger.info("GET sdc properties by uuid completed");
715 // format retrieved data into properties json
716 return sdcCatalogServices.createPropertiesObjectByUUID(getGlobalCldsString(), cldsServiceData);
720 * Determine if the user is authorized for a particular VF by its invariant
723 * @param vfInvariantUuid
724 * @throws NotAuthorizedException
727 public boolean isAuthorizedForVf(String vfInvariantUuid) {
728 if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) {
729 SecureServicePermission permission = SecureServicePermission.create(cldsPermissionTypeFilterVf,
730 cldsPermissionInstance, vfInvariantUuid);
731 return isAuthorized(permission);
733 // if CLDS_PERMISSION_TYPE_FILTER_VF property is not provided, then
734 // VF filtering is turned off
735 logger.warn("VF filtering turned off");
741 * Determine if the user is authorized for a particular VF by its invariant
742 * UUID. If not authorized, then NotAuthorizedException is thrown.
747 private boolean isAuthorizedForVf(CldsModel model) {
748 String vf = ModelProperties.getVf(model);
749 if (vf == null || vf.length() == 0) {
750 logger.info("VF not found in model");
753 return isAuthorizedForVf(vf);
757 private String createUiServiceFormatJson(String responseStr) throws IOException {
758 if (StringUtils.isBlank(responseStr)) {
761 ObjectMapper objectMapper = new ObjectMapper();
762 List<CldsSdcServiceInfo> rawList = objectMapper.readValue(responseStr,
763 objectMapper.getTypeFactory().constructCollectionType(List.class, CldsSdcServiceInfo.class));
764 ObjectNode invariantIdServiceNode = objectMapper.createObjectNode();
765 ObjectNode serviceNode = objectMapper.createObjectNode();
766 logger.info("value of cldsserviceiNfolist: {}", rawList);
767 if (rawList != null && !rawList.isEmpty()) {
768 List<CldsSdcServiceInfo> cldsSdcServiceInfoList = sdcCatalogServices.removeDuplicateServices(rawList);
770 for (CldsSdcServiceInfo currCldsSdcServiceInfo : cldsSdcServiceInfoList) {
771 if (currCldsSdcServiceInfo != null) {
772 invariantIdServiceNode.put(currCldsSdcServiceInfo.getInvariantUUID(),
773 currCldsSdcServiceInfo.getName());
776 serviceNode.putPOJO("service", invariantIdServiceNode);
778 return serviceNode.toString();
781 private String createPropertiesObjectByUUID(String globalProps, String cldsResponseStr) throws IOException {
782 ObjectMapper mapper = new ObjectMapper();
783 CldsSdcServiceDetail cldsSdcServiceDetail = mapper.readValue(cldsResponseStr, CldsSdcServiceDetail.class);
784 ObjectNode globalPropsJson = null;
785 if (cldsSdcServiceDetail != null && cldsSdcServiceDetail.getUuid() != null) {
787 * to create json with vf, alarm and locations
789 ObjectNode serviceObjectNode = createEmptyVfAlarmObject(mapper);
790 ObjectNode vfObjectNode = mapper.createObjectNode();
793 * to create json with vf and vfresourceId
795 createVfObjectNode(vfObjectNode, mapper, cldsSdcServiceDetail.getResources());
796 serviceObjectNode.putPOJO(cldsSdcServiceDetail.getInvariantUUID(), vfObjectNode);
797 ObjectNode byServiceBasicObjetNode = mapper.createObjectNode();
798 byServiceBasicObjetNode.putPOJO("byService", serviceObjectNode);
801 * to create json with VFC Node
803 ObjectNode emptyvfcobjectNode = createByVFCObjectNode(mapper, cldsSdcServiceDetail.getResources());
804 byServiceBasicObjetNode.putPOJO("byVf", emptyvfcobjectNode);
805 globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
806 globalPropsJson.putPOJO("shared", byServiceBasicObjetNode);
807 logger.info("valuie of objNode: {}", globalPropsJson);
810 * to create json with total properties when no serviceUUID passed
812 globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
814 return globalPropsJson.toString();
817 private ObjectNode createEmptyVfAlarmObject(ObjectMapper mapper) {
818 ObjectNode emptyObjectNode = mapper.createObjectNode();
819 emptyObjectNode.put("", "");
820 ObjectNode vfObjectNode = mapper.createObjectNode();
821 vfObjectNode.putPOJO("vf", emptyObjectNode);
822 vfObjectNode.putPOJO("location", emptyObjectNode);
823 vfObjectNode.putPOJO("alarmCondition", emptyObjectNode);
824 ObjectNode emptyServiceObjectNode = mapper.createObjectNode();
825 emptyServiceObjectNode.putPOJO("", vfObjectNode);
826 return emptyServiceObjectNode;
829 private void createVfObjectNode(ObjectNode vfObjectNode2, ObjectMapper mapper,
830 List<CldsSdcResource> rawCldsSdcResourceList) {
831 ObjectNode vfNode = mapper.createObjectNode();
834 // To remove repeated resource instance name from
835 // resourceInstanceList
836 List<CldsSdcResource> cldsSdcResourceList = sdcCatalogServices
837 .removeDuplicateSdcResourceInstances(rawCldsSdcResourceList);
839 * Creating vf resource node using cldsSdcResource Object
841 if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
842 for (CldsSdcResource cldsSdcResource : cldsSdcResourceList) {
843 if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
844 vfNode.put(cldsSdcResource.getResourceUUID(), cldsSdcResource.getResourceName());
848 vfObjectNode2.putPOJO("vf", vfNode);
851 * creating location json object using properties file value
853 ObjectNode locationJsonNode;
855 locationJsonNode = (ObjectNode) mapper.readValue(refProp.getStringValue("ui.location.default"),
857 } catch (IOException e) {
858 logger.error("Unable to load ui.location.default JSON in clds-references.properties properly", e);
859 throw new CldsConfigException(
860 "Unable to load ui.location.default JSON in clds-references.properties properly", e);
862 vfObjectNode2.putPOJO("location", locationJsonNode);
865 * creating alarm json object using properties file value
867 String alarmStringValue = refProp.getStringValue("ui.alarm.default");
868 logger.info("value of alarm: {}", alarmStringValue);
869 ObjectNode alarmStringJsonNode;
871 alarmStringJsonNode = (ObjectNode) mapper.readValue(alarmStringValue, JsonNode.class);
872 } catch (IOException e) {
873 logger.error("Unable to ui.alarm.default JSON in clds-references.properties properly", e);
874 throw new CldsConfigException("Unable to load ui.alarm.default JSON in clds-references.properties properly",
877 vfObjectNode2.putPOJO("alarmCondition", alarmStringJsonNode);
881 private ObjectNode createByVFCObjectNode(ObjectMapper mapper, List<CldsSdcResource> cldsSdcResourceList) {
882 ObjectNode emptyObjectNode = mapper.createObjectNode();
883 ObjectNode emptyvfcobjectNode = mapper.createObjectNode();
884 ObjectNode vfCObjectNode = mapper.createObjectNode();
885 vfCObjectNode.putPOJO("vfC", emptyObjectNode);
886 ObjectNode subVfCObjectNode = mapper.createObjectNode();
887 subVfCObjectNode.putPOJO("vfc", emptyObjectNode);
888 if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
889 for (CldsSdcResource cldsSdcResource : cldsSdcResourceList) {
890 if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
891 vfCObjectNode.putPOJO(cldsSdcResource.getResourceUUID(), subVfCObjectNode);
895 emptyvfcobjectNode.putPOJO("", vfCObjectNode);
896 return emptyvfcobjectNode;
900 @Path("/deploy/{modelName}")
901 @Consumes(MediaType.APPLICATION_JSON)
902 @Produces(MediaType.APPLICATION_JSON)
903 public CldsModel deployModel(@PathParam("action") String action, @PathParam("modelName") String modelName,
904 @QueryParam("test") String test, CldsModel model) throws Exception {
905 Date startTime = new Date();
906 LoggingUtils.setRequestContext("CldsService: Deploy model", getPrincipalName());
907 String deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId";
908 String createNewDeploymentStatusUrl = dcaeDispatcherServices.createNewDeployment(deploymentId,
910 String operationStatus = "processing";
911 long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10);
912 while ("processing".equalsIgnoreCase(operationStatus)) {
913 // Break the loop if waiting for more than 10 mins
914 if (waitingTime < System.nanoTime()) {
917 operationStatus = dcaeDispatcherServices.getOperationStatus(createNewDeploymentStatusUrl);
919 if ("succeeded".equalsIgnoreCase(operationStatus)) {
920 String artifactName = model.getControlName();
921 if (artifactName != null) {
922 artifactName = artifactName + ".yml";
924 DcaeEvent dcaeEvent = new DcaeEvent();
925 /* set dcae events */
926 dcaeEvent.setArtifactName(artifactName);
927 dcaeEvent.setEvent(DcaeEvent.EVENT_DEPLOYMENT);
928 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(),
929 CldsEvent.ACTION_STATE_RECEIVED, null);
930 model.setDeploymentId(deploymentId);
931 model.save(cldsDao, getUserId());
933 logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
934 throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
935 "Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
937 logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId);
939 LoggingUtils.setTimeContext(startTime, new Date());
940 LoggingUtils.setResponseContext("0", "Deploy model success", this.getClass().getName());
941 auditLogger.info("Deploy model completed");
946 @Path("/undeploy/{modelName}")
947 @Consumes(MediaType.APPLICATION_JSON)
948 @Produces(MediaType.APPLICATION_JSON)
949 public CldsModel unDeployModel(@PathParam("action") String action, @PathParam("modelName") String modelName,
950 @QueryParam("test") String test, CldsModel model) throws IOException {
951 Date startTime = new Date();
952 LoggingUtils.setRequestContext("CldsService: Undeploy model", getPrincipalName());
953 String operationStatusUndeployUrl = dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(),
955 String operationStatus = "processing";
956 long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10);
957 while ("processing".equalsIgnoreCase(operationStatus)) {
958 if (waitingTime < System.nanoTime()) {
961 operationStatus = dcaeDispatcherServices.getOperationStatus(operationStatusUndeployUrl);
963 if ("succeeded".equalsIgnoreCase(operationStatus)) {
964 String artifactName = model.getControlName();
965 if (artifactName != null) {
966 artifactName = artifactName + ".yml";
968 DcaeEvent dcaeEvent = new DcaeEvent();
970 dcaeEvent.setArtifactName(artifactName);
971 dcaeEvent.setEvent(DcaeEvent.EVENT_UNDEPLOYMENT);
972 CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(),
973 CldsEvent.ACTION_STATE_RECEIVED, null);
974 model.setDeploymentId(null);
975 model.save(cldsDao, getUserId());
977 logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
978 throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
979 "Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
981 logger.info("Undeploy model (" + modelName + ") succeeded.");
983 LoggingUtils.setTimeContext(startTime, new Date());
984 LoggingUtils.setResponseContext("0", "Undeploy model success", this.getClass().getName());
985 auditLogger.info("Undeploy model completed");
989 private String getGlobalCldsString() {
991 if (null == globalCldsProperties) {
992 globalCldsProperties = new Properties();
993 globalCldsProperties.load(appContext.getResource(globalClds).getInputStream());
995 return (String) globalCldsProperties.get("globalCldsProps");
996 } catch (IOException e) {
997 logger.error("Unable to load the globalClds due to an exception", e);
998 throw new CldsConfigException("Unable to load the globalClds due to an exception", e);