Add encryption for passwords
[clamp.git] / src / main / java / org / onap / clamp / clds / service / CldsService.java
index 509535c..1570634 100644 (file)
 
 package org.onap.clamp.clds.service;
 
+import com.att.ajsc.common.AjscService;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
 import java.io.IOException;
 import java.io.InputStream;
-import java.sql.SQLException;
+import java.security.GeneralSecurityException;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
@@ -35,6 +42,7 @@ import java.util.UUID;
 import java.util.concurrent.TimeUnit;
 
 import javax.annotation.PostConstruct;
+import javax.ws.rs.BadRequestException;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DefaultValue;
 import javax.ws.rs.GET;
@@ -46,22 +54,25 @@ import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
 import javax.ws.rs.QueryParam;
 import javax.ws.rs.core.MediaType;
-import javax.xml.transform.TransformerConfigurationException;
 import javax.xml.transform.TransformerException;
 
 import org.apache.commons.lang3.StringUtils;
 import org.camunda.bpm.engine.RuntimeService;
 import org.camunda.bpm.engine.runtime.ProcessInstance;
-import org.jboss.resteasy.spi.BadRequestException;
+import org.json.simple.parser.ParseException;
 import org.onap.clamp.clds.client.DcaeDispatcherServices;
 import org.onap.clamp.clds.client.DcaeInventoryServices;
 import org.onap.clamp.clds.client.SdcCatalogServices;
 import org.onap.clamp.clds.dao.CldsDao;
+import org.onap.clamp.clds.exception.CldsConfigException;
+import org.onap.clamp.clds.exception.SdcCommunicationException;
+import org.onap.clamp.clds.exception.policy.PolicyClientException;
 import org.onap.clamp.clds.model.CldsDBServiceCache;
 import org.onap.clamp.clds.model.CldsEvent;
 import org.onap.clamp.clds.model.CldsHealthCheck;
 import org.onap.clamp.clds.model.CldsInfo;
 import org.onap.clamp.clds.model.CldsModel;
+import org.onap.clamp.clds.model.CldsModelProp;
 import org.onap.clamp.clds.model.CldsSdcResource;
 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
 import org.onap.clamp.clds.model.CldsSdcServiceInfo;
@@ -69,6 +80,7 @@ import org.onap.clamp.clds.model.CldsServiceData;
 import org.onap.clamp.clds.model.CldsTemplate;
 import org.onap.clamp.clds.model.DcaeEvent;
 import org.onap.clamp.clds.model.ValueItem;
+import org.onap.clamp.clds.model.prop.AbstractModelElement;
 import org.onap.clamp.clds.model.prop.ModelProperties;
 import org.onap.clamp.clds.model.refprop.RefProp;
 import org.onap.clamp.clds.transform.XslTransformer;
@@ -76,14 +88,8 @@ import org.onap.clamp.clds.util.LoggingUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.ApplicationContext;
-
-import com.att.ajsc.common.AjscService;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.client.HttpClientErrorException;
 
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
@@ -92,43 +98,29 @@ import io.swagger.annotations.ApiOperation;
  * Service to save and retrieve the CLDS model attributes.
  */
 @AjscService
