You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by re...@apache.org on 2014/12/10 06:19:47 UTC

[4/8] stratos git commit: Refactoring the REST api

http://git-wip-us.apache.org/repos/asf/stratos/blob/b0d91f7d/components/org.apache.stratos.rest.endpoint/src/main/java/org/apache/stratos/rest/endpoint/api/StratosApiV41Utils.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.rest.endpoint/src/main/java/org/apache/stratos/rest/endpoint/api/StratosApiV41Utils.java b/components/org.apache.stratos.rest.endpoint/src/main/java/org/apache/stratos/rest/endpoint/api/StratosApiV41Utils.java
index c377b08..4fdfb3c 100644
--- a/components/org.apache.stratos.rest.endpoint/src/main/java/org/apache/stratos/rest/endpoint/api/StratosApiV41Utils.java
+++ b/components/org.apache.stratos.rest.endpoint/src/main/java/org/apache/stratos/rest/endpoint/api/StratosApiV41Utils.java
@@ -98,7 +98,7 @@ public class StratosApiV41Utils {
     private static ServiceDeploymentManager serviceDeploymentManager = new ServiceDeploymentManager();
     private static PersistenceManager persistenceManager = new RegistryBasedPersistenceManager();
 
-    public static void deployCartridge(CartridgeDefinitionBean cartridgeDefinitionBean, ConfigurationContext ctxt,
+    public static void createCartridgeDefinition(CartridgeDefinitionBean cartridgeDefinitionBean, ConfigurationContext ctxt,
                                        String userName, String tenantDomain) throws RestAPIException {
 
         log.info("Starting to deploy a Cartridge [type] " + cartridgeDefinitionBean.type);
@@ -114,141 +114,8 @@ public class StratosApiV41Utils {
         }
         log.info("Successfully deployed Cartridge [type] " + cartridgeDefinitionBean.type);
     }
-
-    public static void createApplication (ApplicationDefinition appDefinition) throws RestAPIException {
-
-        try {
-            if (persistenceManager.getApplication(appDefinition.getApplicationId()) != null) {
-                String errorMsg = "Application Definition with id " + appDefinition.getApplicationId() +
-                        " already exists";
-                log.error(errorMsg);
-                throw new RestAPIException(errorMsg);
-            }
-        } catch (PersistenceManagerException e) {
-            throw new RestAPIException(e);
-        }
-
-        try {
-            persistenceManager.createApplication(appDefinition);
-        } catch (PersistenceManagerException e) {
-            throw new RestAPIException(e);
-        }
-    }
-
-    public static void deleteApplication (String appId) throws RestAPIException {
-
-        try {
-            persistenceManager.removeApplication(appId);
-        } catch (PersistenceManagerException e) {
-            throw new RestAPIException(e);
-        }
-    }
-
-    public static void deployApplicationDefinition(ApplicationDefinition appDefinition, ConfigurationContext ctxt,
-                                                   String userName, String tenantDomain)
-            throws RestAPIException {
-
-        // check if an application with same id already exists
-        // check if application with same appId / tenant already exists
-        CartridgeSubscriptionManager subscriptionMgr = new CartridgeSubscriptionManager();
-        int tenantId = ApplicationManagementUtil.getTenantId(ctxt);
-        String appId = appDefinition.getApplicationId();
-
-        try {
-            if (subscriptionMgr.getApplicationSubscription(appId, tenantId) != null) {
-                String msg = "Duplicate application appId: " + appId + " for tenant " + tenantId;
-                throw new RestAPIException(msg);
-            }
-        } catch (ApplicationSubscriptionException e1) {
-            throw new RestAPIException(e1);
-        }
-
-        ApplicationContext applicationContext =
-                PojoConverter.convertApplicationBeanToApplicationContext(appDefinition);
-        applicationContext.setTenantId(ApplicationManagementUtil.getTenantId(ctxt));
-        applicationContext.setTenantDomain(tenantDomain);
-        applicationContext.setTeantAdminUsername(userName);
-
-        if (appDefinition.getProperty() != null) {
-            org.apache.stratos.autoscaler.stub.Properties properties = new org.apache.stratos.autoscaler.stub.Properties();
-            for (org.apache.stratos.manager.composite.application.beans.PropertyBean propertyBean : appDefinition.getProperty()) {
-                org.apache.stratos.autoscaler.stub.Property property = new org.apache.stratos.autoscaler.stub.Property();
-                property.setName(propertyBean.getName());
-                property.setValue(propertyBean.getValue());
-                properties.addProperties(property);
-            }
-            applicationContext.setProperties(properties);
-        }
-
-        try {
-            AutoscalerServiceClient.getServiceClient().deployApplication(applicationContext);
-        } catch (AutoScalerServiceApplicationDefinitionExceptionException e) {
-            throw new RestAPIException(e);
-        } catch (RemoteException e) {
-            throw new RestAPIException(e);
-        }
-    }
-
-    static ApplicationSubscription getApplicationSubscriptions(String appId, ConfigurationContext ctxt) throws RestAPIException {
-        CartridgeSubscriptionManager subscriptionMgr = new CartridgeSubscriptionManager();
-        try {
-            return subscriptionMgr.getApplicationSubscription(appId, ApplicationManagementUtil.getTenantId(ctxt));
-        } catch (ApplicationSubscriptionException e) {
-            throw new RestAPIException(e);
-        }
-    }
-
-    public static void removeApplication(String appId, ConfigurationContext ctxt,
-                                         String userName, String tenantDomain) throws RestAPIException {
-
-        try {
-            int tenantId = ApplicationManagementUtil.getTenantId(ctxt);
-            //CloudControllerServiceClient.getServiceClient().undeployApplicationDefinition(appId, tenantId, tenantDomain);
-            AutoscalerServiceClient.getServiceClient().undeployApplication(appId, tenantId, tenantDomain);
-
-        } catch (RemoteException e) {
-            throw new RestAPIException(e);
-        } catch (AutoScalerServiceApplicationDefinitionExceptionException e) {
-            throw new RestAPIException(e);
-        }
-
-    }
-
-    @SuppressWarnings("unused")
-    private static DeploymentPolicy[] intersection(
-            DeploymentPolicy[] cartridgeDepPolicies,
-            DeploymentPolicy[] lbCartridgeDepPolicies) {
-
-        List<DeploymentPolicy> commonPolicies =
-                new ArrayList<DeploymentPolicy>();
-        for (DeploymentPolicy policy1
-                : cartridgeDepPolicies) {
-            for (DeploymentPolicy policy2
-                    : lbCartridgeDepPolicies) {
-                if (policy1.equals(policy2)) {
-                    commonPolicies.add(policy1);
-                }
-            }
-
-        }
-        return commonPolicies.toArray(new DeploymentPolicy[0]);
-    }
-
-    public static void undeployApplication(String applicationId) throws RestAPIException {
-        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-        if (autoscalerServiceClient != null) {
-            try {
-                autoscalerServiceClient.unDeployDeploymentPolicy(applicationId);
-            } catch (RemoteException e) {
-                log.error("Error while unDeploying the Deployment Policy for  " + applicationId);
-                throw new RestAPIException(e);
-            }
-        }
-
-
-    }
-
-    public static void undeployCartridge(String cartridgeType) throws RestAPIException {
+    
+    public static void deleteCartridgeDefinition(String cartridgeType) throws RestAPIException {
 
         CloudControllerServiceClient cloudControllerServiceClient = getCloudControllerServiceClient();
         if (cloudControllerServiceClient != null) {
@@ -325,141 +192,324 @@ public class StratosApiV41Utils {
             throw new RestAPIException(msg, e);
         }
     }
-
-
-//    public static void deployPartition(Partition partitionBean) throws RestAPIException {
-//
-//        //log.info("***** " + cartridgeDefinitionBean.toString() + " *****");
-//
-//        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-//        if (autoscalerServiceClient != null) {
-//
-//            org.apache.stratos.cloud.controller.stub.deployment.partition.Partition partition =
-//                    PojoConverter.convertToCCPartitionPojo(partitionBean);
-//
-//            try {
-//                autoscalerServiceClient.deployPartition(partition);
-//            } catch (RemoteException e) {
-//                log.error(e.getMessage(), e);
-//                throw new RestAPIException(e.getMessage(), e);
-//            } catch (AutoScalerServiceInvalidPartitionExceptionException e) {
-//                String message = e.getFaultMessage().getInvalidPartitionException().getMessage();
-//                log.error(message, e);
-//                throw new RestAPIException(message, e);
-//            }
-//
-//        }
-//    }
-
-    public static void deployAutoscalingPolicy(AutoscalePolicy autoscalePolicyBean) throws RestAPIException {
-
-        log.info(String.format("Deploying autoscaling policy: [id] %s", autoscalePolicyBean.getId()));
-
-        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-        if (autoscalerServiceClient != null) {
-
-            org.apache.stratos.autoscaler.stub.autoscale.policy.AutoscalePolicy autoscalePolicy = PojoConverter.
-                    convertToCCAutoscalerPojo(autoscalePolicyBean);
-
-            try {
-                autoscalerServiceClient
-                        .deployAutoscalingPolicy(autoscalePolicy);
-            } catch (RemoteException e) {
-                log.error(e.getMessage(), e);
-                throw new RestAPIException(e.getMessage(), e);
-            } catch (AutoScalerServiceInvalidPolicyExceptionException e) {
-                String message = e.getFaultMessage()
-                        .getInvalidPolicyException().getMessage();
-                log.error(message, e);
-                throw new RestAPIException(message, e);
+    
+    public static List<Cartridge> getCartridgesByCategory(String category, String criteria, ConfigurationContext configurationContext) 
+			throws RestAPIException {
+		List<Cartridge> cartridges = null;
+		
+		if (category.equals("singleTenant")) {
+			cartridges = getAvailableCartridges(null, false, configurationContext);
+		} else if (category.equals("multiTenant")) {
+			cartridges = getAvailableCartridges(null, true, configurationContext);
+		} else if (category.equals("loadBalancer")) {
+			cartridges = getAvailableLbCartridges(false, configurationContext);
+		} else if (category.equals("provider")) {
+			cartridges = getAvailableCartridgesByProvider(criteria, configurationContext);
+		}
+		
+		return cartridges;
+	}
+	
+	public static Cartridge getCartridgeByCategory(String category, String cartridgeType, ConfigurationContext configurationContext) 
+	throws RestAPIException {
+		List<Cartridge> cartridges = getCartridgesByCategory(category, null, configurationContext);
+		
+		for (Cartridge cartridge : cartridges) {
+			if (cartridge.getCartridgeType().equals(cartridgeType)) {
+				return cartridge;
+			}
+		}
+		String msg = "Unavailable cartridge type: " + cartridgeType;
+		log.error(msg);
+		throw new RestAPIException(msg);
+	}
+    
+	/*private static Cartridge getAvailableCartridgeInfo(String cartridgeType, Boolean multiTenant, ConfigurationContext configurationContext) throws RestAPIException {
+        List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant, configurationContext);
+        for (Cartridge cartridge : cartridges) {
+            if (cartridge.getCartridgeType().equals(cartridgeType)) {
+                return cartridge;
             }
         }
-    }
-
-    public static void updateAutoscalingPolicy(AutoscalePolicy autoscalePolicyBean) throws RestAPIException {
-
-        log.info(String.format("Updating autoscaling policy: [id] %s", autoscalePolicyBean.getId()));
-
-        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-        if (autoscalerServiceClient != null) {
-
-            org.apache.stratos.autoscaler.stub.autoscale.policy.AutoscalePolicy autoscalePolicy = PojoConverter.
-                    convertToCCAutoscalerPojo(autoscalePolicyBean);
+        String msg = "Unavailable cartridge type: " + cartridgeType;
+        log.error(msg);
+        throw new RestAPIException(msg);
+    }*/
 
-            try {
-                autoscalerServiceClient.updateAutoscalingPolicy(autoscalePolicy);
-            } catch (RemoteException e) {
-                log.error(e.getMessage(), e);
-                throw new RestAPIException(e.getMessage(), e);
-            } catch (AutoScalerServiceInvalidPolicyExceptionException e) {
-                String message = e.getFaultMessage().getInvalidPolicyException().getMessage();
-                log.error(message, e);
-                throw new RestAPIException(message, e);
+    private static List<Cartridge> getAvailableLbCartridges(Boolean multiTenant,
+                                                    ConfigurationContext configurationContext) throws RestAPIException {
+        List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant,
+                configurationContext);
+        List<Cartridge> lbCartridges = new ArrayList<Cartridge>();
+        for (Cartridge cartridge : cartridges) {
+            if (cartridge.isLoadBalancer()) {
+                lbCartridges.add(cartridge);
             }
         }
+
+		/*if(lbCartridges == null || lbCartridges.isEmpty()) {
+            String msg = "Load balancer Cartridges are not available.";
+	        log.error(msg);
+	        throw new RestAPIException(msg) ;
+		}*/
+        return lbCartridges;
     }
 
-    public static String deployDeploymentPolicy(
-            org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy deploymentPolicyBean)
-            throws RestAPIException {
+	private static List<Cartridge> getAvailableCartridgesByProvider(String provider, ConfigurationContext configurationContext) throws RestAPIException {
+		List<Cartridge> cartridges = new ArrayList<Cartridge>();
 
-        String policyId = null;
+		if (log.isDebugEnabled()) {
+			log.debug("Getting available cartridges. Privider name : " + provider );
+		}
 
-        if (log.isDebugEnabled()) {
-            log.debug("Starting to deploy a deployment policy of application: "
-                    + deploymentPolicyBean.applicationPolicy.applicationId);
-        }
+		boolean allowMultipleSubscription = new Boolean(
+				System.getProperty(CartridgeConstants.FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED));
 
-        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-        if (autoscalerServiceClient != null) {
+		try {
 
-            org.apache.stratos.autoscaler.stub.deployment.policy.DeploymentPolicy deploymentPolicy =
-                    PojoConverter.convetToASDeploymentPolicyPojo(deploymentPolicyBean);
 
-            try {
-                policyId = autoscalerServiceClient.deployDeploymentPolicy(deploymentPolicy);
-            } catch (RemoteException e) {
-                log.error(e.getMessage(), e);
-                throw new RestAPIException(e.getMessage(), e);
-            } catch (AutoScalerServiceInvalidPolicyExceptionException e) {
-                String message = e.getFaultMessage().getInvalidPolicyException().getMessage();
-                log.error(message, e);
-                throw new RestAPIException(message, e);
-            }
+			String[] availableCartridges = CloudControllerServiceClient.getServiceClient().getRegisteredCartridges();
 
-            log.info(String.format("Deployed deployment policy: [id] %s", policyId));
-        }
-        
-        return policyId;
-    }
+			if (availableCartridges != null) {
+				for (String cartridgeType : availableCartridges) {
+					CartridgeInfo cartridgeInfo = null;
+					try {
+						cartridgeInfo = CloudControllerServiceClient.getServiceClient().getCartridgeInfo(cartridgeType);
+					} catch (Exception e) {
+						if (log.isWarnEnabled()) {
+							log.warn("Error when calling getCartridgeInfo for " + cartridgeType + ", Error: "
+							         + e.getMessage());
+						}
+					}
+					if (cartridgeInfo == null) {
+						// This cannot happen. But continue
+						if (log.isDebugEnabled()) {
+							log.debug("Cartridge Info not found: " + cartridgeType);
+						}
+						continue;
+					}
 
-    public static void updateDeploymentPolicy(
-            org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy deploymentPolicyBean)
-            throws RestAPIException {
 
-        //FIXME we do not have any use-case now?? - Nirmal
-//        log.info(String.format("Updating deployment policy: [id] %s", deploymentPolicyBean.id));
-//
-//        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-//        if (autoscalerServiceClient != null) {
-//
-//            org.apache.stratos.autoscaler.stub.deployment.policy.DeploymentPolicy deploymentPolicy =
-//                    PojoConverter.convetToASDeploymentPolicyPojo(deploymentPolicyBean);
-//
-//
-//            try {
-//                autoscalerServiceClient.updateDeploymentPolicy(deploymentPolicy);
-//            } catch (RemoteException e) {
-//                log.error(e.getMessage(), e);
-//                throw new RestAPIException(e.getMessage(), e);
-//            } catch (AutoScalerServiceInvalidPolicyExceptionException e) {
-//                String message = e.getFaultMessage().getInvalidPolicyException().getMessage();
-//                log.error(message, e);
-//                throw new RestAPIException(message, e);
-//            }
-//        }
+					if (!cartridgeInfo.getProvider().equals(provider)) {
+						continue;
+					}
+
+					Cartridge cartridge = new Cartridge();
+					cartridge.setCartridgeType(cartridgeType);
+					cartridge.setProvider(cartridgeInfo.getProvider());
+					cartridge.setDisplayName(cartridgeInfo.getDisplayName());
+					cartridge.setDescription(cartridgeInfo.getDescription());
+					cartridge.setVersion(cartridgeInfo.getVersion());
+					cartridge.setMultiTenant(cartridgeInfo.getMultiTenant());
+					cartridge.setHostName(cartridgeInfo.getHostName());
+					cartridge.setDefaultAutoscalingPolicy(cartridgeInfo.getDefaultAutoscalingPolicy());
+					cartridge.setDefaultDeploymentPolicy(cartridgeInfo.getDefaultDeploymentPolicy());
+					//cartridge.setStatus(CartridgeConstants.NOT_SUBSCRIBED);
+					cartridge.setCartridgeAlias("-");
+					cartridge.setPersistence(cartridgeInfo.getPersistence());
+					cartridge.setServiceGroup(cartridgeInfo.getServiceGroup());
+
+					if (cartridgeInfo.getProperties() != null) {
+						for (org.apache.stratos.cloud.controller.stub.Property property : cartridgeInfo
+								.getProperties()) {
+							if (property.getName().equals("load.balancer")) {
+								cartridge.setLoadBalancer(true);
+							}
+						}
+					}
+					//cartridge.setActiveInstances(0);
+					cartridges.add(cartridge);
+				}
+			} else {
+				if (log.isDebugEnabled()) {
+					log.debug("There are no available cartridges");
+				}
+			}
+		} catch (Exception e) {
+			String msg = "Error while getting available cartridges. Cause: " + e.getMessage();
+			log.error(msg, e);
+			throw new RestAPIException(msg, e);
+		}
+
+		Collections.sort(cartridges);
+
+		if (log.isDebugEnabled()) {
+			log.debug("Returning available cartridges " + cartridges.size());
+		}
+
+		return cartridges;
     }
 
+    public static List<Cartridge> getAvailableCartridges(String cartridgeSearchString, Boolean multiTenant, ConfigurationContext configurationContext) throws RestAPIException {
+        List<Cartridge> cartridges = new ArrayList<Cartridge>();
+
+        if (log.isDebugEnabled()) {
+            log.debug("Getting available cartridges. Search String: " + cartridgeSearchString + ", Multi-Tenant: " + multiTenant);
+        }
+
+        boolean allowMultipleSubscription = new Boolean(
+                System.getProperty(CartridgeConstants.FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED));
+
+        try {
+            Pattern searchPattern = getSearchStringPattern(cartridgeSearchString);
+
+            String[] availableCartridges = CloudControllerServiceClient.getServiceClient().getRegisteredCartridges();
+
+            if (availableCartridges != null) {
+                for (String cartridgeType : availableCartridges) {
+                    CartridgeInfo cartridgeInfo = null;
+                    try {
+                        cartridgeInfo = CloudControllerServiceClient.getServiceClient().getCartridgeInfo(cartridgeType);
+                    } catch (Exception e) {
+                        if (log.isWarnEnabled()) {
+                            log.warn("Error when calling getCartridgeInfo for " + cartridgeType + ", Error: "
+                                    + e.getMessage());
+                        }
+                    }
+                    if (cartridgeInfo == null) {
+                        // This cannot happen. But continue
+                        if (log.isDebugEnabled()) {
+                            log.debug("Cartridge Info not found: " + cartridgeType);
+                        }
+                        continue;
+                    }
+
+                    if (multiTenant != null && !multiTenant && cartridgeInfo.getMultiTenant()) {
+                        // Need only Single-Tenant cartridges
+                        continue;
+                    } else if (multiTenant != null && multiTenant && !cartridgeInfo.getMultiTenant()) {
+                        // Need only Multi-Tenant cartridges
+                        continue;
+                    }
+
+                    if (!StratosApiV41Utils.cartridgeMatches(cartridgeInfo, searchPattern)) {
+                        continue;
+                    }
+
+                    Cartridge cartridge = new Cartridge();
+                    cartridge.setCartridgeType(cartridgeType);
+                    cartridge.setProvider(cartridgeInfo.getProvider());
+                    cartridge.setDisplayName(cartridgeInfo.getDisplayName());
+                    cartridge.setDescription(cartridgeInfo.getDescription());
+                    cartridge.setVersion(cartridgeInfo.getVersion());
+                    cartridge.setMultiTenant(cartridgeInfo.getMultiTenant());
+                    cartridge.setHostName(cartridgeInfo.getHostName());
+                    cartridge.setDefaultAutoscalingPolicy(cartridgeInfo.getDefaultAutoscalingPolicy());
+                    cartridge.setDefaultDeploymentPolicy(cartridgeInfo.getDefaultDeploymentPolicy());
+                    //cartridge.setStatus(CartridgeConstants.NOT_SUBSCRIBED);
+                    cartridge.setCartridgeAlias("-");
+                    cartridge.setPersistence(cartridgeInfo.getPersistence());
+                    cartridge.setServiceGroup(cartridgeInfo.getServiceGroup());
+
+                    if (cartridgeInfo.getProperties() != null) {
+                        for (org.apache.stratos.cloud.controller.stub.Property property : cartridgeInfo.getProperties()) {
+                            if (property.getName().equals("load.balancer")) {
+                                cartridge.setLoadBalancer(true);
+                            }
+                        }
+                    }
+                    //cartridge.setActiveInstances(0);
+                    cartridges.add(cartridge);
+
+
+                    if (cartridgeInfo.getMultiTenant() && !allowMultipleSubscription) {
+                        // If the cartridge is multi-tenant. We should not let users
+                        // createSubscription twice.
+                        if (isAlreadySubscribed(cartridgeType,
+                                ApplicationManagementUtil.getTenantId(configurationContext))) {
+                            if (log.isDebugEnabled()) {
+                                log.debug("Already subscribed to " + cartridgeType
+                                        + ". This multi-tenant cartridge will not be available to createSubscription");
+                            }
+                            //cartridge.setStatus(CartridgeConstants.SUBSCRIBED);
+                        }
+                    }
+                }
+            } else {
+                if (log.isDebugEnabled()) {
+                    log.debug("There are no available cartridges");
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error while getting available cartridges. Cause: " + e.getMessage();
+            log.error(msg, e);
+            throw new RestAPIException(msg, e);
+        }
+
+        Collections.sort(cartridges);
+
+        if (log.isDebugEnabled()) {
+            log.debug("Returning available cartridges " + cartridges.size());
+        }
+
+        return cartridges;
+    }
+
+    private static boolean isAlreadySubscribed(String cartridgeType,
+                                               int tenantId) {
+
+        Collection<CartridgeSubscription> subscriptionList = CartridgeSubscriptionManager.isCartridgeSubscribed(tenantId, cartridgeType);
+        if (subscriptionList == null || subscriptionList.isEmpty()) {
+            return false;
+        } else {
+            return true;
+        }
+    }
+
+    private static Pattern getSearchStringPattern(String searchString) {
+        if (log.isDebugEnabled()) {
+            log.debug("Creating search pattern for " + searchString);
+        }
+        if (searchString != null) {
+            // Copied from org.wso2.carbon.webapp.mgt.WebappAdmin.doesWebappSatisfySearchString(WebApplication, String)
+            String regex = searchString.toLowerCase().replace("..?", ".?").replace("..*", ".*").replaceAll("\\?", ".?")
+                    .replaceAll("\\*", ".*?");
+            if (log.isDebugEnabled()) {
+                log.debug("Created regex: " + regex + " for search string " + searchString);
+            }
+
+            Pattern pattern = Pattern.compile(regex);
+            return pattern;
+        }
+        return null;
+    }
+
+    private static boolean cartridgeMatches(CartridgeInfo cartridgeInfo, Pattern pattern) {
+        if (pattern != null) {
+            boolean matches = false;
+            if (cartridgeInfo.getDisplayName() != null) {
+                matches = pattern.matcher(cartridgeInfo.getDisplayName().toLowerCase()).find();
+            }
+            if (!matches && cartridgeInfo.getDescription() != null) {
+                matches = pattern.matcher(cartridgeInfo.getDescription().toLowerCase()).find();
+            }
+            return matches;
+        }
+        return true;
+    }
+
+    private static boolean cartridgeMatches(CartridgeInfo cartridgeInfo, CartridgeSubscription cartridgeSubscription, Pattern pattern) {
+        if (pattern != null) {
+            boolean matches = false;
+            if (cartridgeInfo.getDisplayName() != null) {
+                matches = pattern.matcher(cartridgeInfo.getDisplayName().toLowerCase()).find();
+            }
+            if (!matches && cartridgeInfo.getDescription() != null) {
+                matches = pattern.matcher(cartridgeInfo.getDescription().toLowerCase()).find();
+            }
+            if (!matches && cartridgeSubscription.getType() != null) {
+                matches = pattern.matcher(cartridgeSubscription.getType().toLowerCase()).find();
+            }
+            if (!matches && cartridgeSubscription.getAlias() != null) {
+                matches = pattern.matcher(cartridgeSubscription.getAlias().toLowerCase()).find();
+            }
+            return matches;
+        }
+        return true;
+    }
+    	
+    // Util methods to get the service clients
+    
     private static CloudControllerServiceClient getCloudControllerServiceClient() throws RestAPIException {
 
         try {
@@ -473,94 +523,66 @@ public class StratosApiV41Utils {
         }
     }
 
-//    public static Partition[] getAvailablePartitions() throws RestAPIException {
-//
-//        org.apache.stratos.cloud.controller.stub.deployment.partition.Partition[] partitions = null;
-//        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-//        if (autoscalerServiceClient != null) {
-//            try {
-//                partitions = autoscalerServiceClient.getAvailablePartitions();
-//
-//            } catch (RemoteException e) {
-//                String errorMsg = "Error while getting available partitions. Cause : " + e.getMessage();
-//                log.error(errorMsg, e);
-//                throw new RestAPIException(errorMsg, e);
-//            }
-//        }
-//
-//        return PojoConverter.populatePartitionPojos(partitions);
-//    }
-//
-//    public static Partition[] getPartitionsOfDeploymentPolicy(String deploymentPolicyId)
-//            throws RestAPIException {
-//
-//        org.apache.stratos.cloud.controller.stub.deployment.partition.Partition[] partitions = null;
-//        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-//        if (autoscalerServiceClient != null) {
-//            try {
-//                partitions =
-//                        autoscalerServiceClient.getPartitionsOfDeploymentPolicy(deploymentPolicyId);
-//
-//            } catch (RemoteException e) {
-//                String errorMsg = "Error while getting available partitions for deployment policy id " +
-//                        deploymentPolicyId + ". Cause: " + e.getMessage();
-//                log.error(errorMsg, e);
-//                throw new RestAPIException(errorMsg, e);
-//            }
-//        }
-//
-//        return PojoConverter.populatePartitionPojos(partitions);
-//    }
-//
-//    public static Partition[]
-//    getPartitionsOfGroup(String deploymentPolicyId, String groupId) throws RestAPIException {
-//
-//        org.apache.stratos.cloud.controller.stub.deployment.partition.Partition[] partitions = null;
-//        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-//        if (autoscalerServiceClient != null) {
-//            try {
-//                partitions =
-//                        autoscalerServiceClient.getPartitionsOfGroup(deploymentPolicyId, groupId);
-//
-//            } catch (RemoteException e) {
-//                String errorMsg = "Error while getting available partitions for deployment policy id " + deploymentPolicyId +
-//                        ", group id " + groupId + ". Cause: " + e.getMessage();
-//                log.error(errorMsg, e);
-//                throw new RestAPIException(errorMsg, e);
-//            }
-//        }
-//
-//        return PojoConverter.populatePartitionPojos(partitions);
-//    }
-//
-//    public static Partition getPartition(String partitionId) throws RestAPIException {
-//
-//        org.apache.stratos.cloud.controller.stub.deployment.partition.Partition partition = null;
-//        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-//        if (autoscalerServiceClient != null) {
-//            try {
-//                partition = autoscalerServiceClient.getPartition(partitionId);
-//
-//            } catch (RemoteException e) {
-//                String errorMsg = "Error while getting partition for id " + partitionId + ". Cause: " + e.getMessage();
-//                log.error(errorMsg, e);
-//                throw new RestAPIException(errorMsg, e);
-//            }
-//        }
-//
-//        return PojoConverter.populatePartitionPojo(partition);
-//    }
+    private static AutoscalerServiceClient getAutoscalerServiceClient() throws RestAPIException {
+
+        try {
+            return AutoscalerServiceClient.getServiceClient();
+
+        } catch (AxisFault axisFault) {
+            String errorMsg = "Error while getting AutoscalerServiceClient instance to connect to the "
+                    + "Autoscaler. Cause: " + axisFault.getMessage();
+            log.error(errorMsg, axisFault);
+            throw new RestAPIException(errorMsg, axisFault);
+        }
+    }
+
+    // Util methods for Autoscaling policies
+
+    public static void createAutoscalingPolicy(AutoscalePolicy autoscalePolicyBean) throws RestAPIException {
+
+        log.info(String.format("Deploying autoscaling policy: [id] %s", autoscalePolicyBean.getId()));
+
+        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
+        if (autoscalerServiceClient != null) {
+
+            org.apache.stratos.autoscaler.stub.autoscale.policy.AutoscalePolicy autoscalePolicy = PojoConverter.
+                    convertToCCAutoscalerPojo(autoscalePolicyBean);
+
+            try {
+                autoscalerServiceClient
+                        .deployAutoscalingPolicy(autoscalePolicy);
+            } catch (RemoteException e) {
+                log.error(e.getMessage(), e);
+                throw new RestAPIException(e.getMessage(), e);
+            } catch (AutoScalerServiceInvalidPolicyExceptionException e) {
+                String message = e.getFaultMessage()
+                        .getInvalidPolicyException().getMessage();
+                log.error(message, e);
+                throw new RestAPIException(message, e);
+            }
+        }
+    }
+
+    public static void updateAutoscalingPolicy(AutoscalePolicy autoscalePolicyBean) throws RestAPIException {
 
-    private static AutoscalerServiceClient getAutoscalerServiceClient() throws RestAPIException {
+        log.info(String.format("Updating autoscaling policy: [id] %s", autoscalePolicyBean.getId()));
 
-        try {
-            return AutoscalerServiceClient.getServiceClient();
+        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
+        if (autoscalerServiceClient != null) {
 
-        } catch (AxisFault axisFault) {
-            String errorMsg = "Error while getting AutoscalerServiceClient instance to connect to the "
-                    + "Autoscaler. Cause: " + axisFault.getMessage();
-            log.error(errorMsg, axisFault);
-            throw new RestAPIException(errorMsg, axisFault);
+            org.apache.stratos.autoscaler.stub.autoscale.policy.AutoscalePolicy autoscalePolicy = PojoConverter.
+                    convertToCCAutoscalerPojo(autoscalePolicyBean);
+
+            try {
+                autoscalerServiceClient.updateAutoscalingPolicy(autoscalePolicy);
+            } catch (RemoteException e) {
+                log.error(e.getMessage(), e);
+                throw new RestAPIException(e.getMessage(), e);
+            } catch (AutoScalerServiceInvalidPolicyExceptionException e) {
+                String message = e.getFaultMessage().getInvalidPolicyException().getMessage();
+                log.error(message, e);
+                throw new RestAPIException(message, e);
+            }
         }
     }
 
@@ -599,331 +621,163 @@ public class StratosApiV41Utils {
 
         return PojoConverter.populateAutoscalePojo(autoscalePolicy);
     }
+    
+    // Util methods for Deployment policies
+    
+    public static String createDeploymentPolicy(
+    		org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy deploymentPolicyBean)
+    	            throws RestAPIException {
+    	String policyId = null;
 
-    public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy[]
-    getDeploymentPolicies() throws RestAPIException {
-
-        DeploymentPolicy[] deploymentPolicies = null;
-        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-        if (autoscalerServiceClient != null) {
-            try {
-                deploymentPolicies = autoscalerServiceClient.getDeploymentPolicies();
-            } catch (RemoteException e) {
-                String errorMsg = "Error getting available deployment policies. Cause : " + e.getMessage();
-                log.error(errorMsg, e);
-                throw new RestAPIException(errorMsg, e);
-            }
+        if (log.isDebugEnabled()) {
+            log.debug("Starting to create a deployment policy of application: "
+                    + deploymentPolicyBean.applicationPolicy.applicationId);
         }
-
-
-        return PojoConverter.populateDeploymentPolicyPojos(deploymentPolicies);
-    }
-
-    public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy[]
-    getDeploymentPolicies(String cartridgeType) throws RestAPIException {
-
-        DeploymentPolicy[] deploymentPolicies = null;
+        
         AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
         if (autoscalerServiceClient != null) {
-            try {
-                deploymentPolicies = autoscalerServiceClient.getDeploymentPolicies(cartridgeType);
-
-            } catch (RemoteException e) {
-                String errorMsg = "Error while getting available deployment policies for cartridge type " +
-                        cartridgeType + ". Cause: " + e.getMessage();
-                log.error(errorMsg, e);
-                throw new RestAPIException(errorMsg, e);
-            }
-        }
-
-        if (deploymentPolicies.length == 0) {
-            String errorMsg = "Cannot find any matching deployment policy for Cartridge [type] " + cartridgeType;
-            log.error(errorMsg);
-            throw new RestAPIException(errorMsg);
-        }
-
-        return PojoConverter.populateDeploymentPolicyPojos(deploymentPolicies);
-    }
 
-    public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy
-    getDeploymentPolicy(String deploymentPolicyId) throws RestAPIException {
+            org.apache.stratos.autoscaler.stub.deployment.policy.DeploymentPolicy deploymentPolicy =
+                    PojoConverter.convetToASDeploymentPolicyPojo(deploymentPolicyBean);
 
-        DeploymentPolicy deploymentPolicy = null;
-        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-        if (autoscalerServiceClient != null) {
             try {
-                deploymentPolicy = autoscalerServiceClient.getDeploymentPolicy(deploymentPolicyId);
-
+                policyId = autoscalerServiceClient.addDeploymentPolicy(deploymentPolicy);
             } catch (RemoteException e) {
-                String errorMsg = "Error while getting deployment policy with id " +
-                        deploymentPolicyId + ". Cause: " + e.getMessage();
-                log.error(errorMsg, e);
-                throw new RestAPIException(errorMsg, e);
+                log.error(e.getMessage(), e);
+                throw new RestAPIException(e.getMessage(), e);
+            } catch (AutoScalerServiceInvalidPolicyExceptionException e) {
+                String message = e.getFaultMessage().getInvalidPolicyException().getMessage();
+                log.error(message, e);
+                throw new RestAPIException(message, e);
             }
-        }
 
-        if (deploymentPolicy == null) {
-            String errorMsg = "Cannot find a matching deployment policy for [id] " + deploymentPolicyId;
-            log.error(errorMsg);
-            throw new RestAPIException(errorMsg);
+            log.info(String.format("Created deployment policy: [id] %s", policyId));
         }
-
-        return PojoConverter.populateDeploymentPolicyPojo(deploymentPolicy);
+        
+        return policyId;
     }
-
-    public static ApplicationLevelNetworkPartition[] getPartitionGroups(String deploymentPolicyId)
+    
+    public static void updateDeploymentPolicy(
+            org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy deploymentPolicyBean)
             throws RestAPIException {
 
-        org.apache.stratos.autoscaler.stub.deployment.partition.ApplicationLevelNetworkPartition[] partitionGroups = null;
-        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
-        if (autoscalerServiceClient != null) {
-            try {
-                partitionGroups = autoscalerServiceClient.getApplicationLevelNetworkPartition(deploymentPolicyId);
-
-            } catch (RemoteException e) {
-                String errorMsg = "Error getting available partition groups for deployment policy id "
-                        + deploymentPolicyId + ". Cause: " + e.getMessage();
-                log.error(errorMsg, e);
-                throw new RestAPIException(errorMsg, e);
-            }
-        }
-
-        return PojoConverter.populatePartitionGroupPojos(partitionGroups);
-    }
-
-    static Cartridge getAvailableCartridgeInfo(String cartridgeType, Boolean multiTenant, ConfigurationContext configurationContext) throws RestAPIException {
-        List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant, configurationContext);
-        for (Cartridge cartridge : cartridges) {
-            if (cartridge.getCartridgeType().equals(cartridgeType)) {
-                return cartridge;
-            }
-        }
-        String msg = "Unavailable cartridge type: " + cartridgeType;
-        log.error(msg);
-        throw new RestAPIException(msg);
-    }
-
-    static List<Cartridge> getAvailableLbCartridges(Boolean multiTenant,
-                                                    ConfigurationContext configurationContext) throws RestAPIException {
-        List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant,
-                configurationContext);
-        List<Cartridge> lbCartridges = new ArrayList<Cartridge>();
-        for (Cartridge cartridge : cartridges) {
-            if (cartridge.isLoadBalancer()) {
-                lbCartridges.add(cartridge);
-            }
-        }
-
-		/*if(lbCartridges == null || lbCartridges.isEmpty()) {
-            String msg = "Load balancer Cartridges are not available.";
-	        log.error(msg);
-	        throw new RestAPIException(msg) ;
-		}*/
-        return lbCartridges;
-    }
-
-	static List<Cartridge> getAvailableCartridgesByProvider(String provider, ConfigurationContext configurationContext) throws RestAPIException {
-		List<Cartridge> cartridges = new ArrayList<Cartridge>();
-
-		if (log.isDebugEnabled()) {
-			log.debug("Getting available cartridges. Privider name : " + provider );
-		}
-
-		boolean allowMultipleSubscription = new Boolean(
-				System.getProperty(CartridgeConstants.FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED));
-
-		try {
-
-
-			String[] availableCartridges = CloudControllerServiceClient.getServiceClient().getRegisteredCartridges();
-
-			if (availableCartridges != null) {
-				for (String cartridgeType : availableCartridges) {
-					CartridgeInfo cartridgeInfo = null;
-					try {
-						cartridgeInfo = CloudControllerServiceClient.getServiceClient().getCartridgeInfo(cartridgeType);
-					} catch (Exception e) {
-						if (log.isWarnEnabled()) {
-							log.warn("Error when calling getCartridgeInfo for " + cartridgeType + ", Error: "
-							         + e.getMessage());
-						}
-					}
-					if (cartridgeInfo == null) {
-						// This cannot happen. But continue
-						if (log.isDebugEnabled()) {
-							log.debug("Cartridge Info not found: " + cartridgeType);
-						}
-						continue;
-					}
-
-
-					if (!cartridgeInfo.getProvider().equals(provider)) {
-						continue;
-					}
-
-					Cartridge cartridge = new Cartridge();
-					cartridge.setCartridgeType(cartridgeType);
-					cartridge.setProvider(cartridgeInfo.getProvider());
-					cartridge.setDisplayName(cartridgeInfo.getDisplayName());
-					cartridge.setDescription(cartridgeInfo.getDescription());
-					cartridge.setVersion(cartridgeInfo.getVersion());
-					cartridge.setMultiTenant(cartridgeInfo.getMultiTenant());
-					cartridge.setHostName(cartridgeInfo.getHostName());
-					cartridge.setDefaultAutoscalingPolicy(cartridgeInfo.getDefaultAutoscalingPolicy());
-					cartridge.setDefaultDeploymentPolicy(cartridgeInfo.getDefaultDeploymentPolicy());
-					//cartridge.setStatus(CartridgeConstants.NOT_SUBSCRIBED);
-					cartridge.setCartridgeAlias("-");
-					cartridge.setPersistence(cartridgeInfo.getPersistence());
-					cartridge.setServiceGroup(cartridgeInfo.getServiceGroup());
-
-					if (cartridgeInfo.getProperties() != null) {
-						for (org.apache.stratos.cloud.controller.stub.Property property : cartridgeInfo
-								.getProperties()) {
-							if (property.getName().equals("load.balancer")) {
-								cartridge.setLoadBalancer(true);
-							}
-						}
-					}
-					//cartridge.setActiveInstances(0);
-					cartridges.add(cartridge);
-				}
-			} else {
-				if (log.isDebugEnabled()) {
-					log.debug("There are no available cartridges");
-				}
-			}
-		} catch (Exception e) {
-			String msg = "Error while getting available cartridges. Cause: " + e.getMessage();
-			log.error(msg, e);
-			throw new RestAPIException(msg, e);
-		}
-
-		Collections.sort(cartridges);
-
-		if (log.isDebugEnabled()) {
-			log.debug("Returning available cartridges " + cartridges.size());
-		}
-
-		return cartridges;
+        //FIXME we do not have any use-case now?? - Nirmal
+//        log.info(String.format("Updating deployment policy: [id] %s", deploymentPolicyBean.id));
+//
+//        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
+//        if (autoscalerServiceClient != null) {
+//
+//            org.apache.stratos.autoscaler.stub.deployment.policy.DeploymentPolicy deploymentPolicy =
+//                    PojoConverter.convetToASDeploymentPolicyPojo(deploymentPolicyBean);
+//
+//
+//            try {
+//                autoscalerServiceClient.updateDeploymentPolicy(deploymentPolicy);
+//            } catch (RemoteException e) {
+//                log.error(e.getMessage(), e);
+//                throw new RestAPIException(e.getMessage(), e);
+//            } catch (AutoScalerServiceInvalidPolicyExceptionException e) {
+//                String message = e.getFaultMessage().getInvalidPolicyException().getMessage();
+//                log.error(message, e);
+//                throw new RestAPIException(message, e);
+//            }
+//        }
     }
 
-    static List<Cartridge> getAvailableCartridges(String cartridgeSearchString, Boolean multiTenant, ConfigurationContext configurationContext) throws RestAPIException {
-        List<Cartridge> cartridges = new ArrayList<Cartridge>();
+    public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy[]
+    getDeploymentPolicies() throws RestAPIException {
 
-        if (log.isDebugEnabled()) {
-            log.debug("Getting available cartridges. Search String: " + cartridgeSearchString + ", Multi-Tenant: " + multiTenant);
+        DeploymentPolicy[] deploymentPolicies = null;
+        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
+        if (autoscalerServiceClient != null) {
+            try {
+                deploymentPolicies = autoscalerServiceClient.getDeploymentPolicies();
+            } catch (RemoteException e) {
+                String errorMsg = "Error getting available deployment policies. Cause : " + e.getMessage();
+                log.error(errorMsg, e);
+                throw new RestAPIException(errorMsg, e);
+            }
         }
 
-        boolean allowMultipleSubscription = new Boolean(
-                System.getProperty(CartridgeConstants.FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED));
 
-        try {
-            Pattern searchPattern = getSearchStringPattern(cartridgeSearchString);
+        return PojoConverter.populateDeploymentPolicyPojos(deploymentPolicies);
+    }
 
-            String[] availableCartridges = CloudControllerServiceClient.getServiceClient().getRegisteredCartridges();
+    /*public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy[]
+    getDeploymentPolicies(String cartridgeType) throws RestAPIException {
 
-            if (availableCartridges != null) {
-                for (String cartridgeType : availableCartridges) {
-                    CartridgeInfo cartridgeInfo = null;
-                    try {
-                        cartridgeInfo = CloudControllerServiceClient.getServiceClient().getCartridgeInfo(cartridgeType);
-                    } catch (Exception e) {
-                        if (log.isWarnEnabled()) {
-                            log.warn("Error when calling getCartridgeInfo for " + cartridgeType + ", Error: "
-                                    + e.getMessage());
-                        }
-                    }
-                    if (cartridgeInfo == null) {
-                        // This cannot happen. But continue
-                        if (log.isDebugEnabled()) {
-                            log.debug("Cartridge Info not found: " + cartridgeType);
-                        }
-                        continue;
-                    }
+        DeploymentPolicy[] deploymentPolicies = null;
+        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
+        if (autoscalerServiceClient != null) {
+            try {
+                deploymentPolicies = autoscalerServiceClient.getDeploymentPolicies(cartridgeType);
 
-                    if (multiTenant != null && !multiTenant && cartridgeInfo.getMultiTenant()) {
-                        // Need only Single-Tenant cartridges
-                        continue;
-                    } else if (multiTenant != null && multiTenant && !cartridgeInfo.getMultiTenant()) {
-                        // Need only Multi-Tenant cartridges
-                        continue;
-                    }
+            } catch (RemoteException e) {
+                String errorMsg = "Error while getting available deployment policies for cartridge type " +
+                        cartridgeType + ". Cause: " + e.getMessage();
+                log.error(errorMsg, e);
+                throw new RestAPIException(errorMsg, e);
+            }
+        }
 
-                    if (!StratosApiV41Utils.cartridgeMatches(cartridgeInfo, searchPattern)) {
-                        continue;
-                    }
+        if (deploymentPolicies.length == 0) {
+            String errorMsg = "Cannot find any matching deployment policy for Cartridge [type] " + cartridgeType;
+            log.error(errorMsg);
+            throw new RestAPIException(errorMsg);
+        }
 
-                    Cartridge cartridge = new Cartridge();
-                    cartridge.setCartridgeType(cartridgeType);
-                    cartridge.setProvider(cartridgeInfo.getProvider());
-                    cartridge.setDisplayName(cartridgeInfo.getDisplayName());
-                    cartridge.setDescription(cartridgeInfo.getDescription());
-                    cartridge.setVersion(cartridgeInfo.getVersion());
-                    cartridge.setMultiTenant(cartridgeInfo.getMultiTenant());
-                    cartridge.setHostName(cartridgeInfo.getHostName());
-                    cartridge.setDefaultAutoscalingPolicy(cartridgeInfo.getDefaultAutoscalingPolicy());
-                    cartridge.setDefaultDeploymentPolicy(cartridgeInfo.getDefaultDeploymentPolicy());
-                    //cartridge.setStatus(CartridgeConstants.NOT_SUBSCRIBED);
-                    cartridge.setCartridgeAlias("-");
-                    cartridge.setPersistence(cartridgeInfo.getPersistence());
-                    cartridge.setServiceGroup(cartridgeInfo.getServiceGroup());
+        return PojoConverter.populateDeploymentPolicyPojos(deploymentPolicies);
+    }*/
 
-                    if (cartridgeInfo.getProperties() != null) {
-                        for (org.apache.stratos.cloud.controller.stub.Property property : cartridgeInfo.getProperties()) {
-                            if (property.getName().equals("load.balancer")) {
-                                cartridge.setLoadBalancer(true);
-                            }
-                        }
-                    }
-                    //cartridge.setActiveInstances(0);
-                    cartridges.add(cartridge);
+    public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy
+    getDeploymentPolicy(String deploymentPolicyId) throws RestAPIException {
 
+        DeploymentPolicy deploymentPolicy = null;
+        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
+        if (autoscalerServiceClient != null) {
+            try {
+                deploymentPolicy = autoscalerServiceClient.getDeploymentPolicy(deploymentPolicyId);
 
-                    if (cartridgeInfo.getMultiTenant() && !allowMultipleSubscription) {
-                        // If the cartridge is multi-tenant. We should not let users
-                        // createSubscription twice.
-                        if (isAlreadySubscribed(cartridgeType,
-                                ApplicationManagementUtil.getTenantId(configurationContext))) {
-                            if (log.isDebugEnabled()) {
-                                log.debug("Already subscribed to " + cartridgeType
-                                        + ". This multi-tenant cartridge will not be available to createSubscription");
-                            }
-                            //cartridge.setStatus(CartridgeConstants.SUBSCRIBED);
-                        }
-                    }
-                }
-            } else {
-                if (log.isDebugEnabled()) {
-                    log.debug("There are no available cartridges");
-                }
+            } catch (RemoteException e) {
+                String errorMsg = "Error while getting deployment policy with id " +
+                        deploymentPolicyId + ". Cause: " + e.getMessage();
+                log.error(errorMsg, e);
+                throw new RestAPIException(errorMsg, e);
             }
-        } catch (Exception e) {
-            String msg = "Error while getting available cartridges. Cause: " + e.getMessage();
-            log.error(msg, e);
-            throw new RestAPIException(msg, e);
         }
 
-        Collections.sort(cartridges);
-
-        if (log.isDebugEnabled()) {
-            log.debug("Returning available cartridges " + cartridges.size());
+        if (deploymentPolicy == null) {
+            String errorMsg = "Cannot find a matching deployment policy for [id] " + deploymentPolicyId;
+            log.error(errorMsg);
+            throw new RestAPIException(errorMsg);
         }
 
-        return cartridges;
+        return PojoConverter.populateDeploymentPolicyPojo(deploymentPolicy);
     }
 
-    private static boolean isAlreadySubscribed(String cartridgeType,
-                                               int tenantId) {
+    public static ApplicationLevelNetworkPartition[] getPartitionGroups(String deploymentPolicyId)
+            throws RestAPIException {
 
-        Collection<CartridgeSubscription> subscriptionList = CartridgeSubscriptionManager.isCartridgeSubscribed(tenantId, cartridgeType);
-        if (subscriptionList == null || subscriptionList.isEmpty()) {
-            return false;
-        } else {
-            return true;
+        org.apache.stratos.autoscaler.stub.deployment.partition.ApplicationLevelNetworkPartition[] partitionGroups = null;
+        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
+        if (autoscalerServiceClient != null) {
+            try {
+                partitionGroups = autoscalerServiceClient.getApplicationLevelNetworkPartition(deploymentPolicyId);
+
+            } catch (RemoteException e) {
+                String errorMsg = "Error getting available partition groups for deployment policy id "
+                        + deploymentPolicyId + ". Cause: " + e.getMessage();
+                log.error(errorMsg, e);
+                throw new RestAPIException(errorMsg, e);
+            }
         }
-    }
 
-    public static List<ServiceDefinitionBean> getdeployedServiceInformation() throws RestAPIException {
+        return PojoConverter.populatePartitionGroupPojos(partitionGroups);
+    }
+    
+    // Util methods for services and subscriptions
+    
+    /*public static List<ServiceDefinitionBean> getdeployedServiceInformation() throws RestAPIException {
 
         Collection<Service> services = null;
 
@@ -941,9 +795,9 @@ public class StratosApiV41Utils {
         }
 
         return null;
-    }
+    }*/
 
-    public static ServiceDefinitionBean getDeployedServiceInformation(String type) throws RestAPIException {
+    /*public static ServiceDefinitionBean getDeployedServiceInformation(String type) throws RestAPIException {
 
         Service service = null;
 
@@ -961,9 +815,9 @@ public class StratosApiV41Utils {
         } else {
             return PojoConverter.convertToServiceDefinitionBean(service);
         }
-    }
+    }*/
 
-    public static List<Cartridge> getActiveDeployedServiceInformation(ConfigurationContext configurationContext) throws RestAPIException {
+    /*public static List<Cartridge> getActiveDeployedServiceInformation(ConfigurationContext configurationContext) throws RestAPIException {
 
         Collection<Service> services = null;
 
@@ -1001,17 +855,16 @@ public class StratosApiV41Utils {
             }
         }
         
-		/*if (availableMultitenantCartridges.isEmpty()) {
-            String msg = "Cannot find any active deployed service for tenant [id] "+tenantId;
-			log.error(msg);
-			throw new RestAPIException(msg);
-		}*/
+//		if (availableMultitenantCartridges.isEmpty()) {
+//            String msg = "Cannot find any active deployed service for tenant [id] "+tenantId;
+//			log.error(msg);
+//			throw new RestAPIException(msg);
+//		}
 
         return availableMultitenantCartridges;
-    }
-
+    }*/
 
-    static List<Cartridge> getSubscriptions(String cartridgeSearchString, String serviceGroup, ConfigurationContext configurationContext) throws RestAPIException {
+    public static List<Cartridge> getSubscriptions(String cartridgeSearchString, String serviceGroup, ConfigurationContext configurationContext) throws RestAPIException {
         List<Cartridge> cartridges = new ArrayList<Cartridge>();
 
         if (log.isDebugEnabled()) {
@@ -1088,8 +941,7 @@ public class StratosApiV41Utils {
         return cartridges;
     }
 
-
-    static Cartridge getSubscription(String cartridgeAlias, ConfigurationContext configurationContext) throws RestAPIException {
+    /*static Cartridge getSubscription(String cartridgeAlias, ConfigurationContext configurationContext) throws RestAPIException {
 
         Cartridge cartridge = getCartridgeFromSubscription(CartridgeSubscriptionManager.getCartridgeSubscription(ApplicationManagementUtil.
                 getTenantId(configurationContext), cartridgeAlias));
@@ -1121,9 +973,9 @@ public class StratosApiV41Utils {
         cartridge.setStatus(cartridgeStatus);
         return cartridge;
 
-    }
+    }*/
 
-    static int getActiveInstances(String cartridgeType, String cartridgeAlias, ConfigurationContext configurationContext) throws RestAPIException {
+    /*static int getActiveInstances(String cartridgeType, String cartridgeAlias, ConfigurationContext configurationContext) throws RestAPIException {
         int noOfActiveInstances = 0;
         Cluster cluster = TopologyClusterInformationModel.getInstance().getCluster(ApplicationManagementUtil.getTenantId(configurationContext),
                 cartridgeAlias);
@@ -1140,7 +992,7 @@ public class StratosApiV41Utils {
             }
         }
         return noOfActiveInstances;
-    }
+    }*/
 
     private static Cartridge getCartridgeFromSubscription(CartridgeSubscription subscription) throws RestAPIException {
 
@@ -1206,63 +1058,11 @@ public class StratosApiV41Utils {
 
     }
 
-    static Pattern getSearchStringPattern(String searchString) {
-        if (log.isDebugEnabled()) {
-            log.debug("Creating search pattern for " + searchString);
-        }
-        if (searchString != null) {
-            // Copied from org.wso2.carbon.webapp.mgt.WebappAdmin.doesWebappSatisfySearchString(WebApplication, String)
-            String regex = searchString.toLowerCase().replace("..?", ".?").replace("..*", ".*").replaceAll("\\?", ".?")
-                    .replaceAll("\\*", ".*?");
-            if (log.isDebugEnabled()) {
-                log.debug("Created regex: " + regex + " for search string " + searchString);
-            }
-
-            Pattern pattern = Pattern.compile(regex);
-            return pattern;
-        }
-        return null;
-    }
-
-    static boolean cartridgeMatches(CartridgeInfo cartridgeInfo, Pattern pattern) {
-        if (pattern != null) {
-            boolean matches = false;
-            if (cartridgeInfo.getDisplayName() != null) {
-                matches = pattern.matcher(cartridgeInfo.getDisplayName().toLowerCase()).find();
-            }
-            if (!matches && cartridgeInfo.getDescription() != null) {
-                matches = pattern.matcher(cartridgeInfo.getDescription().toLowerCase()).find();
-            }
-            return matches;
-        }
-        return true;
-    }
-
-    static boolean cartridgeMatches(CartridgeInfo cartridgeInfo, CartridgeSubscription cartridgeSubscription, Pattern pattern) {
-        if (pattern != null) {
-            boolean matches = false;
-            if (cartridgeInfo.getDisplayName() != null) {
-                matches = pattern.matcher(cartridgeInfo.getDisplayName().toLowerCase()).find();
-            }
-            if (!matches && cartridgeInfo.getDescription() != null) {
-                matches = pattern.matcher(cartridgeInfo.getDescription().toLowerCase()).find();
-            }
-            if (!matches && cartridgeSubscription.getType() != null) {
-                matches = pattern.matcher(cartridgeSubscription.getType().toLowerCase()).find();
-            }
-            if (!matches && cartridgeSubscription.getAlias() != null) {
-                matches = pattern.matcher(cartridgeSubscription.getAlias().toLowerCase()).find();
-            }
-            return matches;
-        }
-        return true;
-    }
-
     public static CartridgeSubscription getCartridgeSubscription(String alias, ConfigurationContext configurationContext) {
         return CartridgeSubscriptionManager.getCartridgeSubscription(ApplicationManagementUtil.getTenantId(configurationContext), alias);
     }
 
-    static SubscriptionInfo subscribe(CartridgeInfoBean cartridgeInfoBean, ConfigurationContext configurationContext, String tenantUsername, String tenantDomain)
+    /*static SubscriptionInfo subscribe(CartridgeInfoBean cartridgeInfoBean, ConfigurationContext configurationContext, String tenantUsername, String tenantDomain)
             throws RestAPIException {
 
         SubscriptionData subscriptionData = new SubscriptionData();
@@ -1288,32 +1088,173 @@ public class StratosApiV41Utils {
             subscriptionData.setProperties(PojoConverter.getProperties(cartridgeInfoBean.getProperty()));
         }
 
-        /*
-        if (cartridgeInfoBean.isPersistanceRequired()) {
-        if (cartridgeInfoBean.getPersistence() != null) {
-            // Add persistence related properties to PersistenceContext
-            PersistenceContext persistenceContext = new PersistenceContext();
-            persistenceContext.setPersistanceRequiredProperty(IS_VOLUME_REQUIRED, String.valueOf(cartridgeInfoBean.isPersistanceRequired()));
-            persistenceContext.setSizeProperty(VOLUME_SIZE, cartridgeInfoBean.getSize());
-            persistenceContext.setDeleteOnTerminationProperty(SHOULD_DELETE_VOLUME, String.valueOf(cartridgeInfoBean.isRemoveOnTermination()));
-            if(cartridgeInfoBean.getVolumeId() != null) {
-                persistenceContext.setVolumeIdProperty(VOLUME_ID, String.valueOf(cartridgeInfoBean.getVolumeId()));
-            }
-            subscriptionData.setPersistanceCtxt(persistenceContext);
-        }
-        */
+        
+//        if (cartridgeInfoBean.isPersistanceRequired()) {
+//        if (cartridgeInfoBean.getPersistence() != null) {
+//            // Add persistence related properties to PersistenceContext
+//            PersistenceContext persistenceContext = new PersistenceContext();
+//            persistenceContext.setPersistanceRequiredProperty(IS_VOLUME_REQUIRED, String.valueOf(cartridgeInfoBean.isPersistanceRequired()));
+//            persistenceContext.setSizeProperty(VOLUME_SIZE, cartridgeInfoBean.getSize());
+//            persistenceContext.setDeleteOnTerminationProperty(SHOULD_DELETE_VOLUME, String.valueOf(cartridgeInfoBean.isRemoveOnTermination()));
+//            if(cartridgeInfoBean.getVolumeId() != null) {
+//                persistenceContext.setVolumeIdProperty(VOLUME_ID, String.valueOf(cartridgeInfoBean.getVolumeId()));
+//            }
+//            subscriptionData.setPersistanceCtxt(persistenceContext);
+//        }
+        
         //subscribe
         SubscriptionInfo subscriptionInfo = null;
         try {
             subscriptionInfo = CartridgeSubscriptionManager.subscribeToCartridgeWithProperties(subscriptionData);
         } catch (Exception e) {
-            throw new RestAPIException(e.getMessage(), e);
+            throw new RestAPIException(e.getMessage(), e);
+        }
+
+        return subscriptionInfo;
+    }*/
+
+    /*static void unsubscribe(String alias, String tenantDomain) throws RestAPIException {
+
+        try {
+            cartridgeSubsciptionManager.unsubscribeFromCartridge(tenantDomain, alias);
+
+        } catch (ADCException e) {
+            String msg = "Failed to unsubscribe from [alias] " + alias + ". Cause: " + e.getMessage();
+            log.error(msg, e);
+            throw new RestAPIException(msg, e);
+
+        } catch (NotSubscribedException e) {
+            log.error(e.getMessage(), e);
+            throw new RestAPIException(e.getMessage(), e);
+        }
+    }*/
+    
+    /**
+     * Super tenant will deploy multitenant service.
+     * <p/>
+     * get domain , subdomain as well..
+     *
+     * @param clusterDomain
+     * @param clusterSubdomain
+     */
+    /*static void deployService(String cartridgeType, String alias, String autoscalingPolicy, String deploymentPolicy,
+                              String tenantDomain, String tenantUsername, int tenantId, String clusterDomain, String clusterSubdomain, String tenantRange, boolean isPublic) throws RestAPIException {
+        log.info("Deploying service..");
+        try {
+            serviceDeploymentManager.deployService(cartridgeType, autoscalingPolicy, deploymentPolicy, tenantId, tenantRange, tenantDomain, tenantUsername, isPublic);
+
+        } catch (Exception e) {
+            String msg = String.format("Failed to deploy the Service [Cartridge type] %s [alias] %s . Cause: %s", cartridgeType, alias, e.getMessage());
+            log.error(msg, e);
+            throw new RestAPIException(msg, e);
+        }
+    }*/
+
+    /*static void undeployService(String serviceType) throws RestAPIException, ServiceDoesNotExistException {
+
+        try {
+            serviceDeploymentManager.undeployService(serviceType);
+        } catch (ServiceDoesNotExistException ex) {
+            throw ex;
+        } catch (Exception e) {
+            String msg = "Failed to undeploy service cluster definition of type " + serviceType + " Cause: " + e.getMessage();
+            log.error(msg, e);
+            throw new RestAPIException(msg, e);
         }
+    }*/
+    
+    /*public static void addSubscriptionDomains(ConfigurationContext configurationContext,
+            String subscriptionAlias,
+            SubscriptionDomainRequest request)
+	throws RestAPIException {
+		try {
+			int tenantId = ApplicationManagementUtil.getTenantId(configurationContext);
+			
+			for (org.apache.stratos.rest.endpoint.bean.subscription.domain.SubscriptionDomainBean subscriptionDomain : request.domains) {
+			boolean isDomainExists = isSubscriptionDomainExists(configurationContext, subscriptionAlias, subscriptionDomain.domainName);
+				if (isDomainExists) {
+					String message = "Subscription domain " + subscriptionDomain.domainName + " exists";
+					throw new RestAPIException(Status.INTERNAL_SERVER_ERROR, message);
+				}
+			}
+	
+			for (org.apache.stratos.rest.endpoint.bean.subscription.domain.SubscriptionDomainBean subscriptionDomain : request.domains) {
+		
+				CartridgeSubscriptionManager.addSubscriptionDomain(tenantId, subscriptionAlias,
+				subscriptionDomain.domainName, subscriptionDomain.applicationContext);
+			}
+		} catch (Exception e) {
+			log.error(e.getMessage(), e);
+			throw new RestAPIException(e.getMessage(), e);
+			}
+	}*/
 
-        return subscriptionInfo;
-    }
+	/*public static boolean isSubscriptionDomainExists(ConfigurationContext configurationContext,
+	                   String subscriptionAlias, String domain) throws RestAPIException {
+		try {
+			int tenantId = ApplicationManagementUtil.getTenantId(configurationContext);
+			SubscriptionDomainBean subscriptionDomain = PojoConverter.populateSubscriptionDomainPojo(CartridgeSubscriptionManager.getSubscriptionDomain(tenantId,
+					subscriptionAlias, domain));
+		
+			if (subscriptionDomain.domainName != null) {
+				return true;
+			} else {
+				return false;
+			}
+		} catch (Exception e) {
+			log.error(e.getMessage(), e);
+			throw new RestAPIException(e.getMessage(), e);
+		}
+	}*/
+	
+	/*public static List<SubscriptionDomainBean> getSubscriptionDomains(ConfigurationContext configurationContext,
+	                                    String subscriptionAlias) throws RestAPIException {
+		try {
+			int tenantId = ApplicationManagementUtil.getTenantId(configurationContext);
+			return PojoConverter.populateSubscriptionDomainPojos(CartridgeSubscriptionManager.getSubscriptionDomains(tenantId, subscriptionAlias));
+		} catch (Exception e) {
+			log.error(e.getMessage(), e);
+			throw new RestAPIException(e.getMessage(), e);
+		}
+	}*/
+
+	/*public static SubscriptionDomainBean getSubscriptionDomain(ConfigurationContext configurationContext,
+	                             String subscriptionAlias, String domain) throws RestAPIException {
+		try {
+			int tenantId = ApplicationManagementUtil
+			.getTenantId(configurationContext);
+			SubscriptionDomainBean subscriptionDomain = PojoConverter.populateSubscriptionDomainPojo(CartridgeSubscriptionManager.getSubscriptionDomain(tenantId,
+			subscriptionAlias, domain));
+			
+			if (subscriptionDomain == null) {
+				String message = "Could not find a subscription for [domain] " + domain + " and [alias] " + subscriptionAlias;
+				log.error(message);
+				throw new RestAPIException(Status.NOT_FOUND, message);
+			}
+			
+			return subscriptionDomain;
+		
+		} catch (Exception e) {
+			log.error(e.getMessage(), e);
+			throw new RestAPIException(e.getMessage(), e);
+		}
+	}*/
+
+	/*public static void removeSubscriptionDomain(ConfigurationContext configurationContext,
+	              String subscriptionAlias, String domain) throws RestAPIException, DomainMappingExistsException {
+		try {
+			int tenantId = ApplicationManagementUtil.getTenantId(configurationContext);
+				CartridgeSubscriptionManager.removeSubscriptionDomain(tenantId, subscriptionAlias, domain);
+		} catch (Exception e) {
+				log.error(e.getMessage(), e);
+				throw new RestAPIException(e.getMessage(), e);
+		}
 
-    public static org.apache.stratos.rest.endpoint.bean.topology.Cluster getCluster(String subscriptionAlias, ConfigurationContext configurationContext) throws RestAPIException {
+	}*/
+    
+    // Util methods for clusters
+    
+    /*public static org.apache.stratos.rest.endpoint.bean.topology.Cluster getCluster(String subscriptionAlias, ConfigurationContext configurationContext) throws RestAPIException {
 
         Cluster cluster = TopologyClusterInformationModel.getInstance().getCluster(ApplicationManagementUtil.getTenantId(configurationContext),
                 subscriptionAlias);
@@ -1322,7 +1263,7 @@ public class StratosApiV41Utils {
         } else {
             return PojoConverter.populateClusterPojos(cluster, null);
         }
-    }
+    }*/
 
     public static org.apache.stratos.rest.endpoint.bean.topology.Cluster[] getClustersForTenant(ConfigurationContext configurationContext) {
 
@@ -1357,7 +1298,7 @@ public class StratosApiV41Utils {
 
     }
 
-    public static org.apache.stratos.rest.endpoint.bean.topology.Cluster[] getClustersForCartridgeType(String cartridgeType) {
+    /*public static org.apache.stratos.rest.endpoint.bean.topology.Cluster[] getClustersForCartridgeType(String cartridgeType) {
 
         Set<Cluster> clusterSet = TopologyClusterInformationModel
                 .getInstance()
@@ -1371,7 +1312,7 @@ public class StratosApiV41Utils {
         arrCluster = clusters.toArray(arrCluster);
         return arrCluster;
 
-    }
+    }*/
 
     // return the cluster id for the lb. This is a temp fix.
     /*private static String subscribeToLb(String cartridgeType, String loadBalancedCartridgeType, String lbAlias,
@@ -1419,224 +1360,232 @@ public class StratosApiV41Utils {
         return cartridgeSubscription.getClusterDomain();
     } */
 
-    static void unsubscribe(String alias, String tenantDomain) throws RestAPIException {
+    // Util methods for repo actions
 
+    public static void getGitRepositoryNotification(Payload payload) throws RestAPIException {
         try {
-            cartridgeSubsciptionManager.unsubscribeFromCartridge(tenantDomain, alias);
 
-        } catch (ADCException e) {
-            String msg = "Failed to unsubscribe from [alias] " + alias + ". Cause: " + e.getMessage();
+            RepositoryNotification repoNotification = new RepositoryNotification();
+            repoNotification.updateRepository(payload.getRepository().getUrl());
+
+        } catch (Exception e) {
+            String msg = "Failed to get git repository notifications. Cause : " + e.getMessage();
             log.error(msg, e);
             throw new RestAPIException(msg, e);
-
-        } catch (NotSubscribedException e) {
-            log.error(e.getMessage(), e);
-            throw new RestAPIException(e.getMessage(), e);
         }
     }
 
-    /**
-     * Super tenant will deploy multitenant service.
-     * <p/>
-     * get domain , subdomain as well..
-     *
-     * @param clusterDomain
-     * @param clusterSubdomain
-     */
-    static void deployService(String cartridgeType, String alias, String autoscalingPolicy, String deploymentPolicy,
-                              String tenantDomain, String tenantUsername, int tenantId, String clusterDomain, String clusterSubdomain, String tenantRange, boolean isPublic) throws RestAPIException {
-        log.info("Deploying service..");
+    public static void synchronizeRepository(CartridgeSubscription cartridgeSubscription) throws RestAPIException {
         try {
-            serviceDeploymentManager.deployService(cartridgeType, autoscalingPolicy, deploymentPolicy, tenantId, tenantRange, tenantDomain, tenantUsername, isPublic);
-
+            RepositoryNotification repoNotification = new RepositoryNotification();
+            repoNotification.updateRepository(cartridgeSubscription);
         } catch (Exception e) {
-            String msg = String.format("Failed to deploy the Service [Cartridge type] %s [alias] %s . Cause: %s", cartridgeType, alias, e.getMessage());
+            String msg = "Failed to get git repository notifications. Cause : " + e.getMessage();
             log.error(msg, e);
             throw new RestAPIException(msg, e);
         }
     }
 
-    static void undeployService(String serviceType) throws RestAPIException, ServiceDoesNotExistException {
+    // Util methods for service groups
+    
+    public static void createServiceGroupDefinition(ServiceGroupDefinition serviceGroupDefinition) throws RestAPIException {
 
         try {
-            serviceDeploymentManager.undeployService(serviceType);
-        } catch (ServiceDoesNotExistException ex) {
-            throw ex;
-        } catch (Exception e) {
-            String msg = "Failed to undeploy service cluster definition of type " + serviceType + " Cause: " + e.getMessage();
-            log.error(msg, e);
-            throw new RestAPIException(msg, e);
+            serviceGropingManager.deployServiceGroupDefinition(serviceGroupDefinition);
+
+        } catch (InvalidServiceGroupException e) {
+            throw new RestAPIException(e);
+        } catch (ServiceGroupDefinitioException e) {
+            throw new RestAPIException(e);
+        } catch (ADCException e) {
+            throw new RestAPIException(e);
+        } catch (CloudControllerServiceUnregisteredCartridgeExceptionException e) {
+            throw new RestAPIException(e);
         }
+
+        log.info("Successfully created the Service Group Definition with name " + serviceGroupDefinition.getName());
     }
 
-    static void getGitRepositoryNotification(Payload payload) throws RestAPIException {
-        try {
+    public static ServiceGroupDefinition getServiceGroupDefinition(String serviceGroupDefinitionName) throws RestAPIException {
 
-            RepositoryNotification repoNotification = new RepositoryNotification();
-            repoNotification.updateRepository(payload.getRepository().getUrl());
+        try {
+            return serviceGropingManager.getServiceGroupDefinition(serviceGroupDefinitionName);
 
-        } catch (Exception e) {
-            String msg = "Failed to get git repository notifications. Cause : " + e.getMessage();
-            log.error(msg, e);
-            throw new RestAPIException(msg, e);
+        } catch (ServiceGroupDefinitioException e) {
+            throw new RestAPIException(e);
+        } catch (ADCException e) {
+            throw new RestAPIException(e);
         }
     }
 
-    static void synchronizeRepository(CartridgeSubscription cartridgeSubscription) throws RestAPIException {
+    public static ServiceGroupDefinition[] getServiceGroupDefinitions() throws RestAPIException {
         try {
-            RepositoryNotification repoNotification = new RepositoryNotification();
-            repoNotification.updateRepository(cartridgeSubscription);
-        } catch (Exception e) {
-            String msg = "Failed to get git repository notifications. Cause : " + e.getMessage();
-            log.error(msg, e);
-            throw new RestAPIException(msg, e);
+            return serviceGropingManager.getServiceGroupDefinitions();
+        } catch (ADCException e) {
+            throw new RestAPIException(e);
+        } catch (ServiceGroupDefinitioException e) {
+            throw new RestAPIException(e);
         }
     }
 
-    public static void addSubscriptionDomains(ConfigurationContext configurationContext,
-                                              String subscriptionAlias,
-                                              SubscriptionDomainRequest request)
-            throws RestAPIException {
-        try {
-            int tenantId = ApplicationManagementUtil.getTenantId(configurationContext);
-
-            for (org.apache.stratos.rest.endpoint.bean.subscription.domain.SubscriptionDomainBean subscriptionDomain : request.domains) {
-                boolean isDomainExists = isSubscriptionDomainExists(configurationContext, subscriptionAlias, subscriptionDomain.domainName);
-                if (isDomainExists) {
-                    String message = "Subscription domain " + subscriptionDomain.domainName + " exists";
-                    throw new RestAPIException(Status.INTERNAL_SERVER_ERROR, message);
-                }
-            }
+    public static void deleteServiceGroupDefinition(String serviceGroupDefinitionName) throws RestAPIException {
 
-            for (org.apache.stratos.rest.endpoint.bean.subscription.domain.SubscriptionDomainBean subscriptionDomain : request.domains) {
+        try {
+            serviceGropingManager.undeployServiceGroupDefinition(serviceGroupDefinitionName);
 
-                CartridgeSubscriptionManager.addSubscriptionDomain(tenantId, subscriptionAlias,
-                        subscriptionDomain.domainName, subscriptionDomain.applicationContext);
-            }
-        } catch (Exception e) {
-            log.error(e.getMessage(), e);
-            throw new RestAPIException(e.getMessage(), e);
+        } catch (ServiceGroupDefinitioException e) {
+            throw new RestAPIException(e);
+        } catch (ADCException e) {
+            throw new RestAPIException(e);
         }
+
+        log.info("Successfully deleted the Service Group Definition with name " + serviceGroupDefinitionName);
     }
 
-    public static boolean isSubscriptionDomainExists(ConfigurationContext configurationContext,
-                                                     String subscriptionAlias, String domain) throws RestAPIException {
-        try {
-            int tenantId = ApplicationManagementUtil.getTenantId(configurationContext);
-            SubscriptionDomainBean subscriptionDomain = PojoConverter.populateSubscriptionDomainPojo(CartridgeSubscriptionManager.getSubscriptionDomain(tenantId,
-                    subscriptionAlias, domain));
+    // Util methods for Applications
 
-            if (subscriptionDomain.domainName != null) {
-                return true;
-            } else {
-                return false;
+    /*public static void createApplication (ApplicationDefinition appDefinition) throws RestAPIException {
+
+        try {
+            if (persistenceManager.getApplication(appDefinition.getApplicationId()) != null) {
+                String errorMsg = "Application Definition with id " + appDefinition.getApplicationId() +
+                        " already exists";
+                log.error(errorMsg);
+                throw new RestAPIException(errorMsg);
             }
-        } catch (Exception e) {
-            log.error(e.getMessage(), e);
-            throw new RestAPIException(e.getMessage(), e);
+        } catch (PersistenceManagerException e) {
+            throw new RestAPIException(e);
         }
 
-    }
-
-    public static List<SubscriptionDomainBean> getSubscriptionDomains(ConfigurationContext configurationContext,
-                                                                      String subscriptionAlias) throws RestAPIException {
         try {
-            int tenantId = ApplicationManagementUtil.getTenantId(configurationContext);
-            return PojoConverter.populateSubscriptionDomainPojos(CartridgeSubscriptionManager.getSubscriptionDomains(tenantId, subscriptionAlias));
-        } catch (Exception e) {
-            log.error(e.getMessage(), e);
-            throw new RestAPIException(e.getMessage(), e);
+            persistenceManager.createApplication(appDefinition);
+        } catch (PersistenceManagerException e) {
+            throw new RestAPIException(e);
         }
-    }
+    }*/
+
+    /*public static void deleteApplication (String appId) throws RestAPIException {
 
-    public static SubscriptionDomainBean getSubscriptionDomain(ConfigurationContext configurationContext,
-                                                               String subscriptionAlias, String domain) throws RestAPIException {
         try {
-            int tenantId = ApplicationManagementUtil
-                    .getTenantId(configurationContext);
-            SubscriptionDomainBean subscriptionDomain = PojoConverter.populateSubscriptionDomainPojo(CartridgeSubscriptionManager.getSubscriptionDomain(tenantId,
-                    subscriptionAlias, domain));
-
-            if (subscriptionDomain == null) {
-                String message = "Could not find a subscription for [domain] " + domain + " and [alias] " + subscriptionAlias;
-                log.error(message);
-                throw new RestAPIException(Status.NOT_FOUND, message);
-            }
+            persistenceManager.removeApplication(appId);
+        } catch (PersistenceManagerException e) {
+            throw new RestAPIException(e);
+        }
+    }*/
 
-            return subscriptionDomain;
+    public static void createApplicationDefinition(ApplicationDefinition appDefinition, ConfigurationContext ctxt,
+                                                   String userName, String tenantDomain)
+            throws RestAPIException {
 
-        } catch (Exception e) {
-            log.error(e.getMessage(), e);
-            throw new RestAPIException(e.getMessage(), e);
-        }
-    }
+        // check if an application with same id already exists
+        // check if application with same appId / tenant already exists
+        CartridgeSubscriptionManager subscriptionMgr = new CartridgeSubscriptionManager();
+        int tenantId = ApplicationManagementUtil.getTenantId(ctxt);
+        String appId = appDefinition.getApplicationId();
 
-    public static void removeSubscriptionDomain(ConfigurationContext configurationContext,
-                                                String subscriptionAlias, String domain) throws RestAPIException, DomainMappingExistsException {
         try {
-            int tenantId = ApplicationManagementUtil.getTenantId(configurationContext);
-            CartridgeSubscriptionManager.removeSubscriptionDomain(tenantId, subscriptionAlias, domain);
-        } catch (Exception e) {
-            log.error(e.getMessage(), e);
-            throw new RestAPIException(e.getMessage(), e);
+            if (subscriptionMgr.getApplicationSubscription(appId, tenantId) != null) {
+                String msg = "Duplicate application appId: " + appId + " for tenant " + tenantId;
+                throw new RestAPIException(msg);
+            }
+        } catch (ApplicationSubscriptionException e1) {
+            throw new RestAPIException(e1);
         }
 
-    }
+        ApplicationContext applicationContext =
+                PojoConverter.convertApplicationBeanToApplicationContext(appDefinition);
+        applicationContext.setTenantId(ApplicationManagementUtil.getTenantId(ctxt));
+        applicationContext.setTenantDomain(tenantDomain);
+        applicationContext.setTeantAdminUsername(userName);
 
-    public static void deployServiceGroupDefinition(ServiceGroupDefinition serviceGroupDefinition) throws RestAPIException {
+        if (appDefinition.getProperty() != null) {
+            org.apache.stratos.autoscaler.stub.Properties properties = new org.apache.stratos.autoscaler.stub.Properties();
+            for (org.apache.stratos.manager.composite.application.beans.PropertyBean propertyBean : appDefinition.getProperty()) {
+                org.apache.stratos.autoscaler.stub.Property property = new org.apache.stratos.autoscaler.stub.Property();
+                property.setName(propertyBean.getName());
+                property.setValue(propertyBean.getValue());
+                properties.addProperties(property);
+            }
+            applicationContext.setProperties(properties);
+        }
 
         try {
-            serviceGropingManager.deployServiceGroupDefinition(serviceGroupDefinition);
-
-        } catch (InvalidServiceGroupException e) {
-            throw new RestAPIException(e);
-        } catch (ServiceGroupDefinitioException e) {
-            throw new RestAPIException(e);
-        } catch (ADCException e) {
+            AutoscalerServiceClient.getServiceClient().deployApplication(applicationContext);
+        } catch (AutoScalerServiceApplicationDefinitionExceptionException e) {
             throw new RestAPIException(e);
-        } catch (CloudControllerServiceUnregisteredCartridgeExceptionException e) {
+        } catch (RemoteException e) {
             throw new RestAPIException(e);
         }
-
-        log.info("Successfully deployed the Service Group Definition with name " + serviceGroupDefinition.getName());
     }
+    
+    public static void deployApplication(
+            org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy deploymentPolicyBean)
+            throws RestAPIException {
 
-    static ServiceGroupDefinition getServiceGroupDefinition(String serviceGroupDefinitionName) throws RestAPIException {
+        if (log.isDebugEnabled()) {
+            log.debug("Starting to deploy a deployment policy of application: "
+                    + deploymentPolicyBean.applicationPolicy.applicationId);
+        }
 
-        try {
-            return serviceGropingManager.getServiceGroupDefinition(serviceGroupDefinitionName);
+        AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient();
+        if (autoscalerServiceClient != null) {
 
-        } catch (ServiceGroupDefinitioException e) {
-            throw new RestAPIException(e);
-        } catch (ADCException e) {
-            throw new RestAPIException(e);
+            org.apache.stratos.autoscaler.stub.deployment.policy.DeploymentP

<TRUNCATED>