-@Api(value = "/clds", description = "Clds operations")
+@Api(value = "/clds")
 @Path("/clds")
 public class CldsService extends SecureServiceBase {
-
+    protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger();
     @Autowired
-    private ApplicationContext      appContext;
-
-    private static final String     RESOURCE_NAME = "clds-version.properties";
-
-    protected static final EELFLogger       logger        = EELFManager.getInstance().getLogger(CldsService.class);
-    protected static final EELFLogger auditLogger   = EELFManager.getInstance().getAuditLogger();
-
+    private ApplicationContext        appContext;
+    private static final String       RESOURCE_NAME  = "clds-version.properties";
     @Value("${CLDS_PERMISSION_TYPE_CL:permission-type-cl}")
-    private String                  cldsPersmissionTypeCl;
-
+    private String                    cldsPersmissionTypeCl;
     @Value("${CLDS_PERMISSION_TYPE_CL_MANAGE:permission-type-cl-manage}")
-    private String                  cldsPermissionTypeClManage;
-
+    private String                    cldsPermissionTypeClManage;
     @Value("${CLDS_PERMISSION_TYPE_CL_EVENT:permission-type-cl-event}")
-    private String                  cldsPermissionTypeClEvent;
-
+    private String                    cldsPermissionTypeClEvent;
     @Value("${CLDS_PERMISSION_TYPE_FILTER_VF:permission-type-filter-vf}")
-    private String                  cldsPermissionTypeFilterVf;
-
+    private String                    cldsPermissionTypeFilterVf;
     @Value("${CLDS_PERMISSION_TYPE_TEMPLATE:permission-type-template}")
-    private String                  cldsPermissionTypeTemplate;
-
+    private String                    cldsPermissionTypeTemplate;
     @Value("${CLDS_PERMISSION_INSTANCE:dev}")
-    private String                  cldsPermissionInstance;
-
-    private SecureServicePermission permissionReadCl;
-
-    private SecureServicePermission permissionUpdateCl;
-
-    private SecureServicePermission permissionReadTemplate;
-
-    private SecureServicePermission permissionUpdateTemplate;
+    private String                    cldsPermissionInstance;
+    private SecureServicePermission   permissionReadCl;
+    private SecureServicePermission   permissionUpdateCl;
+    private SecureServicePermission   permissionReadTemplate;
+    private SecureServicePermission   permissionUpdateTemplate;
 
     @PostConstruct
     private final void afterConstruction() {
@@ -142,25 +134,19 @@ public class CldsService extends SecureServiceBase {
 
     @Value("${org.onap.clamp.config.files.globalClds:'classpath:/clds/globalClds.properties'}")
     private String                 globalClds;
-
     private Properties             globalCldsProperties;
-
     @Autowired
     private CldsDao                cldsDao;
     @Autowired
     private RuntimeService         runtimeService;
     @Autowired
     private XslTransformer         cldsBpmnTransformer;
-
     @Autowired
     private RefProp                refProp;
-
     @Autowired
     private SdcCatalogServices     sdcCatalogServices;
-
     @Autowired
     private DcaeDispatcherServices dcaeDispatcherServices;
-
     @Autowired
     private DcaeInventoryServices  dcaeInventoryServices;
 
@@ -177,78 +163,68 @@ public class CldsService extends SecureServiceBase {
      * that is currently installed from pom.xml file 3. User permissions
      *
      */
-
     @GET
     @Path("/cldsInfo")
     @Produces(MediaType.APPLICATION_JSON)
     public CldsInfo getCldsInfo() {
-
         CldsInfo cldsInfo = new CldsInfo();
-
+        Date startTime = new Date();
+        LoggingUtils.setRequestContext("CldsService: GET cldsInfo", getPrincipalName());
+        LoggingUtils.setTimeContext(startTime, new Date());
         // Get the user info
         cldsInfo.setUserName(getUserName());
-
         // Get CLDS application version
         String cldsVersion = "";
         Properties props = new Properties();
-        InputStream resourceStream = null;
-
-        try {
-            ClassLoader loader = Thread.currentThread().getContextClassLoader();
-            resourceStream = loader.getResourceAsStream(RESOURCE_NAME);
+        ClassLoader loader = Thread.currentThread().getContextClassLoader();
+        try (InputStream resourceStream = loader.getResourceAsStream(RESOURCE_NAME)) {
             props.load(resourceStream);
             cldsVersion = props.getProperty("clds.version");
         } catch (Exception ex) {
-            ex.printStackTrace();
-        } finally {
-            if (resourceStream != null) {
-                try {
-                    resourceStream.close();
-                } catch (IOException e) {
-                    e.printStackTrace();
-                }
-            }
+            logger.error("Exception caught during the clds.version reading", ex);
         }
         cldsInfo.setCldsVersion(cldsVersion);
-
         // Get the user list of permissions
-        cldsInfo.setPermissionReadCl(isAuthorized(permissionReadCl));
-        cldsInfo.setPermissionUpdateCl(isAuthorized(permissionUpdateCl));
-        cldsInfo.setPermissionReadTemplate(isAuthorized(permissionReadTemplate));
-        cldsInfo.setPermissionUpdateTemplate(isAuthorized(permissionUpdateTemplate));
+        cldsInfo.setPermissionReadCl(isAuthorizedNoException(permissionReadCl));
+        cldsInfo.setPermissionUpdateCl(isAuthorizedNoException(permissionUpdateCl));
+        cldsInfo.setPermissionReadTemplate(isAuthorizedNoException(permissionReadTemplate));
+        cldsInfo.setPermissionUpdateTemplate(isAuthorizedNoException(permissionUpdateTemplate));
+        // audit log
+        LoggingUtils.setTimeContext(startTime, new Date());
+        LoggingUtils.setResponseContext("0", "Get cldsInfo success", this.getClass().getName());
+        securityLogger.info("GET cldsInfo completed");
         return cldsInfo;
     }
 
+    /**
+     * REST service that retrieves clds healthcheck information.
+     * 
+     * @return CldsHealthCheck class containing healthcheck info
+     */
     @GET
     @Path("/healthcheck")
     @Produces(MediaType.APPLICATION_JSON)
     public CldsHealthCheck gethealthcheck() {
-
         CldsHealthCheck cldsHealthCheck = new CldsHealthCheck();
-
+        Date startTime = new Date();
+        LoggingUtils.setRequestContext("CldsService: GET healthcheck", getPrincipalName());
+        LoggingUtils.setTimeContext(startTime, new Date());
         try {
             cldsDao.doHealthCheck();
             cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
             cldsHealthCheck.setHealthCheckStatus("UP");
             cldsHealthCheck.setDescription("OK");
-        } catch (SQLException e) {
-            logger.error("CLAMP application DB Error" + e);
-            cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
-            cldsHealthCheck.setHealthCheckStatus("DOWN");
-            cldsHealthCheck.setDescription("NOT-OK");
-            // return Response.status(500).entity("Database down for CLDS
-            // application").build();
         } catch (Exception e) {
-            logger.error("CLAMP application DB Error" + e);
+            logger.error("CLAMP application DB Error", e);
             cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
             cldsHealthCheck.setHealthCheckStatus("DOWN");
             cldsHealthCheck.setDescription("NOT-OK");
-            // return Response.status(500).entity("Database down for CLDS
-            // application").build();
         }
-
+        // audit log
+        LoggingUtils.setTimeContext(startTime, new Date());
+        LoggingUtils.setResponseContext("0", "Get healthcheck success", this.getClass().getName());
+        securityLogger.info("GET healthcheck completed");
         return cldsHealthCheck;
-
     }
 
     /**
@@ -276,32 +252,6 @@ public class CldsService extends SecureServiceBase {
         return model.getBpmnText();
     }
 
-    /**
-     * REST service that saves BPMN for a CLDS model by name in the database.
-     * This is subset of the json putModel. This is only expected to be used for
-     * testing purposes, not by the UI.
-     *
-     * @param modelName
-     */
-    @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)
-    @PUT
-    @Path("/model/bpmn/{modelName}")
-    @Consumes(MediaType.TEXT_XML)
-    public String putBpmnXml(@PathParam("modelName") String modelName, String bpmnText) {
-        LoggingUtils.setRequestContext("CldsService: PUT model bpmn", getPrincipalName());
-        isAuthorized(permissionUpdateCl);
-        logger.info("PUT bpmnText for modelName={}", modelName);
-        logger.info("PUT bpmnText={}", bpmnText);
-        CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, true);
-        cldsModel.setBpmnText(bpmnText);
-        cldsModel.save(cldsDao, getUserId());
-        // audit log
-        LoggingUtils.setTimeContext(new Date(), new Date());
-        LoggingUtils.setResponseContext("0", "Put model bpmn success", this.getClass().getName());
-        auditLogger.info("PUT model bpmn completed");
-        return "wrote bpmnText for modelName=" + modelName;
-    }
-
     /**
      * REST service that retrieves image for a CLDS model name from the
      * database. This is subset of the json getModel. This is only expected to
@@ -327,45 +277,17 @@ public class CldsService extends SecureServiceBase {
         return model.getImageText();
     }
 
-    /**
-     * REST service that saves image for a CLDS model by name in the database.
-     * This is subset of the json putModel. This is only expected to be used for
-     * testing purposes, not by the UI.
-     *
-     * @param modelName
-     */
-    @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)
-    @PUT
-    @Path("/model/image/{modelName}")
-    @Consumes(MediaType.TEXT_XML)
-    public String putImageXml(@PathParam("modelName") String modelName, String imageText) {
-        Date startTime = new Date();
-        LoggingUtils.setRequestContext("CldsService: PUT model image", getPrincipalName());
-        isAuthorized(permissionUpdateCl);
-        logger.info("PUT iamgeText for modelName={}", modelName);
-        logger.info("PUT imageText={}", imageText);
-        CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, true);
-        cldsModel.setImageText(imageText);
-        cldsModel.save(cldsDao, getUserId());
-        // audit log
-        LoggingUtils.setTimeContext(startTime, new Date());
-        LoggingUtils.setResponseContext("0", "Put model image success", this.getClass().getName());
-        auditLogger.info("PUT model image completed");
-        return "wrote imageText for modelName=" + modelName;
-    }
-
     /**
      * REST service that retrieves a CLDS model by name from the database.
      *
      * @param modelName
      * @return clds model - clds model for the given model name
-     * @throws NotAuthorizedException
      */
     @ApiOperation(value = "Retrieves a CLDS model by name from the database", notes = "", response = String.class)
     @GET
     @Path("/model/{modelName}")
     @Produces(MediaType.APPLICATION_JSON)
-    public CldsModel getModel(@PathParam("modelName") String modelName) throws NotAuthorizedException {
+    public CldsModel getModel(@PathParam("modelName") String modelName) {
         Date startTime = new Date();
         LoggingUtils.setRequestContext("CldsService: GET model", getPrincipalName());
         isAuthorized(permissionReadCl);
@@ -373,9 +295,8 @@ public class CldsService extends SecureServiceBase {
         CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false);
         isAuthorizedForVf(cldsModel);
         cldsModel.setUserAuthorizedToUpdate(isAuthorizedNoException(permissionUpdateCl));
-
         /**
-         * Checking condtion whether our CLDS model can call INventory Method
+         * Checking condition whether our CLDS model can call INventory Method
          */
         if (cldsModel.canInventoryCall()) {
             try {
@@ -400,16 +321,13 @@ public class CldsService extends SecureServiceBase {
      * REST service that saves a CLDS model by name in the database.
      *
      * @param modelName
-     * @throws TransformerException
-     * @throws TransformerConfigurationException
      */
     @ApiOperation(value = "Saves a CLDS model by name in the database", notes = "", response = String.class)
     @PUT
     @Path("/model/{modelName}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public CldsModel putModel(@PathParam("modelName") String modelName, CldsModel cldsModel)
-            throws TransformerException {
+    public CldsModel putModel(@PathParam("modelName") String modelName, CldsModel cldsModel) {
         Date startTime = new Date();
         LoggingUtils.setRequestContext("CldsService: PUT model", getPrincipalName());
         isAuthorized(permissionUpdateCl);
@@ -419,7 +337,12 @@ public class CldsService extends SecureServiceBase {
         logger.info("PUT propText={}", cldsModel.getPropText());
         logger.info("PUT imageText={}", cldsModel.getImageText());
         cldsModel.setName(modelName);
-
+        try {
+            duplicateCheckforServiceVf(modelName, cldsModel.getPropText());
+        } catch (IOException | BadRequestException e) {
+            logger.error("Exception occured during duplicate check for service and VF", e);
+            throw new CldsConfigException(e.getMessage(), e);
+        }
         if (cldsModel.getTemplateName() != null) {
             CldsTemplate template = cldsDao.getTemplate(cldsModel.getTemplateName());
             if (template != null) {
@@ -429,7 +352,6 @@ public class CldsService extends SecureServiceBase {
             }
         }
         cldsModel.save(cldsDao, getUserId());
-        cldsModel.save(cldsDao, getUserId());
         // audit log
         LoggingUtils.setTimeContext(startTime, new Date());
         LoggingUtils.setResponseContext("0", "Put model success", this.getClass().getName());
@@ -447,9 +369,9 @@ public class CldsService extends SecureServiceBase {
     @Path("/model-names")
     @Produces(MediaType.APPLICATION_JSON)
     public List<ValueItem> getModelNames() {
-        // isAuthorized(permissionReadCl);
         Date startTime = new Date();
         LoggingUtils.setRequestContext("CldsService: GET model names", getPrincipalName());
+        isAuthorized(permissionReadCl);
         logger.info("GET list of model names");
         List<ValueItem> names = cldsDao.getBpmnNames();
         // audit log
@@ -467,9 +389,9 @@ public class CldsService extends SecureServiceBase {
      * @param test
      * @param model
      * @return
-     * @throws Exception
-     * @throws JsonProcessingException
-     * @throws NotAuthorizedException
+     * @throws TransformerException
+     * @throws ParseException
+     * @throws GeneralSecurityException
      */
     @ApiOperation(value = "Saves and processes an action for a CLDS model by name", notes = "", response = String.class)
     @PUT
@@ -478,7 +400,7 @@ public class CldsService extends SecureServiceBase {
     @Produces(MediaType.APPLICATION_JSON)
     public CldsModel putModelAndProcessAction(@PathParam("action") String action,
             @PathParam("modelName") String modelName, @QueryParam("test") String test, CldsModel model)
-            throws Exception {
+            throws TransformerException, ParseException, GeneralSecurityException {
         Date startTime = new Date();
         LoggingUtils.setRequestContext("CldsService: Process model action", getPrincipalName());
         String actionCd = action.toUpperCase();
@@ -489,7 +411,6 @@ public class CldsService extends SecureServiceBase {
         String userid = getUserId();
         String actionStateCd = CldsEvent.ACTION_STATE_INITIATED;
         String processDefinitionKey = "clds-process-action-wf";
-
         logger.info("PUT actionCd={}", actionCd);
         logger.info("PUT actionStateCd={}", actionStateCd);
         logger.info("PUT processDefinitionKey={}", processDefinitionKey);
@@ -500,7 +421,6 @@ public class CldsService extends SecureServiceBase {
         logger.info("PUT userid={}", userid);
         logger.info("PUT getTypeId={}", model.getTypeId());
         logger.info("PUT deploymentId={}", model.getDeploymentId());
-
         if (model.getTemplateName() != null) {
             CldsTemplate template = cldsDao.getTemplate(model.getTemplateName());
             if (template != null) {
@@ -512,24 +432,19 @@ public class CldsService extends SecureServiceBase {
         // save model to db
         model.setName(modelName);
         model.save(cldsDao, getUserId());
-
         // get vars and format if necessary
         String prop = model.getPropText();
         String bpmn = model.getBpmnText();
         String docText = model.getDocText();
         String controlName = model.getControlName();
-
         String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn);
         logger.info("PUT bpmnJson={}", bpmnJson);
-
-        // Flag indicates whether it is triggered by Validation Test button from UI
+        // Flag indicates whether it is triggered by Validation Test button from
+        // UI
         boolean isTest = false;
         if (test != null && test.equalsIgnoreCase("true")) {
-               isTest = true;
+            isTest = true;
         } else {
-            // if action.test.override is true, then any action will be marked
-            // as test=true (even if incoming action request had test=false);
-            // otherwise, test flag will be unchanged on the action request
             String actionTestOverride = refProp.getStringValue("action.test.override");
             if (actionTestOverride != null && actionTestOverride.equalsIgnoreCase("true")) {
                 logger.info("PUT actionTestOverride={}", actionTestOverride);
@@ -538,17 +453,14 @@ public class CldsService extends SecureServiceBase {
             }
         }
         logger.info("PUT isTest={}", isTest);
-
         boolean isInsertTestEvent = false;
         String insertTestEvent = refProp.getStringValue("action.insert.test.event");
         if (insertTestEvent != null && insertTestEvent.equalsIgnoreCase("true")) {
             isInsertTestEvent = true;
         }
         logger.info("PUT isInsertTestEvent={}", isInsertTestEvent);
-
         // determine if requested action is permitted
         model.validateAction(actionCd);
-
         // input variables to camunda process
         Map<String, Object> variables = new HashMap<>();
         variables.put("actionCd", actionCd);
@@ -562,17 +474,18 @@ public class CldsService extends SecureServiceBase {
         variables.put("isInsertTestEvent", isInsertTestEvent);
         logger.info("modelProp - " + prop);
         logger.info("docText - " + docText);
-
-        // start camunda process
-        ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinitionKey, variables);
-
-        // log process info
-        logger.info("Started processDefinitionId={}, processInstanceId={}", pi.getProcessDefinitionId(),
-                pi.getProcessInstanceId());
-
+        try {
+            // start camunda process
+            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinitionKey, variables);
+            // log process info
+            logger.info("Started processDefinitionId={}, processInstanceId={}", pi.getProcessDefinitionId(),
+                    pi.getProcessInstanceId());
+        } catch (SdcCommunicationException | PolicyClientException | BadRequestException e) {
+            logger.error("Exception occured during invoking bpmn process", e);
+            throw new CldsConfigException(e.getMessage(), e);
+        }
         // refresh model info from db (get fresh event info)
         CldsModel retreivedModel = CldsModel.retrieve(cldsDao, modelName, false);
-
         if (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT)
                 || actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT)) {
             // To verify inventory status and modify model status to distribute
@@ -583,7 +496,6 @@ public class CldsService extends SecureServiceBase {
         LoggingUtils.setTimeContext(startTime, new Date());
         LoggingUtils.setResponseContext("0", "Process model action success", this.getClass().getName());
         auditLogger.info("Process model action completed");
-
         return retreivedModel;
     }
 
@@ -592,14 +504,13 @@ public class CldsService extends SecureServiceBase {
      *
      * @param test
      * @param dcaeEvent
-     * @throws BadRequestException
      */
     @ApiOperation(value = "Accepts events for a model", notes = "", response = String.class)
     @POST
     @Path("/dcae/event")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public String postDcaeEvent(@QueryParam("test") String test, DcaeEvent dcaeEvent) throws BadRequestException {
+    public String postDcaeEvent(@QueryParam("test") String test, DcaeEvent dcaeEvent) {
         Date startTime = new Date();
         LoggingUtils.setRequestContext("CldsService: Post dcae event", getPrincipalName());
         String userid = null;
@@ -611,13 +522,12 @@ public class CldsService extends SecureServiceBase {
             isAuthorized(permissionEvent);
             userid = getUserId();
         }
-
-        // Flag indicates whether it is triggered by Validation Test button from UI
+        // Flag indicates whether it is triggered by Validation Test button from
+        // UI
         boolean isTest = false;
         if (test != null && test.equalsIgnoreCase("true")) {
-               isTest = true;
+            isTest = true;
         }
-
         int instanceCount = 0;
         if (dcaeEvent.getInstances() != null) {
             instanceCount = dcaeEvent.getInstances().size();
@@ -626,7 +536,6 @@ public class CldsService extends SecureServiceBase {
                 + " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName()
                 + " instance count=" + instanceCount + " isTest=" + isTest;
         logger.info("POST dcae event {}", msgInfo);
-
         if (isTest) {
             logger.warn("Ignorning test event from DCAE");
         } else {
@@ -641,29 +550,30 @@ public class CldsService extends SecureServiceBase {
         LoggingUtils.setTimeContext(startTime, new Date());
         LoggingUtils.setResponseContext("0", "Post dcae event success", this.getClass().getName());
         auditLogger.info("Post dcae event completed");
-
         return msgInfo;
     }
 
     /**
      * REST service that retrieves sdc services
+     * 
+     * @throws GeneralSecurityException
+     *             In case of issue when decryting the SDC password
      *
-     * @throws Exception
      */
     @ApiOperation(value = "Retrieves sdc services", notes = "", response = String.class)
     @GET
     @Path("/sdc/services")
     @Produces(MediaType.APPLICATION_JSON)
-    public String getSdcServices() throws Exception {
+    public String getSdcServices() throws GeneralSecurityException {
         Date startTime = new Date();
         LoggingUtils.setRequestContext("CldsService: GET sdc services", getPrincipalName());
         String retStr;
+        String responseStr = sdcCatalogServices.getSdcServicesInformation(null);
         try {
-            String responseStr = sdcCatalogServices.getSdcServicesInformation(null);
             retStr = createUiServiceFormatJson(responseStr);
-        } catch (Exception e) {
-            logger.info("{} {}", e.getClass().getName(), e.getMessage());
-            throw e;
+        } catch (IOException e) {
+            logger.error("IOException during SDC communication", e);
+            throw new SdcCommunicationException("IOException during SDC communication", e);
         }
         logger.info("value of sdcServices : {}", retStr);
         // audit log
@@ -675,22 +585,26 @@ public class CldsService extends SecureServiceBase {
 
     /**
      * REST service that retrieves total properties required by UI
+     * 
+     * @throws IOException
+     *             In case of issues
      *
-     * @throws Exception
      */
     @ApiOperation(value = "Retrieves total properties required by UI", notes = "", response = String.class)
     @GET
     @Path("/properties")
     @Produces(MediaType.APPLICATION_JSON)
-    public String getSdcProperties() throws Exception {
+    public String getSdcProperties() throws IOException {
         return createPropertiesObjectByUUID(getGlobalCldsString(), "{}");
     }
 
     /**
      * REST service that retrieves total properties by using invariantUUID based
      * on refresh and non refresh
-     *
-     * @throws Exception
+     * 
+     * @throws GeneralSecurityException
+     *             In case of issue when decryting the SDC password
+     * 
      */
     @ApiOperation(value = "Retrieves total properties by using invariantUUID based on refresh and non refresh", notes = "", response = String.class)
     @GET
@@ -698,12 +612,11 @@ public class CldsService extends SecureServiceBase {
     @Produces(MediaType.APPLICATION_JSON)
     public String getSdcPropertiesByServiceUUIDForRefresh(
             @PathParam("serviceInvariantUUID") String serviceInvariantUUID,
-            @DefaultValue("false") @QueryParam("refresh") String refresh) throws Exception {
+            @DefaultValue("false") @QueryParam("refresh") String refresh) throws GeneralSecurityException {
         Date startTime = new Date();
         LoggingUtils.setRequestContext("CldsService: GET sdc properties by uuid", getPrincipalName());
         CldsServiceData cldsServiceData = new CldsServiceData();
         cldsServiceData.setServiceInvariantUUID(serviceInvariantUUID);
-
         boolean isCldsSdcDataExpired = true;
         // To getcldsService information from database cache using invariantUUID
         // only when refresh = false
@@ -726,17 +639,15 @@ public class CldsService extends SecureServiceBase {
                 cldsServiceData.setCldsServiceCache(cldsDao, cldsDBServiceCache);
             }
         }
-
         // filter out VFs the user is not authorized for
         cldsServiceData.filterVfs(this);
-
+        // format retrieved data into properties json
+        String sdcProperties = sdcCatalogServices.createPropertiesObjectByUUID(getGlobalCldsString(), cldsServiceData);
         // audit log
         LoggingUtils.setTimeContext(startTime, new Date());
         LoggingUtils.setResponseContext("0", "Get sdc properties by uuid success", this.getClass().getName());
         auditLogger.info("GET sdc properties by uuid completed");
-
-        // format retrieved data into properties json
-        return sdcCatalogServices.createPropertiesObjectByUUID(getGlobalCldsString(), cldsServiceData);
+        return sdcProperties;
     }
 
     /**
@@ -747,8 +658,8 @@ public class CldsService extends SecureServiceBase {
      * @throws NotAuthorizedException
      * @return
      */
-    public boolean isAuthorizedForVf(String vfInvariantUuid) throws NotAuthorizedException {
-        if (cldsPermissionTypeFilterVf != null && cldsPermissionTypeFilterVf.length() > 0) {
+    public boolean isAuthorizedForVf(String vfInvariantUuid) {
+        if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) {
             SecureServicePermission permission = SecureServicePermission.create(cldsPermissionTypeFilterVf,
                     cldsPermissionInstance, vfInvariantUuid);
             return isAuthorized(permission);
@@ -767,7 +678,7 @@ public class CldsService extends SecureServiceBase {
      * @param model
      * @return
      */
-    private boolean isAuthorizedForVf(CldsModel model) throws NotAuthorizedException {
+    private boolean isAuthorizedForVf(CldsModel model) {
         String vf = ModelProperties.getVf(model);
         if (vf == null || vf.length() == 0) {
             logger.info("VF not found in model");
@@ -787,9 +698,8 @@ public class CldsService extends SecureServiceBase {
         ObjectNode invariantIdServiceNode = objectMapper.createObjectNode();
         ObjectNode serviceNode = objectMapper.createObjectNode();
         logger.info("value of cldsserviceiNfolist: {}", rawList);
-        if (rawList != null && rawList.size() > 0) {
+        if (rawList != null && !rawList.isEmpty()) {
             List<CldsSdcServiceInfo> cldsSdcServiceInfoList = sdcCatalogServices.removeDuplicateServices(rawList);
-
             for (CldsSdcServiceInfo currCldsSdcServiceInfo : cldsSdcServiceInfoList) {
                 if (currCldsSdcServiceInfo != null) {
                     invariantIdServiceNode.put(currCldsSdcServiceInfo.getInvariantUUID(),
@@ -811,7 +721,6 @@ public class CldsService extends SecureServiceBase {
              */
             ObjectNode serviceObjectNode = createEmptyVfAlarmObject(mapper);
             ObjectNode vfObjectNode = mapper.createObjectNode();
-
             /**
              * to create json with vf and vfresourceId
              */
@@ -819,7 +728,6 @@ public class CldsService extends SecureServiceBase {
             serviceObjectNode.putPOJO(cldsSdcServiceDetail.getInvariantUUID(), vfObjectNode);
             ObjectNode byServiceBasicObjetNode = mapper.createObjectNode();
             byServiceBasicObjetNode.putPOJO("byService", serviceObjectNode);
-
             /**
              * to create json with VFC Node
              */
@@ -850,39 +758,50 @@ public class CldsService extends SecureServiceBase {
     }
 
     private void createVfObjectNode(ObjectNode vfObjectNode2, ObjectMapper mapper,
-            List<CldsSdcResource> rawCldsSdcResourceList) throws IOException {
+            List<CldsSdcResource> rawCldsSdcResourceList) {
         ObjectNode vfNode = mapper.createObjectNode();
         vfNode.put("", "");
-
-        // To remove repeated resource instance name from resourceInstanceList
+        // To remove repeated resource instance name from
+        // resourceInstanceList
         List<CldsSdcResource> cldsSdcResourceList = sdcCatalogServices
                 .removeDuplicateSdcResourceInstances(rawCldsSdcResourceList);
         /**
          * Creating vf resource node using cldsSdcResource Object
          */
-        if (cldsSdcResourceList != null && cldsSdcResourceList.size() > 0) {
+        if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
             for (CldsSdcResource cldsSdcResource : cldsSdcResourceList) {
-                if (cldsSdcResource != null && cldsSdcResource.getResoucreType() != null
-                        && cldsSdcResource.getResoucreType().equalsIgnoreCase("VF")) {
+                if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
                     vfNode.put(cldsSdcResource.getResourceUUID(), cldsSdcResource.getResourceName());
                 }
             }
         }
         vfObjectNode2.putPOJO("vf", vfNode);
-        String locationStringValue = refProp.getStringValue("ui.location.default");
-        String alarmStringValue = refProp.getStringValue("ui.alarm.default");
-
         /**
          * creating location json object using properties file value
          */
-        ObjectNode locationJsonNode = (ObjectNode) mapper.readValue(locationStringValue, JsonNode.class);
+        ObjectNode locationJsonNode;
+        try {
+            locationJsonNode = (ObjectNode) mapper.readValue(refProp.getStringValue("ui.location.default"),
+                    JsonNode.class);
+        } catch (IOException e) {
+            logger.error("Unable to load ui.location.default JSON in clds-references.properties properly", e);
+            throw new CldsConfigException(
+                    "Unable to load ui.location.default JSON in clds-references.properties properly", e);
+        }
         vfObjectNode2.putPOJO("location", locationJsonNode);
-
         /**
          * creating alarm json object using properties file value
          */
+        String alarmStringValue = refProp.getStringValue("ui.alarm.default");
         logger.info("value of alarm: {}", alarmStringValue);
-        ObjectNode alarmStringJsonNode = (ObjectNode) mapper.readValue(alarmStringValue, JsonNode.class);
+        ObjectNode alarmStringJsonNode;
+        try {
+            alarmStringJsonNode = (ObjectNode) mapper.readValue(alarmStringValue, JsonNode.class);
+        } catch (IOException e) {
+            logger.error("Unable to ui.alarm.default JSON in clds-references.properties properly", e);
+            throw new CldsConfigException("Unable to load ui.alarm.default JSON in clds-references.properties properly",
+                    e);
+        }
         vfObjectNode2.putPOJO("alarmCondition", alarmStringJsonNode);
     }
 
@@ -893,10 +812,9 @@ public class CldsService extends SecureServiceBase {
         vfCObjectNode.putPOJO("vfC", emptyObjectNode);
         ObjectNode subVfCObjectNode = mapper.createObjectNode();
         subVfCObjectNode.putPOJO("vfc", emptyObjectNode);
-        if (cldsSdcResourceList != null && cldsSdcResourceList.size() > 0) {
+        if (cldsSdcResourceList != null && !cldsSdcResourceList.isEmpty()) {
             for (CldsSdcResource cldsSdcResource : cldsSdcResourceList) {
-                if (cldsSdcResource != null && cldsSdcResource.getResoucreType() != null
-                        && cldsSdcResource.getResoucreType().equalsIgnoreCase("VF")) {
+                if (cldsSdcResource != null && "VF".equalsIgnoreCase(cldsSdcResource.getResoucreType())) {
                     vfCObjectNode.putPOJO(cldsSdcResource.getResourceUUID(), subVfCObjectNode);
                 }
             }
@@ -910,22 +828,28 @@ public class CldsService extends SecureServiceBase {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     public CldsModel deployModel(@PathParam("action") String action, @PathParam("modelName") String modelName,
-            @QueryParam("test") String test, CldsModel model) throws Exception {
+            @QueryParam("test") String test, CldsModel model) throws IOException {
         Date startTime = new Date();
         LoggingUtils.setRequestContext("CldsService: Deploy model", getPrincipalName());
-        String deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId";
+        String deploymentId = "";
+        // If model is already deployed then pass same deployment id
+        if (model.getDeploymentId() != null && !model.getDeploymentId().isEmpty()) {
+            deploymentId = model.getDeploymentId();
+        } else {
+            deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId";
+        }
         String createNewDeploymentStatusUrl = dcaeDispatcherServices.createNewDeployment(deploymentId,
                 model.getTypeId());
         String operationStatus = "processing";
         long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10);
-        while (operationStatus.equalsIgnoreCase("processing")) {
-            //Break the loop if waiting for more than 10 mins
-            if(waitingTime < System.nanoTime()){
+        while ("processing".equalsIgnoreCase(operationStatus)) {
+            // Break the loop if waiting for more than 10 mins
+            if (waitingTime < System.nanoTime()) {
                 break;
             }
             operationStatus = dcaeDispatcherServices.getOperationStatus(createNewDeploymentStatusUrl);
         }
-        if (operationStatus != null && operationStatus.equalsIgnoreCase("succeeded")) {
+        if ("succeeded".equalsIgnoreCase(operationStatus)) {
             String artifactName = model.getControlName();
             if (artifactName != null) {
                 artifactName = artifactName + ".yml";
@@ -938,12 +862,12 @@ public class CldsService extends SecureServiceBase {
                     CldsEvent.ACTION_STATE_RECEIVED, null);
             model.setDeploymentId(deploymentId);
             model.save(cldsDao, getUserId());
+        } else {
+            logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
+            throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
+                    "Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
         }
-        else{
-                       logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
-                       throw new Exception("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
-               }
-               logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId);
+        logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId);
         // audit log
         LoggingUtils.setTimeContext(startTime, new Date());
         LoggingUtils.setResponseContext("0", "Deploy model success", this.getClass().getName());
@@ -956,20 +880,20 @@ public class CldsService extends SecureServiceBase {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     public CldsModel unDeployModel(@PathParam("action") String action, @PathParam("modelName") String modelName,
-            @QueryParam("test") String test, CldsModel model) throws Exception {
+            @QueryParam("test") String test, CldsModel model) throws IOException {
         Date startTime = new Date();
         LoggingUtils.setRequestContext("CldsService: Undeploy model", getPrincipalName());
         String operationStatusUndeployUrl = dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(),
                 model.getTypeId());
         String operationStatus = "processing";
         long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10);
-        while (operationStatus.equalsIgnoreCase("processing")) {
-            if(waitingTime < System.nanoTime()){
+        while ("processing".equalsIgnoreCase(operationStatus)) {
+            if (waitingTime < System.nanoTime()) {
                 break;
             }
             operationStatus = dcaeDispatcherServices.getOperationStatus(operationStatusUndeployUrl);
         }
-        if (operationStatus != null && operationStatus.equalsIgnoreCase("succeeded")) {
+        if ("succeeded".equalsIgnoreCase(operationStatus)) {
             String artifactName = model.getControlName();
             if (artifactName != null) {
                 artifactName = artifactName + ".yml";
@@ -982,24 +906,52 @@ public class CldsService extends SecureServiceBase {
                     CldsEvent.ACTION_STATE_RECEIVED, null);
             model.setDeploymentId(null);
             model.save(cldsDao, getUserId());
+        } else {
+            logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
+            throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
+                    "Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
         }
-        else{
-                       logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
-                       throw new Exception("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus);
-               }
-               logger.info("Undeploy model (" + modelName + ") succeeded.");
-               // audit log
+        logger.info("Undeploy model (" + modelName + ") succeeded.");
+        // audit log
         LoggingUtils.setTimeContext(startTime, new Date());
         LoggingUtils.setResponseContext("0", "Undeploy model success", this.getClass().getName());
         auditLogger.info("Undeploy model completed");
         return model;
     }
 
-    private String getGlobalCldsString() throws Exception {
-        if (null == globalCldsProperties) {
-            globalCldsProperties = new Properties();
-            globalCldsProperties.load(appContext.getResource(globalClds).getInputStream());
+    private String getGlobalCldsString() {
+        try {
+            if (null == globalCldsProperties) {
+                globalCldsProperties = new Properties();
+                globalCldsProperties.load(appContext.getResource(globalClds).getInputStream());
+            }
+            return (String) globalCldsProperties.get("globalCldsProps");
+        } catch (IOException e) {
+            logger.error("Unable to load the globalClds due to an exception", e);
+            throw new CldsConfigException("Unable to load the globalClds due to an exception", e);
+        }
+    }
+
+    private void duplicateCheckforServiceVf(String modelName, String modelPropText) throws IOException {
+        JsonNode modelJson = new ObjectMapper().readTree(modelPropText);
+        JsonNode globalNode = modelJson.get("global");
+        String service = AbstractModelElement.getValueByName(globalNode, "service");
+        List<String> resourceVf = AbstractModelElement.getValuesByName(globalNode, "vf");
+        if (resourceVf != null && !resourceVf.isEmpty()) {
+            List<CldsModelProp> cldsModelPropList = cldsDao.getAllModelProperties();
+            for (CldsModelProp cldsModelProp : cldsModelPropList) {
+                JsonNode currentJson = new ObjectMapper().readTree(cldsModelProp.getPropText());
+                JsonNode currentNode = currentJson.get("global");
+                String currentService = AbstractModelElement.getValueByName(currentNode, "service");
+                List<String> currentVf = AbstractModelElement.getValuesByName(currentNode, "vf");
+                if (currentVf != null && !currentVf.isEmpty()) {
+                    if (!modelName.equalsIgnoreCase(cldsModelProp.getName()) && service.equalsIgnoreCase(currentService)
+                            && resourceVf.get(0).equalsIgnoreCase(currentVf.get(0))) {
+                        throw new BadRequestException("Same service/VF already exists in " + cldsModelProp.getName()
+                                + " model, please select different service/VF.");
+                    }
+                }
+            }
         }
-        return (String) globalCldsProperties.get("globalCldsProps");
     }
 }