You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by is...@apache.org on 2013/07/10 18:51:36 UTC

[01/45] fixing component version issues and adding currently refactored components to the parent pom

Updated Branches:
  refs/heads/master 9d7cc50d7 -> 99508a500


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/Resources.properties
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/Resources.properties b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/Resources.properties
deleted file mode 100644
index 85081f9..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/Resources.properties
+++ /dev/null
@@ -1,11 +0,0 @@
-service.name=Service Name
-active.user.count=Active User Count
-active.tenants.services= Active Tenants on Services
-view.list=View List
-active.tenant.count=Active Tenant Count
-active.tenants.on= Active Tenants on
-tenant.domain= Tenant Domain
-active.status=State
-enter.tenant.domain=Enter Tenant Domain
-tenant.status=Tenant State
-tenant.state.on.services.for.tenant= Tenant State on Services For Tenant Domain

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/css/tenant-usage.css
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/css/tenant-usage.css b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/css/tenant-usage.css
deleted file mode 100644
index 5c85728..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/css/tenant-usage.css
+++ /dev/null
@@ -1,28 +0,0 @@
-.disableLink {
-    color: #aaaaaa;
-}
-
-.pageLinks {
-    background: #FFFFFF none repeat scroll 0%;
-    border: 1px solid #DDDDDD;
-    padding: 2px 3px;
-    text-decoration: none;
-    margin: 0px;
-    margin-left: 2px;
-    margin-right: 2px;
-}
-
-.pageLinks-selected {
-    background: #e8e9ae none repeat scroll 0%;
-    border: 1px solid #DDDDDD;
-    padding: 2px 3px;
-    text-decoration: none;
-    margin: 0px;
-    margin-left: 2px;
-    margin-right: 2px;
-}
-
-a {
-    color: #386698;
-    cursor: pointer;
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/images/view-usage.png
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/images/view-usage.png b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/images/view-usage.png
deleted file mode 100644
index 3d036c0..0000000
Binary files a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/images/view-usage.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/userguide.html
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/userguide.html b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/userguide.html
deleted file mode 100644
index 2c6a979..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/userguide.html
+++ /dev/null
@@ -1,76 +0,0 @@
-<!--
- ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- ~
- ~ WSO2 Inc. licenses this file to you under the Apache License,
- ~ Version 2.0 (the "License"); you may not use this file except
- ~ in compliance with the License.
- ~ You may obtain a copy of the License at
- ~
- ~    http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing,
- ~ software distributed under the License is distributed on an
- ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- ~ KIND, either express or implied.  See the License for the
- ~ specific language governing permissions and limitations
- ~ under the License.
- -->
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<html>
-<head>
-  <title>View Usage - User Guide</title>
-  <link href="../../admin/css/documentation.css" rel="stylesheet" type="text/css" media="all" />
-</head>
-
-<body>
-<h1>View Usage</h1>
-
-<p>
-You can view usage of the stratos resource by your organization from this page
-</p>
-
-<p>
-<img src="images/view-usage.png" alt="View Usage"/>
-<div><strong>Figure1: View Usage</strong></div>
-</p>
-
-<p>
-
-<table>
-    <thead>
-        <td>
-            The Form Field
-        </td>
-        <td>
-            Description
-        </td>
-    </thead>
-    <tbody>
-        <tr>
-            <td>Year-Month</td>
-            <td>The year and the month the usage is metered.</td>
-        </tr>
-        <tr>
-            <td>Number of Users</td>
-            <td>Number of users of your stratos account.</td>
-        </tr>
-        <tr>
-            <td>Active data storage</td>
-            <td>The registry data storage amount.</td>
-        </tr>
-        <tr>
-            <td>Registry Total Bandwidth</td>
-            <td>Total bandwidth consumed by the registry accesses.</td>
-        </tr>
-        <tr>
-            <td>Service Total Bandwidth</td>
-            <td>The bandwidth consumed by the web services.</td>
-        </tr>
-    </tbody>
-</table>
-
-</p>
-
-</body>
-
-</html>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant-ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant-ajaxprocessor.jsp b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant-ajaxprocessor.jsp
deleted file mode 100644
index 0c9a988..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant-ajaxprocessor.jsp
+++ /dev/null
@@ -1,59 +0,0 @@
-<%--
- ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- ~
- ~ WSO2 Inc. licenses this file to you under the Apache License,
- ~ Version 2.0 (the "License"); you may not use this file except
- ~ in compliance with the License.
- ~ You may obtain a copy of the License at
- ~
- ~    http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing,
- ~ software distributed under the License is distributed on an
- ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- ~ KIND, either express or implied.  See the License for the
- ~ specific language governing permissions and limitations
- ~ under the License.
- --%>
-<%@page contentType="text/html" pageEncoding="UTF-8" %>
-<%@ page import="org.json.JSONObject" %>
-<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Invoice" %>
-<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Payment" %>
-<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
-<%@ page import="java.util.Date" %>
-<%@ page import="org.wso2.carbon.tenant.activity.ui.clients.TenantActivityServiceClient" %>
-<%@ page import="java.io.Console" %>
-<%@ page import="javax.rmi.CORBA.Util" %>
-<%@ page import="org.wso2.carbon.tenant.activity.ui.utils.TenantMonitorUtil" %>
-<%@ page import="org.wso2.carbon.tenant.activity.stub.beans.xsd.PaginatedTenantDataBean" %>
-
-<%
-    String serverUrl = request.getParameter("backEndUrl");
-    String serviceName = request.getParameter("serviceName");
-    String domainName = request.getParameter("domainName");
-
-    boolean state = false;
-    if (serverUrl == null || "null".equals(serverUrl.trim())) {
-        try {
-            TenantActivityServiceClient client = new TenantActivityServiceClient(config, session);
-            state = client.isTenantActiveInService(domainName);
-        } catch (Exception e) {
-        }
-
-    } else {
-        try {
-            TenantActivityServiceClient client = new TenantActivityServiceClient(serverUrl, config, session);
-            state = client.isTenantActiveInService(domainName);
-        } catch (Exception e) {
-        }
-    }
-
-    try {
-        JSONObject obj = new JSONObject();
-        obj.put("isActive", state);
-        obj.put("service", serviceName);
-        out.write(obj.toString());
-    } catch (Exception e) {
-        e.printStackTrace();
-    }
-%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant.jsp
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant.jsp b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant.jsp
deleted file mode 100644
index d938710..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant.jsp
+++ /dev/null
@@ -1,110 +0,0 @@
-<!--
-~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-~
-~ WSO2 Inc. licenses this file to you under the Apache License,
-~ Version 2.0 (the "License"); you may not use this file except
-~ in compliance with the License.
-~ You may obtain a copy of the License at
-~
-~ http://www.apache.org/licenses/LICENSE-2.0
-~
-~ Unless required by applicable law or agreed to in writing,
-~ software distributed under the License is distributed on an
-~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-~ KIND, either express or implied. See the License for the
-~ specific language governing permissions and limitations
-~ under the License.
--->
-<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
-<%@ taglib prefix="carbon" uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" %>
-<%@ page import="org.wso2.carbon.tenant.activity.ui.utils.TenantMonitorUtil" %>
-<%@ page import="org.apache.stratos.common.config.CloudServiceConfig" %>
-<%@ page import="java.util.Map" %>
-<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
-<script type="text/javascript" src="../registry_common/js/registry_validation.js"></script>
-<script type="text/javascript" src="../registry_common/js/registry_common.js"></script>
-<script type="text/javascript" src="../ajax/js/prototype.js"></script>
-<script type="text/javascript" src="js/tenant_config.js"></script>
-
-<carbon:jsi18n
-        resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.JSResources"
-        request="<%=request%>"/>
-
-<fmt:bundle basename="org.wso2.carbon.tenant.activity.ui.i18n.Resources">
-    <carbon:breadcrumb
-            label="govern.view_tenants.menu"
-            resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.Resources"
-            topPage="true"
-            request="<%=request%>"/>
-    <%
-        String domainNameStr = request.getParameter("domain");
-    %>
-    <div id="middle">
-        <h2><fmt:message key="tenant.state.on.services.for.tenant"/> "<%=domainNameStr%>"</h2>
-
-        <div id="workArea">
-            <table id="activeStateTable" cellpadding="0" cellspacing="0" border="0" style="width:100%"
-                   class="styledLeft">
-                <thead>
-                <tr>
-                    <th style="padding-left:5px;text-align:left;width:40%"><fmt:message key="service.name"/></th>
-                    <th style="padding-left:5px;text-align:left;"><fmt:message key="tenant.status"/></th>
-                </tr>
-                </thead>
-            </table>
-        </div>
-    </div>
-</fmt:bundle>
-<%
-    String domainName = request.getParameter("domain");
-    Map<String, CloudServiceConfig> cloudServicesConfigs = TenantMonitorUtil.getCloudServiceConfigMap();
-%>
-
-<script type="text/javascript">
-
-    function getStats() {
-        var serviceArray = new Array();
-    <%
-    for(String serviceName : cloudServicesConfigs.keySet()){
-    %>
-        var serviceObj = new Object();
-        serviceObj.backEndUrl = '<%=cloudServicesConfigs.get(serviceName).getLink()%>';
-        serviceObj.serviceName = '<%=serviceName%>';
-        serviceObj.domainName = '<%=domainName%>';
-        serviceArray.push(serviceObj);
-    <% }
-    %>
-
-        for (var i = 0; i < serviceArray.length; i++) {
-
-            jQuery.ajax({
-                type: 'GET',
-                url: 'find-tenant-ajaxprocessor.jsp',
-                data: 'backEndUrl=' + serviceArray[i].backEndUrl + '&serviceName=' + serviceArray[i].serviceName + '&domainName=' + serviceArray[i].domainName,
-                dataType: 'json',
-                async: true,
-                success: function(msg) {
-                    var resp = msg;
-                    var active = 'Active';
-                    var inActive = 'Inactive';
-                    if (resp.isActive === true) {
-                        document.getElementById('activeStateTable').innerHTML += '<tr><td>' + resp.service + '</td><td>' + active + '</td></tr>';
-                    }
-                    else {
-                        document.getElementById('activeStateTable').innerHTML += '<tr><td>' + resp.service + '</td><td>' + inActive + '</td></tr>';
-                    }
-                },
-                error:function () {
-                    CARBON.showErrorDialog('Could not connect to server');
-                    //document.getElementById('serviceStatTable').innerHTML += '<tr><td>' + eresp.servic + '</td><td>' + resp.count + '</td></tr>';
-                    document.getElementById('activeStateTable').innerHTML += 'Not Available';
-                }
-            });
-        }
-    }
-</script>
-
-<body onload="getStats();">
-<div>
-</div>
-</body>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/get-data-ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/get-data-ajaxprocessor.jsp b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/get-data-ajaxprocessor.jsp
deleted file mode 100644
index 15f558b..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/get-data-ajaxprocessor.jsp
+++ /dev/null
@@ -1,66 +0,0 @@
-<%--
- ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- ~
- ~ WSO2 Inc. licenses this file to you under the Apache License,
- ~ Version 2.0 (the "License"); you may not use this file except
- ~ in compliance with the License.
- ~ You may obtain a copy of the License at
- ~
- ~    http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing,
- ~ software distributed under the License is distributed on an
- ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- ~ KIND, either express or implied.  See the License for the
- ~ specific language governing permissions and limitations
- ~ under the License.
- --%>
-<%@page contentType="text/html" pageEncoding="UTF-8" %>
-<%@ page import="org.json.JSONObject" %>
-<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Invoice" %>
-<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Payment" %>
-<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
-<%@ page import="java.util.Date" %>
-<%@ page import="org.wso2.carbon.tenant.activity.ui.clients.TenantActivityServiceClient" %>
-<%@ page import="java.io.Console" %>
-<%@ page import="javax.rmi.CORBA.Util" %>
-<%@ page import="org.wso2.carbon.tenant.activity.ui.utils.TenantMonitorUtil" %>
-<%@ page import="org.wso2.carbon.tenant.activity.stub.beans.xsd.PaginatedTenantDataBean" %>
-
-<%
-    String serverUrl = request.getParameter("backEndUrl");
-    String serviceName = request.getParameter("serviceName");
-
-
-    int count = 0;
-    if (serverUrl == null || "null".equals(serverUrl.trim())) {
-        try {
-            TenantActivityServiceClient client = new TenantActivityServiceClient(config, session);
-           // TenantMonitorUtil.tenantDataList.put(serviceName, client.getAllActiveTenantList());
-           count=client.getActiveTenantCount();
-        } catch (Exception e) {
-        }
-
-    } else {
-        try {
-            TenantActivityServiceClient client = new TenantActivityServiceClient(serverUrl, config, session);
-           // count = client.getAllActiveTenantList().length;
-           count=client.getActiveTenantCount();
-            if (count > 0) {
-               // TenantMonitorUtil.tenantDataList.put(serviceName, client.getAllActiveTenantList());
-            } else {
-                TenantMonitorUtil.tenantDataList.put(serviceName, null);
-            }
-        } catch (Exception e) {
-        }
-    }
-
-    try {
-        JSONObject obj = new JSONObject();
-        obj.put("count", count);
-        obj.put("service", serviceName);
-        out.write(obj.toString());
-    } catch (Exception e) {
-        e.printStackTrace();
-    }
-%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/instance-usage-report.gif
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/instance-usage-report.gif b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/instance-usage-report.gif
deleted file mode 100644
index 4a1ae6a..0000000
Binary files a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/instance-usage-report.gif and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/search.gif
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/search.gif b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/search.gif
deleted file mode 100644
index cfe76b5..0000000
Binary files a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/search.gif and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/tenant-usage-report.gif
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/tenant-usage-report.gif b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/tenant-usage-report.gif
deleted file mode 100644
index a9b04e2..0000000
Binary files a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/tenant-usage-report.gif and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/user-usage-report.gif
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/user-usage-report.gif b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/user-usage-report.gif
deleted file mode 100644
index 9070c35..0000000
Binary files a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/user-usage-report.gif and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/show-active-tenants.jsp
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/show-active-tenants.jsp b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/show-active-tenants.jsp
deleted file mode 100644
index 7f9e0cc..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/show-active-tenants.jsp
+++ /dev/null
@@ -1,129 +0,0 @@
-<!--
-~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-~
-~ WSO2 Inc. licenses this file to you under the Apache License,
-~ Version 2.0 (the "License"); you may not use this file except
-~ in compliance with the License.
-~ You may obtain a copy of the License at
-~
-~ http://www.apache.org/licenses/LICENSE-2.0
-~
-~ Unless required by applicable law or agreed to in writing,
-~ software distributed under the License is distributed on an
-~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-~ KIND, either express or implied. See the License for the
-~ specific language governing permissions and limitations
-~ under the License.
--->
-<%@ page import="java.util.List" %>
-<%@ page import="org.wso2.carbon.tenant.activity.ui.clients.TenantActivityServiceClient" %>
-<%@ page import="org.wso2.carbon.tenant.activity.ui.utils.TenantMonitorUtil" %>
-<%@ page import="java.util.Map" %>
-<%@ page import="org.wso2.carbon.tenant.reg.agent.client.util.Util" %>
-<%@ page import="org.apache.stratos.common.config.CloudServiceConfig" %>
-<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
-<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
-<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
-<%@ page import="org.wso2.carbon.CarbonConstants" %>
-<%@ page import="org.wso2.carbon.registry.common.ui.UIException" %>
-<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
-<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
-<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
-<%@ page import="java.text.SimpleDateFormat" %>
-<%@ page import="java.util.Calendar" %>
-<%@ page import="java.util.Date" %>
-<%@ page import="org.wso2.carbon.tenant.activity.stub.TenantActivityServiceStub" %>
-<%@ page import="org.wso2.carbon.tenant.activity.stub.beans.xsd.TenantDataBean" %>
-<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
-<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
-<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
-<script type="text/javascript" src="../registry_common/js/registry_validation.js"></script>
-<script type="text/javascript" src="../registry_common/js/registry_common.js"></script>
-<script type="text/javascript" src="../ajax/js/prototype.js"></script>
-<script type="text/javascript" src="js/tenant_config.js"></script>
-
-<carbon:jsi18n
-        resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.JSResources"
-        request="<%=request%>"/>
-
-<fmt:bundle basename="org.wso2.carbon.tenant.activity.ui.i18n.Resources">
-    <carbon:breadcrumb
-            label="govern.view_tenants.menu"
-            resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.Resources"
-            topPage="true"
-            request="<%=request%>"/>
-    <%
-        String serviceNameStr = request.getParameter("serviceName");
-    %>
-
-    <div id="middle">
-        <h2><fmt:message key="active.tenants.on"/> <%=serviceNameStr%>
-        </h2>
-
-        <div id="workArea">
-            <table id="serviceStatTable1" cellpadding="0" cellspacing="0" border="0" style="width:100%"
-                   class="styledLeft">
-                <thead>
-                <tr>
-                    <th style="padding-left:5px;text-align:left;width:30%"><fmt:message key="tenant.domain"/></th>
-                    <th style="padding-left:5px;text-align:left;"><fmt:message
-                            key="active.status"/></th>
-                </tr>
-                </thead>
-                <tbody>
-                <%
-                    String pageNumberStr = request.getParameter("pageNumber");
-                    if (pageNumberStr == null) {
-                        pageNumberStr = "0";
-
-                    }
-                    int pageNumber = 1;
-                    try {
-                        pageNumber = Integer.parseInt(pageNumberStr);
-                    } catch (NumberFormatException ignored) {
-                        // page number format exception
-                    }
-                    int numberOfPages = 1;
-                    try {
-                        String backEndUrl = TenantMonitorUtil.getCloudServiceConfigMap().get(request.getParameter("serviceName")).getLink();
-                        TenantActivityServiceClient client;
-                        if (backEndUrl == null || "null".equals(backEndUrl.trim())) {
-                            client = new TenantActivityServiceClient(config, session);
-                        } else {
-                            client = new TenantActivityServiceClient(backEndUrl, config, session);
-                        }
-                        for (TenantDataBean bean : client.getPaginatedActiveTenantList(pageNumber).getTenantInfoBeans()) {
-                %>
-                <tr>
-                    <td><%=bean.getDomain()%>
-                    </td>
-                    <td>Active</td>
-                </tr>
-                <%
-                    }
-                } catch (Exception e) {
-                %>
-                <tr>
-                    <td>No Data Available for this Service</td>
-                </tr>
-                <% }
-                    String reDirectPage = "show-active-tenants.jsp?serviceName=" + serviceNameStr + "&";
-                %>
-                <carbon:paginator pageNumber="<%=pageNumber%>" numberOfPages="<%=numberOfPages%>"
-                                  page="<%=reDirectPage%>" pageNumberParameterName="pageNumber"/>
-                </tbody>
-            </table>
-            <input type='hidden' name='serviceName' id="serviceName"/>
-        </div>
-    </div>
-</fmt:bundle>
-
-<script type="text/javascript">
-
-    function getStats() {
-        console.log("In the getStat() function");
-
-    }
-    function showTenants(serviceNameKey) {
-    }
-</script>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/tenant-activity.jsp
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/tenant-activity.jsp b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/tenant-activity.jsp
deleted file mode 100644
index e7db5a7..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/tenant-activity.jsp
+++ /dev/null
@@ -1,174 +0,0 @@
-<!--
-~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-~
-~ WSO2 Inc. licenses this file to you under the Apache License,
-~ Version 2.0 (the "License"); you may not use this file except
-~ in compliance with the License.
-~ You may obtain a copy of the License at
-~
-~ http://www.apache.org/licenses/LICENSE-2.0
-~
-~ Unless required by applicable law or agreed to in writing,
-~ software distributed under the License is distributed on an
-~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-~ KIND, either express or implied. See the License for the
-~ specific language governing permissions and limitations
-~ under the License.
--->
-<%@ page import="java.util.List" %>
-<%@ page import="org.wso2.carbon.tenant.activity.ui.clients.TenantActivityServiceClient" %>
-<%@ page import="org.wso2.carbon.tenant.activity.ui.utils.TenantMonitorUtil" %>
-<%@ page import="java.util.Map" %>
-<%@ page import="org.apache.stratos.common.config.CloudServiceConfig" %>
-<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
-<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
-
-
-<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
-<%@ page import="org.wso2.carbon.CarbonConstants" %>
-<%@ page import="org.wso2.carbon.registry.common.ui.UIException" %>
-<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
-<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
-<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
-<%@ page import="java.text.SimpleDateFormat" %>
-<%@ page import="java.util.Calendar" %>
-<%@ page import="java.util.Date" %>
-<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
-<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
-<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
-<script type="text/javascript" src="../registry_common/js/registry_validation.js"></script>
-<script type="text/javascript" src="../registry_common/js/registry_common.js"></script>
-<script type="text/javascript" src="../ajax/js/prototype.js"></script>
-<script type="text/javascript" src="js/tenant_config.js"></script>
-
-<carbon:jsi18n
-        resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.JSResources"
-        request="<%=request%>"/>
-
-<fmt:bundle basename="org.wso2.carbon.tenant.activity.ui.i18n.Resources">
-    <carbon:breadcrumb
-            label="govern.view_tenants.menu"
-            resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.Resources"
-            topPage="true"
-            request="<%=request%>"/>
-
-
-    <div id="middle">
-        <div id="top">
-            <h2><fmt:message key="active.tenants.services"/></h2>
-
-            <form id="findTenantForm" action="find-tenant.jsp" method="post">
-                <table class="normal-nopadding" cellspacing="0">
-                    <tbody>
-                    <tr style="border:0; !important">
-                        <td style="border:0; !important">
-                            <nobr>
-                                &nbsp;&nbsp;&nbsp;
-                                Enter Tenant Domain
-                                <input type="text" name="domain" id="domain" value="">&nbsp;
-                            </nobr>
-                        </td>
-                        <td style="border:0; !important">
-                            <a class="icon-link" href="#" style="background-image: url(images/search.gif);"
-                               onclick="domainSelected();" alt="Search"></a>
-                        </td>
-                    </tr>
-                    </tbody>
-                </table>
-            </form>
-        </div>
-
-        <div id="workArea">
-            <table id="serviceStatTable1" cellpadding="0" cellspacing="0" border="0" style="width:100%"
-                   class="styledLeft">
-                <thead>
-                <tr>
-                    <th style="padding-left:5px;text-align:left;width:40%"><fmt:message key="service.name"/></th>
-                    <th style="padding-left:5px;text-align:left;width:150px"><fmt:message
-                            key="active.tenant.count"/></th>
-                    <th style="padding-left:5px;text-align:left;"><fmt:message key="view.list"/></th>
-                </tr>
-                </thead>
-            </table>
-        </div>
-    </div>
-</fmt:bundle>
-
-<%
-    Map<String, CloudServiceConfig> cloudServicesConfigs = TenantMonitorUtil.getCloudServiceConfigMap();
-%>
-
-
-<script type="text/javascript">
-
-    function getStats() {
-        console.log("In the getStat() function");
-        var serviceArray = new Array();
-
-    <%
-    for(String serviceName : cloudServicesConfigs.keySet()){
-
-    %>
-
-        var serviceObj = new Object();
-        serviceObj.backEndUrl = '<%=cloudServicesConfigs.get(serviceName).getLink()%>';
-        serviceObj.serviceName = '<%=serviceName%>';
-        serviceArray.push(serviceObj);
-
-    <% }
-    %>
-
-        for (var i = 0; i < serviceArray.length; i++) {
-
-            jQuery.ajax({
-                type: 'GET',
-                url: 'get-data-ajaxprocessor.jsp',
-                data: 'backEndUrl=' + serviceArray[i].backEndUrl + '&serviceName=' + serviceArray[i].serviceName,
-                dataType: 'json',
-                async: true,
-                success: function(msg) {
-                    var resp = msg;
-                    var view = 'View';
-                    if (resp.count > 0) {
-                        document.getElementById('serviceStatTable1').innerHTML += '<tr><td><a href="javascript:showTenants(\'' + resp.service + '\');">' + resp.service + '</a></td><td>' + resp.count + '</td><td><a href="javascript:showTenants(\'' + resp.service + '\');">' + view + '</a></td></tr>';
-                    }
-                    else {
-                        document.getElementById('serviceStatTable1').innerHTML += '<tr><td>' + resp.service + '</td><td>' + resp.count + '</td><td>-</td></tr>';
-                    }
-                },
-                error:function () {
-                    CARBON.showErrorDialog('Could not connect to server');
-                    //document.getElementById('serviceStatTable').innerHTML += '<tr><td>' + eresp.servic + '</td><td>' + resp.count + '</td></tr>';
-                    document.getElementById('serviceStatTable').innerHTML += 'Not Available';
-                }
-            });
-
-        }
-    }
-    function showTenants(serviceNameKey) {
-        document.getElementById("serviceName").value = serviceNameKey;
-        document.myform.submit();
-    }
-
-    function domainSelected() {
-        var findDomainForm = document.getElementById('findTenantForm');
-        var domain = document.getElementById("domain").getValue();
-        if(domain.length > 3){
-            findDomainForm.submit();
-        }
-        else{
-          CARBON.showErrorDialog('Enter valid domain name');
-        }
-
-    }
-
-</script>
-
-<body onload="getStats();">
-<div>
-    <table id="serviceStatTable"></table>
-    <form name="myform" method="post" action="show-active-tenants.jsp">
-        <input type='hidden' name='serviceName' id="serviceName"/>
-    </form>
-</div>
-</body>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/pom.xml
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/pom.xml b/components/tenant-activity/org.apache.stratos.tenant.activity/pom.xml
deleted file mode 100644
index 6b6bc73..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/pom.xml
+++ /dev/null
@@ -1,145 +0,0 @@
-<!--
- *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
-  -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>tenant.activity.parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.tenant.activity</artifactId>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - TenantActivity</name>
-
-    <build>
-
-        <plugins>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.codehaus.mojo</groupId>
-                <artifactId>build-helper-maven-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>add-source</id>
-                        <phase>generate-sources</phase>
-                        <goals>
-                            <goal>add-source</goal>
-                        </goals>
-                        <configuration>
-                            <sources>
-                                <source>target/generated-code/src</source>
-                            </sources>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-compiler-plugin</artifactId>
-                <configuration>
-                </configuration>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                <version>1.4.0</version>
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Private-Package>
-                            org.wso2.carbon.tenant.activity.internal.*,
-                            org.wso2.carbon.tenant.activity.services.*,
-                        </Private-Package>
-                        <Export-Package>
-                            org.wso2.carbon.tenant.activity.api.*,
-                            org.wso2.carbon.tenant.activity.util.*,
-                            org.wso2.carbon.tenant.activity.beans.*,
-                            org.wso2.carbon.tenant.activity.commands.*,
-                        </Export-Package>
-                        <Import-Package>
-                            !org.wso2.carbon.tenant.activity.stub.*,
-                            org.apache.stratos.common.*,
-                            org.wso2.carbon.cluster.mgt.core.*,
-                            !javax.xml.namespace,
-                            javax.xml.namespace; version=0.0.0,
-                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
-                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
-                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
-                            *;resolution:=optional
-                        </Import-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-
-        </plugins>
-    </build>
-
-    <dependencies>
-
-        <dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2</artifactId>
-            <version>${orbit.version.axis2}</version>
-        </dependency>
-        <!--dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2-kernel</artifactId>
-            <version>${orbit.version.axis2}</version>
-        </dependency-->
-
-        <dependency>
-            <groupId>log4j</groupId>
-            <artifactId>log4j</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.registry.core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>commons-logging</groupId>
-            <artifactId>commons-logging</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.user.core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.user.mgt</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.stratos</groupId>
-            <artifactId>org.apache.stratos.common</artifactId>
-	    <version>2.1.2</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.cluster.mgt.core</artifactId>
-            <version>4.1.0</version>
-        </dependency>
-    </dependencies>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/PaginatedTenantDataBean.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/PaginatedTenantDataBean.java b/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/PaginatedTenantDataBean.java
deleted file mode 100644
index ce43b61..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/PaginatedTenantDataBean.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.tenant.activity.beans;
-
-import org.wso2.carbon.utils.Pageable;
-
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * Bean for paginated tenant information
- */
-public class PaginatedTenantDataBean implements Pageable, Serializable {
-    private TenantDataBean[] tenantInfoBeans;
-    private int numberOfPages;
-
-    public TenantDataBean[] getTenantInfoBeans() {
-        return tenantInfoBeans;
-    }
-
-    public void setTenantInfoBeans(TenantDataBean[] tenantInfoBeans) {
-        this.tenantInfoBeans = tenantInfoBeans;
-    }
-
-    public int getNumberOfPages() {
-        return numberOfPages;
-    }
-
-    public void setNumberOfPages(int numberOfPages) {
-        this.numberOfPages = numberOfPages;
-    }
-
-    public <T> void set(List<T> items) {
-        this.tenantInfoBeans = items.toArray(new TenantDataBean[items.size()]);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/TenantDataBean.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/TenantDataBean.java b/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/TenantDataBean.java
deleted file mode 100644
index e301231..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/TenantDataBean.java
+++ /dev/null
@@ -1,97 +0,0 @@
-package org.apache.stratos.tenant.activity.beans;
-/*
- *  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-
-
-import java.io.Serializable;
-
-/**
- * Represents a Tenant
- */
-@SuppressWarnings("unused")
-public class TenantDataBean implements Serializable {
-
-    /**
-     * The tenant Id
-     */
-    private int id;
-
-    /**
-     * The domain name of the tenant
-     */
-    private String domain;
-
-    /**
-     * The admin user name of the tenant
-     */
-    private String adminName;
-
-    /**
-     * The email address of the tenant
-     */
-    private String email;
-
-    /**
-     * Indicates whether this tenant is active or not
-     */
-    private boolean active;
-
-
-    public String getEmail() {
-        return email;
-    }
-
-    public void setEmail(String email) {
-        this.email = email;
-    }
-
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-
-    public String getAdminName() {
-        return adminName;
-    }
-
-    public void setAdminName(String adminName) {
-        this.adminName = adminName;
-    }
-
-    public String getDomain() {
-        return domain;
-    }
-
-    public void setDomain(String domain) {
-        this.domain = domain;
-    }
-
-    public boolean isActive() {
-        return active;
-    }
-
-    public void setActive(boolean active) {
-        this.active = active;
-    }
-
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberRequest.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberRequest.java b/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberRequest.java
deleted file mode 100644
index 3cd4cd3..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberRequest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- *  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.tenant.activity.commands;
-
-import org.apache.axis2.clustering.ClusteringCommand;
-import org.apache.axis2.clustering.ClusteringMessage;
-import org.apache.axis2.clustering.ClusteringFault;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
-import org.apache.stratos.tenant.activity.beans.TenantDataBean;
-import org.wso2.carbon.user.api.Tenant;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * This Cluster message is used to get active tenants in each node then
- * send response as other cluster command which holds active tenants
- */
-public class GetActiveTenantsInMemberRequest extends ClusteringMessage {
-    private static final Log log = LogFactory.getLog(GetActiveTenantsInMemberRequest.class);
-    private List<TenantDataBean> tenants = new ArrayList<TenantDataBean>();
-
-    public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
-        try {
-            for (Tenant tenant : TenantAxisUtils.getActiveTenants(configurationContext)) {
-                TenantDataBean tb = new TenantDataBean();
-                tb.setDomain(tenant.getDomain());
-                tenants.add(tb);
-            }
-        } catch (Exception e) {
-            String msg = "Cannot get Active tenants";
-            log.error(msg, e);
-            throw new ClusteringFault(msg, e);
-        }
-    }
-
-    public ClusteringCommand getResponse() {
-        return new GetActiveTenantsInMemberResponse(tenants);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberResponse.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberResponse.java b/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberResponse.java
deleted file mode 100644
index b3c19d0..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberResponse.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.tenant.activity.commands;
-
-import org.apache.axis2.clustering.ClusteringCommand;
-import org.apache.axis2.clustering.ClusteringFault;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.stratos.tenant.activity.beans.TenantDataBean;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * This clustering command is used send active tenants list if we send clustering message
- * GetActiveTenantsInMemberRequest then as a response we can get GetActiveTenantsInMemberResponse
- * which holds active tenants list
- */
-public class GetActiveTenantsInMemberResponse extends ClusteringCommand {
-
-    private List<TenantDataBean> tenants = new ArrayList<TenantDataBean>();
-
-    public GetActiveTenantsInMemberResponse(List<TenantDataBean> tenantList) {
-        tenants = tenantList;
-    }
-
-    public void addTenant(TenantDataBean tenant) {
-        tenants.add(tenant);
-    }
-
-    public List<TenantDataBean> getTenants() {
-        return Collections.unmodifiableList(tenants);
-    }
-
-    @Override
-    public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/internal/TenantActivityServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/internal/TenantActivityServiceComponent.java b/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/internal/TenantActivityServiceComponent.java
deleted file mode 100644
index 47042b9..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/internal/TenantActivityServiceComponent.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.tenant.activity.internal;
-
-import org.apache.stratos.tenant.activity.util.Util;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.axis2.transport.local.LocalTransportReceiver;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-import java.lang.Throwable;
-
-/**
- * @scr.component name="org.wso2.stratos.tenant.activity" immediate="true"
- * @scr.reference name="registry.service"
- * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="1..1"
- * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
- * @scr.reference name="user.realmservice.default"
- * interface="org.wso2.carbon.user.core.service.RealmService" cardinality="1..1"
- * policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
- * @scr.reference name="config.context.service"
- * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
- * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
- */
-public class TenantActivityServiceComponent {
-    private static Log log = LogFactory.getLog(TenantActivityServiceComponent.class);
-
-
-    protected void activate(ComponentContext context) {
-        try {
-            Util.registerRetrieverServices(context.getBundleContext());
-            if(log.isDebugEnabled()){
-                log.debug("******* Tenant Activity bundle is activated ******* ");
-            }
-        } catch (Throwable e) {
-            log.error("******* Error in activating Tenant Activity bundle ******* ", e);
-        }
-    }
-
-    protected void deactivate(ComponentContext context) {
-        if (log.isDebugEnabled()) {
-            log.debug("******* Tenant Activity is deactivated ******* ");
-        }
-    }
-
-    protected void setRegistryService(RegistryService registryService) {
-        Util.setRegistryService(registryService);
-    }
-
-    protected void unsetRegistryService(RegistryService registryService) {
-        Util.setRegistryService(null);
-    }
-
-    protected void setRealmService(RealmService realmService) {
-        Util.setRealmService(realmService);
-    }
-
-    protected void unsetRealmService(RealmService realmService) {
-        Util.setRealmService(null);
-    }
-
-    protected void setConfigurationContextService(ConfigurationContextService ccService) {
-        ConfigurationContext serverCtx = ccService.getServerConfigContext();
-        AxisConfiguration serverConfig = serverCtx.getAxisConfiguration();
-        LocalTransportReceiver.CONFIG_CONTEXT = new ConfigurationContext(serverConfig);
-        LocalTransportReceiver.CONFIG_CONTEXT.setServicePath("services");
-        LocalTransportReceiver.CONFIG_CONTEXT.setContextRoot("local:/");
-
-        Util.setConfigurationContextService(ccService);
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService ccService) {
-        Util.setConfigurationContextService(null);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/services/TenantActivityService.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/services/TenantActivityService.java b/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/services/TenantActivityService.java
deleted file mode 100644
index 2d6e2a7..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/services/TenantActivityService.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-
-package org.apache.stratos.tenant.activity.services;
-
-import org.apache.stratos.tenant.activity.util.Util;
-import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
-import org.wso2.carbon.core.AbstractAdmin;
-import org.apache.stratos.tenant.activity.beans.PaginatedTenantDataBean;
-import org.apache.stratos.tenant.activity.beans.TenantDataBean;
-import org.apache.stratos.tenant.activity.util.TenantActivityUtil;
-import org.wso2.carbon.user.api.Tenant;
-import org.wso2.carbon.utils.DataPaginator;
-
-import java.util.*;
-
-/**
- * This service use to get active tenants related data.If its single node
- */
-public class TenantActivityService extends AbstractAdmin {
-    List<String> list = new ArrayList<String>();
-
-    public int getActiveTenantCount() throws Exception {
-        return getAllActiveTenantList().size();
-    }
-
-    /**
-     *
-     * @return Active tenants list on service cluster
-     * @throws Exception  when error in retrieving active tenants list
-     */
-    private List<TenantDataBean> getAllActiveTenantList() throws Exception {
-       // ClusterMgtUtil cm = new ClusterMgtUtil();
-        List<TenantDataBean> list = new ArrayList<TenantDataBean>();
-        //This will add current node active tenants list to tenant list
-        for (Tenant tenant : TenantAxisUtils.getActiveTenants(Util.getConfigurationContextService().getServerConfigContext())) {
-            TenantDataBean tb = new TenantDataBean();
-            tb.setDomain(tenant.getDomain());
-            list.add(tb);
-        }
-        //if there are multiple nodes in clusters get active tenants from there as well
-        for (TenantDataBean tenantDataBean : TenantActivityUtil.getActiveTenantsInCluster()) {
-            if (TenantActivityUtil.indexOfTenantInList(list, tenantDataBean) < 0) {
-                list.add(tenantDataBean);
-            }
-
-        }
-        return list;
-    }
-
-    public PaginatedTenantDataBean retrievePaginatedActiveTenants(int pageNumber) throws Exception {
-        List<TenantDataBean> tenantList = getAllActiveTenantList();
-        // Pagination
-        PaginatedTenantDataBean paginatedTenantInfoBean = new PaginatedTenantDataBean();
-        DataPaginator.doPaging(pageNumber, tenantList, paginatedTenantInfoBean);
-        return paginatedTenantInfoBean;
-    }
-
-    public boolean isActiveTenantOnService(String domainName) throws Exception {
-        boolean state = false;
-        for (TenantDataBean tenant : getAllActiveTenantList()) {
-            if (tenant.getDomain().equalsIgnoreCase(domainName)) {
-                return true;
-            }
-        }
-        return state;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/TenantActivityUtil.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/TenantActivityUtil.java b/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/TenantActivityUtil.java
deleted file mode 100644
index 195980b..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/TenantActivityUtil.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.tenant.activity.util;
-
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.ClusteringCommand;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.stratos.tenant.activity.commands.GetActiveTenantsInMemberRequest;
-import org.apache.stratos.tenant.activity.commands.GetActiveTenantsInMemberResponse;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.tenant.activity.beans.TenantDataBean;
-
-import java.util.ArrayList;
-import java.util.List;
-
-
-public class TenantActivityUtil {
-    private static final Log log = LogFactory.getLog(TenantActivityUtil.class);
-
-    public static List<TenantDataBean> getActiveTenantsInCluster() throws AxisFault {
-        List<TenantDataBean> tenants = new ArrayList<TenantDataBean>();
-        try {
-            ClusteringAgent agent = getClusteringAgent();
-            List<ClusteringCommand> list = agent.sendMessage(new GetActiveTenantsInMemberRequest(), true);
-            if (log.isDebugEnabled()) {
-                log.debug("sent cluster command to to get Active tenants on cluster");
-            }
-            for (ClusteringCommand command : list) {
-                if (command instanceof GetActiveTenantsInMemberResponse) {
-                    GetActiveTenantsInMemberResponse response = (GetActiveTenantsInMemberResponse) command;
-                    for (TenantDataBean tenant : response.getTenants()) {
-                        tenants.add(tenant);
-                    }
-                }
-            }
-
-        } catch (AxisFault f) {
-            String msg = "Error in getting active tenant by cluster commands";
-            log.error(msg, f);
-            throw new AxisFault(msg);
-        }
-        return tenants;
-    }
-
-
-    private static ClusteringAgent getClusteringAgent() throws AxisFault {
-
-        AxisConfiguration axisConfig =
-                Util.getConfigurationContextService().getServerConfigContext().getAxisConfiguration();
-        return axisConfig.getClusteringAgent();
-    }
-
-    public static int indexOfTenantInList(List<TenantDataBean> list, TenantDataBean tenant) {
-        for (int i = 0; i < list.size(); i++) {
-            if (tenant.getDomain().equalsIgnoreCase(list.get(i).getDomain())) {
-                return i;
-            }
-        }
-        return -1;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/Util.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/Util.java b/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/Util.java
deleted file mode 100644
index 18f1bf8..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/Util.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.tenant.activity.util;
-
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.BundleContext;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.user.core.UserRealm;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-/**
- * Util methods for usage.
- */
-public class Util {
-
-    private static final Log log = LogFactory.getLog(Util.class);
-
-    private static RegistryService registryService;
-    private static RealmService realmService;
-    private static ConfigurationContextService configurationContextService;
-
-    public static synchronized void setRegistryService(RegistryService service) {
-        registryService = service;
-    }
-
-    public static void setConfigurationContextService(
-            ConfigurationContextService configurationContextService) {
-        Util.configurationContextService = configurationContextService;
-    }
-
-    public static ConfigurationContextService getConfigurationContextService() {
-        return configurationContextService;
-    }
-
-    public static synchronized void setRealmService(RealmService service) {
-        realmService = service;
-    }
-
-    public static RealmService getRealmService() {
-        return realmService;
-    }
-
-    public static RegistryService getRegistryService() {
-        return registryService;
-    }
-
-    public static UserRealm getUserRealm(int tenantId) throws RegistryException {
-        return registryService.getUserRealm(tenantId);
-    }
-
-    public static UserRegistry getSuperTenantGovernanceSystemRegistry() throws RegistryException {
-        return registryService.getGovernanceSystemRegistry();
-    }
-
-    public static void registerRetrieverServices(BundleContext bundleContext) throws Exception {
-        ConfigurationContextService configCtxSvc = Util.getConfigurationContextService();
-
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/resources/META-INF/component.xml b/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/resources/META-INF/component.xml
deleted file mode 100644
index ebbd1cc..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/resources/META-INF/component.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  ~  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-  ~
-  ~  Licensed under the Apache License, Version 2.0 (the "License");
-  ~  you may not use this file except in compliance with the License.
-  ~  You may obtain a copy of the License at
-  ~
-  ~       http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~  Unless required by applicable law or agreed to in writing, software
-  ~  distributed under the License is distributed on an "AS IS" BASIS,
-  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~  See the License for the specific language governing permissions and
-  ~  limitations under the License.
-  -->
-
-<component xmlns="http://products.wso2.org/carbon">
-    <ManagementPermissions>
-        <ManagementPermission>
-            <DisplayName>Monitor</DisplayName>
-            <ResourceId>/permission/admin/monitor</ResourceId>
-        </ManagementPermission>
-        <ManagementPermission>
-            <DisplayName>Tenant-Activity</DisplayName>
-            <ResourceId>/permission/admin/monitor/tenantActivity</ResourceId>
-        </ManagementPermission>
-        <ManagementPermission>
-            <DisplayName>Protected</DisplayName>
-            <ResourceId>/permission/protected</ResourceId>
-        </ManagementPermission>
-        <ManagementPermission>
-            <DisplayName>Monitor</DisplayName>
-            <ResourceId>/permission/protected/monitor</ResourceId>
-        </ManagementPermission>
-    </ManagementPermissions>
-</component>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/resources/META-INF/services.xml b/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/resources/META-INF/services.xml
deleted file mode 100644
index 0288f27..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,42 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- !
- ! Copyright 2006 The Apache Software Foundation.
- !
- ! Licensed under the Apache License, Version 2.0 (the "License");
- ! you may not use this file except in compliance with the License.
- ! You may obtain a copy of the License at
- !
- !      http://www.apache.org/licenses/LICENSE-2.0
- !
- ! Unless required by applicable law or agreed to in writing, software
- ! distributed under the License is distributed on an "AS IS" BASIS,
- ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ! See the License for the specific language governing permissions and
- ! limitations under the License.
- !-->
-<serviceGroup>
-
-    <service name="TenantActivityService" scope="transportsession">
-        <transports>
-            <transport>https</transport>
-        </transports>
-        <parameter name="ServiceClass" locked="false">
-            org.apache.stratos.tenant.activity.services.TenantActivityService
-        </parameter>
-        <operation name="getActiveTenantCount">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/monitor/tenantActivity</parameter>
-        </operation>
-        <operation name="retrievePaginatedActiveTenants">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/monitor/tenantActivity</parameter>
-        </operation>
-        <operation name="isActiveTenantOnService">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/monitor/tenantActivity</parameter>
-        </operation>
-    </service>
-    <parameter name="adminService" locked="true">true</parameter>
-    <parameter name="hiddenService" locked="true">true</parameter>
-</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/pom.xml
----------------------------------------------------------------------
diff --git a/components/tenant-activity/pom.xml b/components/tenant-activity/pom.xml
deleted file mode 100644
index 8754ab9..0000000
--- a/components/tenant-activity/pom.xml
+++ /dev/null
@@ -1,42 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- ~
- ~ Licensed under the Apache License, Version 2.0 (the "License");
- ~ you may not use this file except in compliance with the License.
- ~ You may obtain a copy of the License at
- ~
- ~      http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>tenant.activity.parent</artifactId>
-    <packaging>pom</packaging>
-    <name>Apache Stratos - Tenant Activity Parent Module</name>
-    <description>WSO2 Stratos Tenant Activity Parent Module</description>
-    <url>http://apache.org</url>
-
-    <modules>
-        <module>org.apache.stratos.tenant.activity</module>
-        <module>org.apache.stratos.tenant.activity.ui</module>
-    </modules>
-
-</project>
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 37a99a1..a5f456a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -166,6 +166,7 @@
 	<apache.stratos.version>3.0.0-SNAPSHOT</apache.stratos.version>
 	<!-- carbon related versions -->
 	<wso2carbon.version>4.1.0</wso2carbon.version>
+	<carbon.platform.package.import.version.range>[4.1.0, 4.2.0)</carbon.platform.package.import.version.range>
      	<carbon.platform.package.export.version>4.1.0</carbon.platform.package.export.version>   
     </properties>
 </project>


[08/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-load-average.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-load-average.xml b/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-load-average.xml
new file mode 100644
index 0000000..f8ecf6f
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-load-average.xml
@@ -0,0 +1,138 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
+  ~
+  ~  WSO2 Inc. licenses this file to you under the Apache License,
+  ~  Version 2.0 (the "License"); you may not use this file except
+  ~  in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~    http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing,
+  ~  software distributed under the License is distributed on an
+  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~  KIND, either express or implied.  See the License for the
+  ~  specific language governing permissions and limitations
+  ~  under the License.
+  -->
+
+<!-- The default synapse configuration shipped with the WSO2 Load Balancer
+     This handles the load balancing and the autoscaling of the stratos services
+ -->
+
+<definitions xmlns="http://ws.apache.org/ns/synapse">
+
+    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
+         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
+    -->
+
+
+    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
+         auto-scale your applications.
+    -->
+
+    <task class="org.wso2.carbon.mediator.autoscale2.LoadAverageBasedEC2LoadAnalyzerTask"
+          name="LoadAnalyzer">
+
+
+        <!--
+            The private key for the ec2
+        -->
+        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
+
+        <!--
+            The certificate for the ec2
+        -->
+        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
+
+        <!--
+            The amazon instance type for the load balanced service instances.
+            Recommended and the default is m1.large.
+        -->
+        <property name="instanceType" value="m1.large"/>
+
+        <!--
+            The amazon instance type for the instances of the load balancer itself.
+            Default is m1.large. Can be changed to m1.small too.
+        -->
+        <property name="loadBalancerInstanceType" value="m1.large"/>
+
+        <!--
+            The group of the service being load balanced.
+        -->
+        <property name="applicationGroup" value="as-2011-02-23,cloud-mysql,default"/>
+
+        <!--
+            The group of the load balancer.
+        -->
+        <property name="loadBalancerGroup" value="stratos-appserver-lb,cloud-mysql,default"/>
+
+        <!--
+            The Amazon availability zone for the instances. 1-c is given as the default
+        -->
+        <property name="availabilityZone" value="us-east-1c"/>
+
+        <!--
+            Additional information for the amazon instances
+        -->
+        <property name="instanceAdditionalInfo" value="EC2 autoscale instance"/>
+
+        <!--
+            The key pair
+        -->
+        <property name="key" value="stratos-1.0.0-keypair"/>
+
+        <!--
+            The service payload file which should be loaded to the bucket
+        -->
+        <property name="applicationPayload" value="resources/cluster_node.zip"/>
+
+        <!--
+            The load balancer payload file which should be loaded to the bucket
+        -->
+        <property name="loadBalancerPayload" value="/mnt/payload.zip"/>
+
+        <!--
+            The elasticIP property can be overriden by the ELASTIC_IP environment var,
+             which is set in the payload
+        -->
+        <property name="elasticIP" value="${ELASTIC_IP}"/>
+
+        <!--
+            The minimum and maximum limits of the load balanced service instances
+        -->
+        <property name="minAppInstances" value="1"/>
+        <property name="maxAppInstances" value="5"/>
+
+        <!--
+            The minimum and maximum limits of the load balancer instances
+        -->
+        <property name="minLoadBalancerInstances" value="1"/>
+
+        <property name="roundsToAverage" value="10"/>
+
+        <!--
+            The instances spawned at once, per scaling up decision.
+	    Default and the recommended value is 1
+        -->
+        <property name="instancesPerScaleUp" value="1"/>
+
+        <!--
+            The low and high limits of the load average
+        -->
+        <property name="loadAverageLowerLimit" value="2"/>
+        <property name="loadAverageHigherLimit" value="5"/>
+
+        <!--
+            The Load Balanced Service Ports
+        -->
+        <property name="serviceHttpPort" value="9763"/>
+        <property name="serviceHttpsPort" value="9443"/>
+
+        <!--
+            The interval to trigger the task in seconds
+        -->
+        <trigger interval="5"/>
+    </task>
+</definitions>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-messages-in-flight.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-messages-in-flight.xml b/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-messages-in-flight.xml
new file mode 100644
index 0000000..3e66066
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-messages-in-flight.xml
@@ -0,0 +1,135 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
+  ~
+  ~  WSO2 Inc. licenses this file to you under the Apache License,
+  ~  Version 2.0 (the "License"); you may not use this file except
+  ~  in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~    http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing,
+  ~  software distributed under the License is distributed on an
+  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~  KIND, either express or implied.  See the License for the
+  ~  specific language governing permissions and limitations
+  ~  under the License.
+  -->
+
+<!-- The default synapse configuration shipped with the WSO2 Load Balancer
+     This handles the load balancing and the autoscaling of the stratos services
+ -->
+
+<definitions xmlns="http://ws.apache.org/ns/synapse">
+
+    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
+         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
+    -->
+
+
+    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
+         auto-scale your applications.
+    -->
+
+    <task class="org.wso2.carbon.mediator.autoscale2.MessagesInFlightBasedEC2LoadAnalyzerTask"
+          name="LoadAnalyzer">
+
+
+        <!--
+            The private key for the ec2
+        -->
+        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
+
+        <!--
+            The certificate for the ec2
+        -->
+        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
+
+        <!--
+            The amazon instance type for the load balanced service instances.
+            Recommended and the default is m1.large.
+        -->
+        <property name="instanceType" value="m1.large"/>
+
+        <!--
+            The amazon instance type for the instances of the load balancer itself.
+            Default is m1.large. Can be changed to m1.small too.
+        -->
+        <property name="loadBalancerInstanceType" value="m1.large"/>
+
+        <!--
+            The group of the service being load balanced.
+        -->
+        <property name="applicationGroup" value="as-2011-02-23,cloud-mysql,default"/>
+
+        <!--
+            The group of the load balancer.
+        -->
+        <property name="loadBalancerGroup" value="stratos-appserver-lb,cloud-mysql,default"/>
+
+        <!--
+            The Amazon availability zone for the instances. 1-c is given as the default
+        -->
+        <property name="availabilityZone" value="us-east-1c"/>
+
+        <!--
+            Additional information for the amazon instances
+        -->
+        <property name="instanceAdditionalInfo" value="EC2 autoscale instance"/>
+
+        <!--
+            The key pair
+        -->
+        <property name="key" value="stratos-1.0.0-keypair"/>
+
+        <!--
+            The service payload file which should be loaded to the bucket
+        -->
+        <property name="applicationPayload" value="resources/cluster_node.zip"/>
+
+        <!--
+            The load balancer payload file which should be loaded to the bucket
+        -->
+        <property name="loadBalancerPayload" value="/mnt/payload.zip"/>
+
+        <!--
+            The elasticIP property can be overriden by the ELASTIC_IP environment var,
+             which is set in the payload
+        -->
+        <property name="elasticIP" value="${ELASTIC_IP}"/>
+
+        <!--
+            The time in milliseconds which the message takes to expire
+        -->
+        <property name="messageExpiryTime" value="60000"/>
+
+        <!--
+            The minimum and maximum limits of the load balanced service instances
+        -->
+        <property name="minAppInstances" value="1"/>
+        <property name="maxAppInstances" value="5"/>
+
+        <!--
+            The number of load balancer instances
+        -->
+        <property name="loadBalancerInstances" value="1"/>
+
+        <!--
+            The given queue length per node, for the calculation in scaling up
+        -->
+        <property name="queueLengthPerNode" value="400"/>
+        <property name="roundsToAverage" value="10"/>
+
+        <!--
+            The instances spawned at once, per scaling up decision.
+	    Default and the recommended value is 1
+        -->
+        <property name="instancesPerScaleUp" value="1"/>
+
+        <!--
+            The interval to trigger the task in seconds
+        -->
+        <trigger interval="5"/>
+    </task>
+</definitions>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-service-messages-in-flight.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-service-messages-in-flight.xml b/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-service-messages-in-flight.xml
new file mode 100644
index 0000000..7332d38
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/resources/synapse-service-messages-in-flight.xml
@@ -0,0 +1,108 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
+  ~
+  ~  WSO2 Inc. licenses this file to you under the Apache License,
+  ~  Version 2.0 (the "License"); you may not use this file except
+  ~  in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~    http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing,
+  ~  software distributed under the License is distributed on an
+  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~  KIND, either express or implied.  See the License for the
+  ~  specific language governing permissions and limitations
+  ~  under the License.
+  -->
+
+<!-- The default synapse configuration shipped with the WSO2 Load Balancer
+     This handles the load balancing and the autoscaling of the stratos services
+ -->
+
+<definitions xmlns="http://ws.apache.org/ns/synapse">
+
+    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
+         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
+    -->
+
+
+    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
+         auto-scale your applications.
+    -->
+    <task class="org.wso2.carbon.mediator.autoscale.lbautoscale.ServiceRequestsInFlightAutoscaler"
+          name="LoadAnalyzer">
+
+        <!--
+            The private key for ec2
+        -->
+        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
+
+        <!--
+            The certificate for ec2
+        -->
+        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
+        <!--
+            The key pair
+        -->
+        <property name="sshKey" value="stratos-1.0.0-keypair"/>
+
+        <property name="loadBalancer">
+            <loadBalancer>
+                <property name="securityGroup" value="stratos-appserver-lb"/>
+                <property name="instanceType" value="m1.large"/>
+                <property name="instances" value="1"/>
+                <property name="elasticIP" value="${ELASTIC_IP}"/>
+                <property name="availabilityZone" value="us-east-1c"/>
+                <property name="payload" value="/mnt/payload.zip"/>
+            </loadBalancer>
+        </property>
+
+        <property name="services">
+            <services>
+                <defaults>
+                    <property name="payload" value="resources/cluster_node.zip"/>
+                    <property name="availabilityZone" value="us-east-1c"/>
+                    <property name="securityGroup" value="as-2011-02-23"/>
+                    <property name="instanceType" value="m1.large"/>
+                    <property name="minAppInstances" value="1"/>
+                    <property name="maxAppInstances" value="5"/>
+                    <property name="queueLengthPerNode" value="400"/>
+                    <property name="roundsToAverage" value="10"/>
+                    <property name="instancesPerScaleUp" value="1"/>
+                    <property name="messageExpiryTime" value="60000"/>
+                </defaults>
+                <service domain="wso2.as.domain">
+                    <property name="payload" value="resources/cluster_node.zip"/>
+                    <property name="availabilityZone" value="us-east-1c"/>
+                </service>
+                <service domain="wso2.ds.domain">
+                    <property name="payload" value="resources/cluster_node.zip"/>
+                    <property name="minAppInstances" value="1"/>
+                    <property name="maxAppInstances" value="5"/>
+                    <property name="queueLengthPerNode" value="400"/>
+                    <property name="roundsToAverage" value="10"/>
+                    <property name="instancesPerScaleUp" value="1"/>
+                    <property name="availabilityZone" value="us-east-1c"/>
+                    <property name="securityGroup" value="ds-2011-02-23"/>
+                </service>
+                <service domain="wso2.bps.domain">
+                    <property name="payload" value="resources/cluster_node.zip"/>
+                    <property name="minAppInstances" value="1"/>
+                    <property name="maxAppInstances" value="5"/>
+                    <property name="queueLengthPerNode" value="400"/>
+                    <property name="roundsToAverage" value="10"/>
+                    <property name="instancesPerScaleUp" value="1"/>
+                    <property name="availabilityZone" value="us-east-1c"/>
+                    <property name="securityGroup" value="bps-2011-02-23"/>
+                </service>
+            </services>
+        </property>
+
+        <!--
+            The interval to trigger the task in seconds
+        -->
+        <trigger interval="5"/>
+    </task>
+</definitions>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java b/components/org.apache.stratos.mediator.autoscale/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
new file mode 100644
index 0000000..7d0d9fa
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
@@ -0,0 +1,105 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale;
+
+import java.io.File;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.tribes.TribesClusteringAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+public class AppDomainContextsTest extends TestCase {
+
+    private static Map<String, Map<String, ?>> map;
+    private LoadBalancerConfiguration lbConfig;
+    ConfigurationContext configCtx;
+    ClusteringAgent clusteringAgent;
+    
+    protected void setUp() throws Exception {
+        super.setUp();
+        configCtx = ConfigurationContextFactory.createEmptyConfigurationContext();
+        clusteringAgent = new TribesClusteringAgent();
+        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                    "worker"),
+                    "wso2.as1.domain", "worker", -1);
+        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                "mgt"),
+                "wso2.as1.domain", "mgt", -1);
+        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                "mgt"),
+                "wso2.as2.domain", "mgt", -1);
+        configCtx.getAxisConfiguration().setClusteringAgent(clusteringAgent);
+        
+        File f = new File("src/test/resources/loadbalancer.conf");
+        System.setProperty("loadbalancer.conf", f.getAbsolutePath());
+        lbConfig = LoadBalancerConfiguration.getInstance();
+        
+        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+        
+    }
+    
+    
+    public void testRemoval(){
+        // removing a cluster domain with only 1 sub domain 
+        lbConfig.removeServiceConfiguration("wso2.as2.domain", "mgt");
+        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+        
+        Assert.assertEquals(true, !map.containsKey("wso2.as2.domain"));
+        
+        // removing a cluster domain with more than 1 sub domain
+        lbConfig.removeServiceConfiguration("wso2.as1.domain", "mgt");
+        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+        
+        Assert.assertEquals(true, map.containsKey("wso2.as1.domain"));
+        Assert.assertEquals(true, map.get("wso2.as1.domain").get("mgt") == null);
+        Assert.assertEquals(true, map.get("wso2.as1.domain").get("worker") != null);
+    }
+    
+    public void testAddition(){
+        ServiceConfiguration config1 = lbConfig.new ServiceConfiguration();
+        config1.setDomain("wso2.as3.domain");
+        config1.setSub_domain("mgt");
+        lbConfig.addServiceConfiguration(config1);
+        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                "mgt"),
+                "wso2.as3.domain", "mgt", -1);
+        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+        
+        Assert.assertEquals(true, map.containsKey("wso2.as3.domain"));
+        Assert.assertEquals(true, map.get("wso2.as3.domain").get("mgt") != null);
+    }
+
+    @Deprecated // use only for writing test cases
+    void printKeys(Map<?,?> map){
+        for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
+            Object type = iterator.next();
+            System.out.println(type);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/test/resources/loadbalancer.conf b/components/org.apache.stratos.mediator.autoscale/src/test/resources/loadbalancer.conf
new file mode 100644
index 0000000..7b2a80a
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/test/resources/loadbalancer.conf
@@ -0,0 +1,50 @@
+loadbalancer {
+    instances	1;
+    enable_autoscaler	true;
+    # interval between two task executions in milliseconds
+    autoscaler_task_interval	5000;
+    # after an instance booted up, task will wait till this much of time and let the server started up
+    server_startup_delay		15000; #default will be 60000ms
+}
+
+services {
+    defaults {
+        min_app_instances 1;
+        max_app_instances       5;
+        max_requests_per_second   400;
+        alarming_upper_rate 0.65;
+        alarming_lower_rate 0.2;
+        scale_down_factor 0.25;
+        rounds_to_average       10;
+        instances_per_scale_up  1;
+        message_expiry_time     60000;
+    }
+
+    appserver {
+        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+        sub_domain      worker1;
+        domains   {
+            wso2.as1.domain {
+            	hosts as1.cloud-test.wso2.com;
+            	  min_app_instances   0;
+            	  sub_domain      worker;
+                tenant_range    1-5;
+            }
+            wso2.as1.domain {
+            	hosts mgt.as1.cloud-test.wso2.com;
+            	  min_app_instances   0;
+            	  sub_domain      mgt;
+                tenant_range    1-5;
+            }
+            wso2.as2.domain {
+            	hosts mgt.as2.cloud-test.wso2.com;
+            	  min_app_instances   0;
+            	  sub_domain      mgt;
+                tenant_range    1-5;
+            }
+            
+        }
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/pom.xml b/components/org.apache.stratos.tenant.activity.ui/pom.xml
new file mode 100644
index 0000000..ad3260a
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/pom.xml
@@ -0,0 +1,144 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.tenant.activity.ui</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Tenant Activity - User Interface</name>
+
+    <build>
+
+        <plugins>
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>1.5</source>
+                    <target>1.5</target>
+                </configuration>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Private-Package>
+                            org.apache.stratos.tenant.activity.ui.internal.*,
+                        </Private-Package>
+                        <Export-Package>
+                            org.apache.stratos.tenant.activity.ui.*,
+                        </Export-Package>
+                        <Import-Package>
+			    org.wso2.carbon.tenant.activity.stub.*; version="${carbon.platform.package.import.version.range}",
+                            org.apache.stratos.common.*,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,                            
+                            org.apache.lucene.*,
+                            *;resolution:=optional
+                        </Import-Package>
+                        <Carbon-Component>UIBundle</Carbon-Component>
+                    </instructions>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+        </dependency>
+	    <dependency>
+            <groupId>commons-codec.wso2</groupId>
+            <artifactId>commons-codec</artifactId>
+	    <version>${version.commons.codec}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.common.ui</artifactId>
+	    <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.equinox</groupId>
+            <artifactId>javax.servlet</artifactId>
+	    <version>3.0.0.v201112011016</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.ws.commons.axiom.wso2</groupId>
+            <artifactId>axiom</artifactId>
+	    <version>${axiom.wso2.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ui</artifactId>
+	    <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+	    <version>${apache.stratos.version}</version>
+        </dependency>
+	    <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.tenant.activity.stub</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+    </dependencies>
+    
+    <properties>
+	<version.commons.codec>1.4.0.wso2v1</version.commons.codec>
+    </properties>
+    
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/clients/TenantActivityServiceClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/clients/TenantActivityServiceClient.java b/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/clients/TenantActivityServiceClient.java
new file mode 100644
index 0000000..a7f3674
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/clients/TenantActivityServiceClient.java
@@ -0,0 +1,155 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.tenant.activity.ui.clients;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.authenticator.proxy.AuthenticationAdminClient;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.tenant.activity.stub.TenantActivityServiceExceptionException;
+import org.wso2.carbon.tenant.activity.stub.beans.xsd.*;
+import org.apache.stratos.tenant.activity.ui.internal.TenantActivityUIServiceComponent;
+import org.wso2.carbon.ui.CarbonUIUtil;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.utils.ServerConstants;
+import org.wso2.carbon.tenant.activity.stub.TenantActivityServiceStub;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpSession;
+import java.rmi.RemoteException;
+
+public class TenantActivityServiceClient {
+    private static final Log log = LogFactory.getLog(TenantActivityServiceClient.class);
+
+    private TenantActivityServiceStub stub;
+    private String epr;
+
+
+    public TenantActivityServiceClient(
+            String cookie, String backendServerURL, ConfigurationContext configContext)
+            throws RegistryException {
+
+        epr = backendServerURL + "TenantMonitorService";
+
+        try {
+            stub = new TenantActivityServiceStub(configContext, epr);
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate TenantMonitorService service client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public TenantActivityServiceClient(ServletConfig config, HttpSession session)
+            throws RegistryException {
+        String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+        String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+        ConfigurationContext configContext = (ConfigurationContext) config.
+                getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+        epr = backendServerURL + "TenantActivityService";
+
+        try {
+            stub = new TenantActivityServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate TenantMonitorService service client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public TenantActivityServiceClient(String url, ServletConfig config, HttpSession session)
+            throws Exception {
+        //String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+        ConfigurationContext configContext = (ConfigurationContext) config.
+                getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+        try {
+            String cookie = login(url + "/services/", 
+                    TenantActivityUIServiceComponent.stratosConfiguration.getAdminUserName(),
+                    TenantActivityUIServiceComponent.stratosConfiguration.getAdminPassword(), 
+                    configContext);
+            epr = url + "/services/TenantActivityService";
+            stub = new TenantActivityServiceStub(configContext, epr);
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate TenantMonitorService service client. ";
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+
+    public int getActiveTenantCount() throws TenantActivityServiceExceptionException, RemoteException {
+        int count = stub.getActiveTenantCount();
+        return count;
+    }
+
+    /*public String[] getActiveTenantList() throws TenantActivityServiceExceptionException, RemoteException {
+        return stub.getActiveTenantList();
+    } */
+
+    public PaginatedTenantDataBean getPaginatedActiveTenantList(int pageNumber) throws TenantActivityServiceExceptionException, RemoteException {
+        return stub.retrievePaginatedActiveTenants(pageNumber);
+    }
+
+    /*  public TenantDataBean[] getAllActiveTenantList() throws TenantActivityServiceExceptionException, RemoteException {
+        return stub.getAllActiveTenantList();
+    }*/
+
+    public boolean isTenantActiveInService(String domainName) throws TenantActivityServiceExceptionException, RemoteException {
+        return stub.isActiveTenantOnService(domainName);
+    }
+    
+    private String login(String serverUrl, String userName, 
+                               String password, ConfigurationContext confContext) throws UserStoreException {
+        String sessionCookie = null;
+        try {
+            AuthenticationAdminClient client =
+                    new AuthenticationAdminClient(confContext, serverUrl, null, null, false);
+            //TODO : get the correct IP
+            boolean isLogin = client.login(userName, password, "127.0.0.1");
+            if (isLogin) {
+                sessionCookie = client.getAdminCookie();
+            }
+        } catch (Exception e) {
+            throw new UserStoreException("Error in login to the server server: " + serverUrl +
+                                         "username: " + userName + ".", e);
+        }
+        return sessionCookie;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/internal/TenantActivityUIServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/internal/TenantActivityUIServiceComponent.java b/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/internal/TenantActivityUIServiceComponent.java
new file mode 100644
index 0000000..d8c8eea
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/internal/TenantActivityUIServiceComponent.java
@@ -0,0 +1,55 @@
+package org.apache.stratos.tenant.activity.ui.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.apache.stratos.common.util.StratosConfiguration;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * @scr.component name="org.wso2.stratos.tenant.activity.ui" immediate="true"
+ * @scr.reference name="config.context.service"
+ * interface="org.wso2.stratos.utils.ConfigurationContextService"
+ * cardinality="1..1" policy="dynamic"  bind="setConfigurationContextService"
+ * unbind="unsetConfigurationContextService"
+ * @scr.reference name="stratos.config.service"
+ * interface="org.wso2.stratos.stratos.common.util.StratosConfiguration" cardinality="1..1"
+ * policy="dynamic" bind="setStratosConfigurationService" unbind="unsetStratosConfigurationService"
+ */
+public class TenantActivityUIServiceComponent {
+    private static Log log = LogFactory.getLog(TenantActivityUIServiceComponent.class);
+    public static ConfigurationContextService contextService;
+    public static StratosConfiguration stratosConfiguration;
+
+    protected void activate(ComponentContext context) {
+        try {
+            if (log.isDebugEnabled()) {
+                log.error("******* Tenant Activity UI bundle is activated ******* ");
+            }
+        } catch (Throwable e) {
+            log.error("******* Error in activating Tenant Activity UI bundle ******* ", e);
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        if (log.isDebugEnabled()) {
+            log.debug("******* Tenant Activity UI bundle is deactivated ******* ");
+        }
+    }
+
+    protected void setStratosConfigurationService(StratosConfiguration stratosConfigService) {
+        TenantActivityUIServiceComponent.stratosConfiguration = stratosConfigService;
+    }
+
+    protected void unsetStratosConfigurationService(StratosConfiguration ccService) {
+        TenantActivityUIServiceComponent.stratosConfiguration = null;
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        TenantActivityUIServiceComponent.contextService = contextService;
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+        TenantActivityUIServiceComponent.contextService = null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/ManagerConfigurations.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/ManagerConfigurations.java b/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/ManagerConfigurations.java
new file mode 100644
index 0000000..294cb15
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/ManagerConfigurations.java
@@ -0,0 +1,147 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.tenant.activity.ui.utils;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.util.CommonUtil;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.xml.namespace.QName;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+
+public class ManagerConfigurations {
+
+    private static final String CONFIG_FILE = "throttling-agent-config.xml";
+
+    private static final String MANAGER_SERVICE_URL_PARAM_NAME = "managerServiceUrl";
+    private static final String USERNAME_PARAM_NAME = "userName";
+    private static final String PASSWORD_PARAM_NAME = "password";
+
+
+    private String managerServerUrl;
+    private String userName;
+    private String password;
+
+    private final static Log log = LogFactory.getLog(ManagerConfigurations.class);
+
+    private static final String CONFIG_NS =
+            "http://wso2.com/stratos/multitenancy/throttling/agent/config";
+    private static final String PARAMTERS_ELEMENT_NAME = "parameters";
+    private static final String PARAMTER_ELEMENT_NAME = "parameter";
+    private static final String PARAMTER_NAME_ATTR_NAME = "name";
+    private Map<String, String> parameters = new HashMap<String, String>();
+
+
+
+
+    public String getConfigFileName() throws Exception {
+
+        String configFileName = CarbonUtils.getCarbonConfigDirPath() +
+                File.separator + StratosConstants.MULTITENANCY_CONFIG_FOLDER +
+                File.separator + CONFIG_FILE;
+
+        return configFileName;
+
+    }
+
+
+    public ManagerConfigurations() throws Exception {
+
+        String throttlingAgentConfigFile = this.getConfigFileName();
+        try {
+            OMElement meteringConfig =
+                    CommonUtil.buildOMElement(new FileInputStream(throttlingAgentConfigFile));
+            deSerialize(meteringConfig);
+            Map<String, String> throttlingAgentParams = getParameters();
+            this.setUserName(throttlingAgentParams.get(USERNAME_PARAM_NAME));
+            this.setPassword(throttlingAgentParams.get(PASSWORD_PARAM_NAME));
+            this.setManagerServerUrl(throttlingAgentParams.get(MANAGER_SERVICE_URL_PARAM_NAME));
+        } catch (FileNotFoundException e) {
+            String msg = "Unable to find the file: " + throttlingAgentConfigFile + ".";
+            log.error(msg, e);
+        }
+    }
+
+    public void deSerialize(OMElement throttlingConfigEle) throws Exception {
+        Iterator meteringConfigChildIt = throttlingConfigEle.getChildElements();
+        while (meteringConfigChildIt.hasNext()) {
+            Object meteringConfigChild = meteringConfigChildIt.next();
+            if (!(meteringConfigChild instanceof OMElement)) {
+                continue;
+            }
+            OMElement meteringConfigChildEle = (OMElement) meteringConfigChild;
+            if (new QName(CONFIG_NS, PARAMTERS_ELEMENT_NAME, "").equals(meteringConfigChildEle
+                    .getQName())) {
+                Iterator parametersChildIt = meteringConfigChildEle.getChildElements();
+                while (parametersChildIt.hasNext()) {
+                    Object taskConfigChild = parametersChildIt.next();
+                    if (!(taskConfigChild instanceof OMElement)) {
+                        continue;
+                    }
+                    OMElement parameterChildEle = (OMElement) taskConfigChild;
+                    if (!new QName(CONFIG_NS, PARAMTER_ELEMENT_NAME, "").equals(parameterChildEle
+                            .getQName())) {
+                        continue;
+                    }
+                    String parameterName =
+                            parameterChildEle.getAttributeValue(new QName(PARAMTER_NAME_ATTR_NAME));
+                    String parameterValue = parameterChildEle.getText();
+                    parameters.put(parameterName, parameterValue);
+                }
+            }
+        }
+    }
+
+    public Map<String, String> getParameters() {
+        return parameters;
+    }
+
+
+    public String getUserName() {
+        return userName;
+    }
+
+    public void setUserName(String userName) {
+        this.userName = userName;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    public String getManagerServerUrl() {
+        return managerServerUrl;
+    }
+
+    public void setManagerServerUrl(String managerServerUrl) {
+        this.managerServerUrl = managerServerUrl;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/TenantMonitorUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/TenantMonitorUtil.java b/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/TenantMonitorUtil.java
new file mode 100644
index 0000000..54d9c83
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/TenantMonitorUtil.java
@@ -0,0 +1,143 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.tenant.activity.ui.utils;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.config.CloudServiceConfig;
+import org.apache.stratos.common.config.CloudServiceConfigParser;
+import org.apache.stratos.common.config.CloudServicesDescConfig;
+
+import java.util.*;
+
+import org.wso2.carbon.tenant.activity.stub.beans.xsd.PaginatedTenantDataBean;
+import org.wso2.carbon.tenant.activity.stub.beans.xsd.TenantDataBean;
+
+public class TenantMonitorUtil {
+    private static final Log log = LogFactory.getLog(TenantMonitorUtil.class);
+
+    public static Map<String, String[]> tenantList = new HashMap<String, String[]>();
+    public static Map<String, TenantDataBean[]> tenantDataList = new HashMap<String, TenantDataBean[]>();
+
+
+    private static ManagerConfigurations managerConfig = null;
+
+
+    public static ManagerConfigurations getManagerConfig() {
+        return managerConfig;
+    }
+
+    public static void setManagerConfig(ManagerConfigurations managerConfig) {
+        TenantMonitorUtil.managerConfig = managerConfig;
+    }
+
+  /*  public static Map<String, Integer> getActiveTenantCount(ServletConfig config, HttpSession session) throws Exception {
+        Map<String, Integer> map = new HashMap<String, Integer>();
+        try {
+            CloudServicesDescConfig cloudServicesDescConfig = CloudServiceConfigParser.loadCloudServicesConfiguration();
+
+            Map<String, CloudServiceConfig> cloudServicesConfigs = cloudServicesDescConfig.getCloudServiceConfigs();
+            for (String serviceName : cloudServicesConfigs.keySet()) {
+                String backEndURL = cloudServicesConfigs.get(serviceName).getLink();
+                System.out.println(backEndURL);
+                if (backEndURL == null) {
+                    try {
+                        TenantActivityServiceClient client = new TenantActivityServiceClient(config, session);
+                        map.put(serviceName, client.getActiveTenantCount());
+                        for (String nn : client.getActiveTenantList()) {
+                            System.out.println(nn);
+                        }
+                    } catch (Exception e) {
+                        log.error("Failed to get active tenants for manager service");
+                    }
+
+                } else {
+                    try {
+                        TenantActivityServiceClient client = new TenantActivityServiceClient(backEndURL, config, session);
+                        map.put(serviceName, client.getActiveTenantCount());
+                    } catch (Exception e) {
+                        log.error("failed to get Active tenants for" + serviceName + e.toString());
+                    }
+                }
+
+            }
+        } catch (Exception e) {
+            log.error("Error while retrieving cloud desc configuration");
+
+        }
+        return map;
+    }*/
+
+    public static Map<String, CloudServiceConfig> getCloudServiceConfigMap() {
+        try {
+            CloudServicesDescConfig cloudServicesDescConfig = CloudServiceConfigParser.loadCloudServicesConfiguration();
+            return cloudServicesDescConfig.getCloudServiceConfigs();
+        } catch (Exception e) {
+            log.error("Error while getting service names " + e.toString());
+        }
+        return null;
+    }
+
+    public static PaginatedTenantDataBean getPaginatedTenantData(int pageNumber, String serviceName) {
+        int entriesPerPage = 15;
+        List<TenantDataBean> tenantListOnService = Arrays.asList(tenantDataList.get(serviceName));
+        List<TenantDataBean> tenantUsages = new ArrayList<TenantDataBean>();
+        int i = 0;
+        int numberOfPages = 0;
+        for (TenantDataBean tenant : tenantListOnService) {
+            if (i % entriesPerPage == 0) {
+                numberOfPages++;
+            }
+            if (numberOfPages == pageNumber) {
+                tenantUsages.add(tenant);
+            }
+            i++;
+
+        }
+        PaginatedTenantDataBean paginatedTenantInfo = new PaginatedTenantDataBean();
+        paginatedTenantInfo.setTenantInfoBeans(
+                tenantUsages.toArray(new TenantDataBean[tenantUsages.size()]));
+        paginatedTenantInfo.setNumberOfPages(numberOfPages);
+        return paginatedTenantInfo;
+    }
+
+    public static boolean isTenantActiveOnService(String serviceName, String domain) {
+        boolean status = false;
+        for (TenantDataBean tenantBean : tenantDataList.get(serviceName)) {
+            if (tenantBean.getDomain().equalsIgnoreCase(domain)) {
+                status = true;
+            }
+        }
+        return status;
+    }
+
+    public static Map<String, String> getAdminParameters() {
+        Map<String, String> adminParameters = new HashMap<String, String>();
+        if (managerConfig == null) {
+            try {
+                managerConfig = new ManagerConfigurations();
+            } catch (Exception e) {
+                log.error("Failed to get administrator credentials" + e.toString());
+            }
+        }
+        adminParameters.put("userName", managerConfig.getUserName());
+        adminParameters.put("password", managerConfig.getPassword());
+        return adminParameters;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/META-INF/component.xml b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..a163b36
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/META-INF/component.xml
@@ -0,0 +1,35 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<component xmlns="http://products.wso2.org/carbon">
+    <!-- sample menu configuration -->
+    <menus>
+        <menu>
+            <id>all_tenant_monitor_menu</id>
+            <i18n-key>Tenant Activity Monitor</i18n-key>
+            <i18n-bundle>org.wso2.carbon.tenant.activity.ui.i18n.Resources</i18n-bundle>
+            <parent-menu>monitor_menu</parent-menu>
+            <link>../tenant-activity/tenant-activity.jsp</link>
+            <region>region4</region>
+            <order>50</order>
+            <style-class>manage</style-class>
+            <icon>../tenant-activity/images/tenant-usage-report.gif</icon>
+            <require-permission>/permission/protected/monitor/userUsage</require-permission>
+            <require-super-tenant>true</require-super-tenant>
+        </menu>
+    </menus>
+</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/JSResources.properties
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/JSResources.properties b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/JSResources.properties
new file mode 100644
index 0000000..f038b96
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/JSResources.properties
@@ -0,0 +1 @@
+session.timed.out=Session timed out. Please login again
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/Resources.properties
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/Resources.properties b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/Resources.properties
new file mode 100644
index 0000000..85081f9
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/Resources.properties
@@ -0,0 +1,11 @@
+service.name=Service Name
+active.user.count=Active User Count
+active.tenants.services= Active Tenants on Services
+view.list=View List
+active.tenant.count=Active Tenant Count
+active.tenants.on= Active Tenants on
+tenant.domain= Tenant Domain
+active.status=State
+enter.tenant.domain=Enter Tenant Domain
+tenant.status=Tenant State
+tenant.state.on.services.for.tenant= Tenant State on Services For Tenant Domain

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/css/tenant-usage.css
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/css/tenant-usage.css b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/css/tenant-usage.css
new file mode 100644
index 0000000..5c85728
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/css/tenant-usage.css
@@ -0,0 +1,28 @@
+.disableLink {
+    color: #aaaaaa;
+}
+
+.pageLinks {
+    background: #FFFFFF none repeat scroll 0%;
+    border: 1px solid #DDDDDD;
+    padding: 2px 3px;
+    text-decoration: none;
+    margin: 0px;
+    margin-left: 2px;
+    margin-right: 2px;
+}
+
+.pageLinks-selected {
+    background: #e8e9ae none repeat scroll 0%;
+    border: 1px solid #DDDDDD;
+    padding: 2px 3px;
+    text-decoration: none;
+    margin: 0px;
+    margin-left: 2px;
+    margin-right: 2px;
+}
+
+a {
+    color: #386698;
+    cursor: pointer;
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/images/view-usage.png
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/images/view-usage.png b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/images/view-usage.png
new file mode 100644
index 0000000..3d036c0
Binary files /dev/null and b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/images/view-usage.png differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/userguide.html
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/userguide.html b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/userguide.html
new file mode 100644
index 0000000..2c6a979
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/docs/userguide.html
@@ -0,0 +1,76 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+  <title>View Usage - User Guide</title>
+  <link href="../../admin/css/documentation.css" rel="stylesheet" type="text/css" media="all" />
+</head>
+
+<body>
+<h1>View Usage</h1>
+
+<p>
+You can view usage of the stratos resource by your organization from this page
+</p>
+
+<p>
+<img src="images/view-usage.png" alt="View Usage"/>
+<div><strong>Figure1: View Usage</strong></div>
+</p>
+
+<p>
+
+<table>
+    <thead>
+        <td>
+            The Form Field
+        </td>
+        <td>
+            Description
+        </td>
+    </thead>
+    <tbody>
+        <tr>
+            <td>Year-Month</td>
+            <td>The year and the month the usage is metered.</td>
+        </tr>
+        <tr>
+            <td>Number of Users</td>
+            <td>Number of users of your stratos account.</td>
+        </tr>
+        <tr>
+            <td>Active data storage</td>
+            <td>The registry data storage amount.</td>
+        </tr>
+        <tr>
+            <td>Registry Total Bandwidth</td>
+            <td>Total bandwidth consumed by the registry accesses.</td>
+        </tr>
+        <tr>
+            <td>Service Total Bandwidth</td>
+            <td>The bandwidth consumed by the web services.</td>
+        </tr>
+    </tbody>
+</table>
+
+</p>
+
+</body>
+
+</html>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant-ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant-ajaxprocessor.jsp b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant-ajaxprocessor.jsp
new file mode 100644
index 0000000..0c9a988
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant-ajaxprocessor.jsp
@@ -0,0 +1,59 @@
+<%--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ --%>
+<%@page contentType="text/html" pageEncoding="UTF-8" %>
+<%@ page import="org.json.JSONObject" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Invoice" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Payment" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%@ page import="java.util.Date" %>
+<%@ page import="org.wso2.carbon.tenant.activity.ui.clients.TenantActivityServiceClient" %>
+<%@ page import="java.io.Console" %>
+<%@ page import="javax.rmi.CORBA.Util" %>
+<%@ page import="org.wso2.carbon.tenant.activity.ui.utils.TenantMonitorUtil" %>
+<%@ page import="org.wso2.carbon.tenant.activity.stub.beans.xsd.PaginatedTenantDataBean" %>
+
+<%
+    String serverUrl = request.getParameter("backEndUrl");
+    String serviceName = request.getParameter("serviceName");
+    String domainName = request.getParameter("domainName");
+
+    boolean state = false;
+    if (serverUrl == null || "null".equals(serverUrl.trim())) {
+        try {
+            TenantActivityServiceClient client = new TenantActivityServiceClient(config, session);
+            state = client.isTenantActiveInService(domainName);
+        } catch (Exception e) {
+        }
+
+    } else {
+        try {
+            TenantActivityServiceClient client = new TenantActivityServiceClient(serverUrl, config, session);
+            state = client.isTenantActiveInService(domainName);
+        } catch (Exception e) {
+        }
+    }
+
+    try {
+        JSONObject obj = new JSONObject();
+        obj.put("isActive", state);
+        obj.put("service", serviceName);
+        out.write(obj.toString());
+    } catch (Exception e) {
+        e.printStackTrace();
+    }
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant.jsp
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant.jsp b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant.jsp
new file mode 100644
index 0000000..d938710
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/find-tenant.jsp
@@ -0,0 +1,110 @@
+<!--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+-->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib prefix="carbon" uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" %>
+<%@ page import="org.wso2.carbon.tenant.activity.ui.utils.TenantMonitorUtil" %>
+<%@ page import="org.apache.stratos.common.config.CloudServiceConfig" %>
+<%@ page import="java.util.Map" %>
+<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
+<script type="text/javascript" src="../registry_common/js/registry_validation.js"></script>
+<script type="text/javascript" src="../registry_common/js/registry_common.js"></script>
+<script type="text/javascript" src="../ajax/js/prototype.js"></script>
+<script type="text/javascript" src="js/tenant_config.js"></script>
+
+<carbon:jsi18n
+        resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.JSResources"
+        request="<%=request%>"/>
+
+<fmt:bundle basename="org.wso2.carbon.tenant.activity.ui.i18n.Resources">
+    <carbon:breadcrumb
+            label="govern.view_tenants.menu"
+            resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.Resources"
+            topPage="true"
+            request="<%=request%>"/>
+    <%
+        String domainNameStr = request.getParameter("domain");
+    %>
+    <div id="middle">
+        <h2><fmt:message key="tenant.state.on.services.for.tenant"/> "<%=domainNameStr%>"</h2>
+
+        <div id="workArea">
+            <table id="activeStateTable" cellpadding="0" cellspacing="0" border="0" style="width:100%"
+                   class="styledLeft">
+                <thead>
+                <tr>
+                    <th style="padding-left:5px;text-align:left;width:40%"><fmt:message key="service.name"/></th>
+                    <th style="padding-left:5px;text-align:left;"><fmt:message key="tenant.status"/></th>
+                </tr>
+                </thead>
+            </table>
+        </div>
+    </div>
+</fmt:bundle>
+<%
+    String domainName = request.getParameter("domain");
+    Map<String, CloudServiceConfig> cloudServicesConfigs = TenantMonitorUtil.getCloudServiceConfigMap();
+%>
+
+<script type="text/javascript">
+
+    function getStats() {
+        var serviceArray = new Array();
+    <%
+    for(String serviceName : cloudServicesConfigs.keySet()){
+    %>
+        var serviceObj = new Object();
+        serviceObj.backEndUrl = '<%=cloudServicesConfigs.get(serviceName).getLink()%>';
+        serviceObj.serviceName = '<%=serviceName%>';
+        serviceObj.domainName = '<%=domainName%>';
+        serviceArray.push(serviceObj);
+    <% }
+    %>
+
+        for (var i = 0; i < serviceArray.length; i++) {
+
+            jQuery.ajax({
+                type: 'GET',
+                url: 'find-tenant-ajaxprocessor.jsp',
+                data: 'backEndUrl=' + serviceArray[i].backEndUrl + '&serviceName=' + serviceArray[i].serviceName + '&domainName=' + serviceArray[i].domainName,
+                dataType: 'json',
+                async: true,
+                success: function(msg) {
+                    var resp = msg;
+                    var active = 'Active';
+                    var inActive = 'Inactive';
+                    if (resp.isActive === true) {
+                        document.getElementById('activeStateTable').innerHTML += '<tr><td>' + resp.service + '</td><td>' + active + '</td></tr>';
+                    }
+                    else {
+                        document.getElementById('activeStateTable').innerHTML += '<tr><td>' + resp.service + '</td><td>' + inActive + '</td></tr>';
+                    }
+                },
+                error:function () {
+                    CARBON.showErrorDialog('Could not connect to server');
+                    //document.getElementById('serviceStatTable').innerHTML += '<tr><td>' + eresp.servic + '</td><td>' + resp.count + '</td></tr>';
+                    document.getElementById('activeStateTable').innerHTML += 'Not Available';
+                }
+            });
+        }
+    }
+</script>
+
+<body onload="getStats();">
+<div>
+</div>
+</body>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/get-data-ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/get-data-ajaxprocessor.jsp b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/get-data-ajaxprocessor.jsp
new file mode 100644
index 0000000..15f558b
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/get-data-ajaxprocessor.jsp
@@ -0,0 +1,66 @@
+<%--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ --%>
+<%@page contentType="text/html" pageEncoding="UTF-8" %>
+<%@ page import="org.json.JSONObject" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Invoice" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Payment" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%@ page import="java.util.Date" %>
+<%@ page import="org.wso2.carbon.tenant.activity.ui.clients.TenantActivityServiceClient" %>
+<%@ page import="java.io.Console" %>
+<%@ page import="javax.rmi.CORBA.Util" %>
+<%@ page import="org.wso2.carbon.tenant.activity.ui.utils.TenantMonitorUtil" %>
+<%@ page import="org.wso2.carbon.tenant.activity.stub.beans.xsd.PaginatedTenantDataBean" %>
+
+<%
+    String serverUrl = request.getParameter("backEndUrl");
+    String serviceName = request.getParameter("serviceName");
+
+
+    int count = 0;
+    if (serverUrl == null || "null".equals(serverUrl.trim())) {
+        try {
+            TenantActivityServiceClient client = new TenantActivityServiceClient(config, session);
+           // TenantMonitorUtil.tenantDataList.put(serviceName, client.getAllActiveTenantList());
+           count=client.getActiveTenantCount();
+        } catch (Exception e) {
+        }
+
+    } else {
+        try {
+            TenantActivityServiceClient client = new TenantActivityServiceClient(serverUrl, config, session);
+           // count = client.getAllActiveTenantList().length;
+           count=client.getActiveTenantCount();
+            if (count > 0) {
+               // TenantMonitorUtil.tenantDataList.put(serviceName, client.getAllActiveTenantList());
+            } else {
+                TenantMonitorUtil.tenantDataList.put(serviceName, null);
+            }
+        } catch (Exception e) {
+        }
+    }
+
+    try {
+        JSONObject obj = new JSONObject();
+        obj.put("count", count);
+        obj.put("service", serviceName);
+        out.write(obj.toString());
+    } catch (Exception e) {
+        e.printStackTrace();
+    }
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/instance-usage-report.gif
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/instance-usage-report.gif b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/instance-usage-report.gif
new file mode 100644
index 0000000..4a1ae6a
Binary files /dev/null and b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/instance-usage-report.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/search.gif
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/search.gif b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/search.gif
new file mode 100644
index 0000000..cfe76b5
Binary files /dev/null and b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/search.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/tenant-usage-report.gif
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/tenant-usage-report.gif b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/tenant-usage-report.gif
new file mode 100644
index 0000000..a9b04e2
Binary files /dev/null and b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/tenant-usage-report.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/user-usage-report.gif
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/user-usage-report.gif b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/user-usage-report.gif
new file mode 100644
index 0000000..9070c35
Binary files /dev/null and b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/images/user-usage-report.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/show-active-tenants.jsp
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/show-active-tenants.jsp b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/show-active-tenants.jsp
new file mode 100644
index 0000000..7f9e0cc
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/show-active-tenants.jsp
@@ -0,0 +1,129 @@
+<!--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+-->
+<%@ page import="java.util.List" %>
+<%@ page import="org.wso2.carbon.tenant.activity.ui.clients.TenantActivityServiceClient" %>
+<%@ page import="org.wso2.carbon.tenant.activity.ui.utils.TenantMonitorUtil" %>
+<%@ page import="java.util.Map" %>
+<%@ page import="org.wso2.carbon.tenant.reg.agent.client.util.Util" %>
+<%@ page import="org.apache.stratos.common.config.CloudServiceConfig" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@ page import="org.wso2.carbon.CarbonConstants" %>
+<%@ page import="org.wso2.carbon.registry.common.ui.UIException" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
+<%@ page import="java.text.SimpleDateFormat" %>
+<%@ page import="java.util.Calendar" %>
+<%@ page import="java.util.Date" %>
+<%@ page import="org.wso2.carbon.tenant.activity.stub.TenantActivityServiceStub" %>
+<%@ page import="org.wso2.carbon.tenant.activity.stub.beans.xsd.TenantDataBean" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
+<script type="text/javascript" src="../registry_common/js/registry_validation.js"></script>
+<script type="text/javascript" src="../registry_common/js/registry_common.js"></script>
+<script type="text/javascript" src="../ajax/js/prototype.js"></script>
+<script type="text/javascript" src="js/tenant_config.js"></script>
+
+<carbon:jsi18n
+        resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.JSResources"
+        request="<%=request%>"/>
+
+<fmt:bundle basename="org.wso2.carbon.tenant.activity.ui.i18n.Resources">
+    <carbon:breadcrumb
+            label="govern.view_tenants.menu"
+            resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.Resources"
+            topPage="true"
+            request="<%=request%>"/>
+    <%
+        String serviceNameStr = request.getParameter("serviceName");
+    %>
+
+    <div id="middle">
+        <h2><fmt:message key="active.tenants.on"/> <%=serviceNameStr%>
+        </h2>
+
+        <div id="workArea">
+            <table id="serviceStatTable1" cellpadding="0" cellspacing="0" border="0" style="width:100%"
+                   class="styledLeft">
+                <thead>
+                <tr>
+                    <th style="padding-left:5px;text-align:left;width:30%"><fmt:message key="tenant.domain"/></th>
+                    <th style="padding-left:5px;text-align:left;"><fmt:message
+                            key="active.status"/></th>
+                </tr>
+                </thead>
+                <tbody>
+                <%
+                    String pageNumberStr = request.getParameter("pageNumber");
+                    if (pageNumberStr == null) {
+                        pageNumberStr = "0";
+
+                    }
+                    int pageNumber = 1;
+                    try {
+                        pageNumber = Integer.parseInt(pageNumberStr);
+                    } catch (NumberFormatException ignored) {
+                        // page number format exception
+                    }
+                    int numberOfPages = 1;
+                    try {
+                        String backEndUrl = TenantMonitorUtil.getCloudServiceConfigMap().get(request.getParameter("serviceName")).getLink();
+                        TenantActivityServiceClient client;
+                        if (backEndUrl == null || "null".equals(backEndUrl.trim())) {
+                            client = new TenantActivityServiceClient(config, session);
+                        } else {
+                            client = new TenantActivityServiceClient(backEndUrl, config, session);
+                        }
+                        for (TenantDataBean bean : client.getPaginatedActiveTenantList(pageNumber).getTenantInfoBeans()) {
+                %>
+                <tr>
+                    <td><%=bean.getDomain()%>
+                    </td>
+                    <td>Active</td>
+                </tr>
+                <%
+                    }
+                } catch (Exception e) {
+                %>
+                <tr>
+                    <td>No Data Available for this Service</td>
+                </tr>
+                <% }
+                    String reDirectPage = "show-active-tenants.jsp?serviceName=" + serviceNameStr + "&";
+                %>
+                <carbon:paginator pageNumber="<%=pageNumber%>" numberOfPages="<%=numberOfPages%>"
+                                  page="<%=reDirectPage%>" pageNumberParameterName="pageNumber"/>
+                </tbody>
+            </table>
+            <input type='hidden' name='serviceName' id="serviceName"/>
+        </div>
+    </div>
+</fmt:bundle>
+
+<script type="text/javascript">
+
+    function getStats() {
+        console.log("In the getStat() function");
+
+    }
+    function showTenants(serviceNameKey) {
+    }
+</script>


[18/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/CommonUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/CommonUtil.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/CommonUtil.java
deleted file mode 100644
index 8adf1e4..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/CommonUtil.java
+++ /dev/null
@@ -1,623 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.util;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.impl.builder.StAXOMBuilder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.common.constants.StratosConstants;
-import org.apache.stratos.common.internal.CloudCommonServiceComponent;
-import org.wso2.carbon.CarbonConstants;
-import org.wso2.carbon.registry.core.ActionConstants;
-import org.wso2.carbon.registry.core.RegistryConstants;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.registry.core.utils.AccessControlConstants;
-import org.wso2.carbon.user.api.RealmConfiguration;
-import org.wso2.carbon.user.core.AuthorizationManager;
-import org.wso2.carbon.user.core.UserRealm;
-import org.wso2.carbon.user.core.UserStoreException;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-import org.wso2.carbon.utils.CarbonUtils;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import javax.xml.namespace.QName;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.text.DateFormat;
-import java.text.DateFormatSymbols;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.regex.Pattern;
-
-/**
- * Common Utility methods for Stratos.
- * Now this class has been growing with several util methods - Should refactor accordingly.
- */
-public class CommonUtil {
-    private static final Log log = LogFactory.getLog(CommonUtil.class);
-    private static StratosConfiguration stratosConfig;
-    private static String eula;
-
-
-    private static final String ILLEGAL_CHARACTERS_FOR_EMAIL =
-            ".*[\\(\\)\\<\\>\\,\\;\\:\\\\\\\"\\[\\]].*";
-    private static final String EMAIL_FILTER_STRING = "^[^@]+@[^@.]+\\.[^@]*\\w\\w$";
-    private static Pattern emailFilterPattern = Pattern.compile(EMAIL_FILTER_STRING);
-    private static Pattern illegalCharactersPatternForEmail = Pattern
-            .compile(ILLEGAL_CHARACTERS_FOR_EMAIL);
-
-    public static StratosConfiguration getStratosConfig() {
-        return stratosConfig;
-    }
-
-    public static void setStratosConfig(StratosConfiguration stratosConfig) {
-        CommonUtil.stratosConfig = stratosConfig;
-    }
-
-    public static String getEula() {
-        return eula;
-    }
-
-    public static void setEula(String eula) {
-        CommonUtil.eula = eula;
-    }
-
-    /**
-     * Checks whether the email validation is mandatory from the configuration file.
-     *
-     * @return true, if the email validation is mandatory to login. Default is false.
-     */
-    public static boolean isEmailValidationMandatory() {
-        boolean isEmailValidationMandatory = false; //false by default.
-        if (stratosConfig != null) {   //make sure the configuration exists.
-            isEmailValidationMandatory = stratosConfig.getEmailValidationRequired();
-        }
-        return isEmailValidationMandatory;
-    }
-
-    /**
-     * Checks whether the email sending is enabled from the configuration file.
-     *
-     * @return true, if the email sending is disabled. By default, this is disabled, and tenant
-     * activation is done without any email sending.
-     */
-    public static boolean isTenantManagementEmailsDisabled() {
-        boolean isEmailsDisabled = true; //true by default.
-        if (stratosConfig != null) {   //make sure the configuration exists.
-            isEmailsDisabled = stratosConfig.isEmailsDisabled();
-        }
-        return isEmailsDisabled;
-    }
-
-    public static String getSuperAdminEmail() {
-        return stratosConfig.getSuperAdminEmail();
-    }
-
-    public static String getAdminUserName() {
-        return stratosConfig.getAdminUserName();
-    }
-    
-    public static String getAdminPassword() {
-        return stratosConfig.getAdminPassword();
-    }
-
-    public static boolean isTenantActivationModerated() {
-        return stratosConfig.isTenantActivationModerated();
-    }
-
-    public static boolean isChargedOnRegistration() {
-        return stratosConfig.isChargeOnRegistration();
-    }
-
-    /**
-     * Checks whether it is for the public cloud setup or Mars.
-     *
-     * @return true, if it is not for the private cloud setups. Default is true.
-     */
-    public static boolean isPublicCloudSetup() {
-        boolean isPublicCloudSetup = true;  // true by default.
-        if (stratosConfig != null) { //make sure the configuration exists.
-            isPublicCloudSetup = stratosConfig.isPublicCloudSetup();
-        }
-        return isPublicCloudSetup;
-    }
-
-    /**
-     * Gets the notification email address of the admin upon the tenant creation.
-     *
-     * @return notification email address for the tenant creations.
-     */
-    public static String getNotificationEmailAddress() {
-        String notificationEmailAddress = "";
-        if (stratosConfig != null) {
-            notificationEmailAddress = stratosConfig.getNotificationEmail();
-            try {
-                validateEmail(notificationEmailAddress);
-            } catch (Exception e) {
-                if (log.isWarnEnabled()) {
-                    log.warn("Invalid Email Address provided for tenant creation notification. " +
-                             "Please check whether the parameter NotificationEmail" +
-                             " is set properly in " +
-                             StratosConstants.STRATOS_CONF_FILE, e);
-                }
-                return "";
-            }
-        }
-        return notificationEmailAddress;
-    }
-
-    public static String getMonthString(Calendar calendar) {
-        int currentMonth = calendar.get(Calendar.MONTH);
-
-        String[] monthArr = new DateFormatSymbols().getMonths();
-        String month = monthArr[currentMonth];
-        return calendar.get(Calendar.YEAR) + "-" + month;
-    }
-
-    public static String getMonthString(int relativeMonth) {
-        Calendar newCalendar = Calendar.getInstance();
-        newCalendar.add(Calendar.MONTH, relativeMonth);
-
-        return CommonUtil.getMonthString(newCalendar);
-    }
-
-    public static Date getDateFromMonthString(String yearMonth) throws ParseException {
-        DateFormat yearMonthFormat = new SimpleDateFormat("yyyy-MMM");
-        return yearMonthFormat.parse(yearMonth);
-    }
-
-    public static String getCurrentMonthString() {
-        Calendar newCalendar = Calendar.getInstance();
-
-        return CommonUtil.getMonthString(newCalendar);
-    }
-
-
-    public static void setAnonAuthorization(String path, UserRealm userRealm)
-            throws RegistryException {
-
-        if (userRealm == null) {
-            return;
-        }
-
-        try {
-            AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
-            String everyoneRole = CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME;
-
-            accessControlAdmin.authorizeRole(everyoneRole, path, ActionConstants.GET);
-            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
-            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
-            accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);
-
-        } catch (UserStoreException e) {
-            String msg = "Could not set authorizations for the " + path + ".";
-            log.error(msg, e);
-            throw new RegistryException(msg);
-        }
-    }
-
-    public static void denyAnonAuthorization(String path, UserRealm userRealm)
-            throws RegistryException {
-        if (userRealm == null) {
-            return;
-        }
-
-        try {
-            AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
-            RealmConfiguration realmConfig;
-            try {
-                realmConfig = userRealm.getRealmConfiguration();
-            } catch (UserStoreException e) {
-                String msg = "Failed to retrieve realm configuration.";
-                log.error(msg, e);
-                throw new RegistryException(msg, e);
-            }
-
-            String everyoneRole = realmConfig.getEveryOneRoleName();
-
-            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.GET);
-            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
-            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
-            accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);
-
-        } catch (UserStoreException e) {
-            String msg = "Could not clear authorizations for the " + path + ".";
-            log.error(msg, e);
-            throw new RegistryException(msg);
-        }
-    }
-
-    /**
-     * builds the OMElement from the given inputStream
-     *
-     * @param inputStream, given input - inputStream
-     * @return OMElement
-     * @throws Exception, if building OMElement from the inputStream failed.
-     */
-    public static OMElement buildOMElement(InputStream inputStream) throws Exception {
-        XMLStreamReader parser;
-        try {
-            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
-        } catch (XMLStreamException e) {
-            String msg = "Error in initializing the parser to build the OMElement.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        // create the builder
-        StAXOMBuilder builder = new StAXOMBuilder(parser);
-        // get the root element (in this case the envelope)
-
-        return builder.getDocumentElement();
-    }
-
-
-    /**
-     * validates the email
-     *
-     * @param email - email address
-     * @throws Exception, if validation failed
-     */
-    public static void validateEmail(String email) throws Exception {
-        if (email == null) {
-            String msg = "Provided email value is null.";
-            log.warn(msg);
-            throw new Exception(msg);
-        }
-        email = email.trim();
-        if ("".equals(email)) {
-            String msg = "Provided email value is empty.";
-            log.warn(msg);
-            throw new Exception(msg);
-        }
-        if (illegalCharactersPatternForEmail.matcher(email).matches()) {
-            String msg = "Wrong characters in the email.";
-            log.error(msg);
-            throw new Exception(msg);
-        }
-        if (!emailFilterPattern.matcher(email).matches()) {
-            String msg = "Invalid email address is provided.";
-            log.error(msg);
-            throw new Exception(msg);
-        }
-    }
-
-    /**
-     * @param name     validate the name.
-     * @param variable entry name.
-     * @throws Exception if empty
-     */
-    public static void validateName(String name, String variable) throws Exception {
-        if (name.trim().equals("")) {
-            String msg = variable + " is not provided.";
-            log.error(msg);
-            throw new Exception(msg);
-        }
-    }
-
-    /**
-     * validates domain from the successkey
-     *
-     * @param governanceSystemRegistry - The governance system registry
-     * @param domain                   - tenant domain
-     * @param successKey               - successkey
-     * @return true, if successfully validated
-     * @throws RegistryException, if validation failed
-     */
-    public static boolean validateDomainFromSuccessKey(UserRegistry governanceSystemRegistry,
-                                                       String domain, String successKey)
-            throws RegistryException {
-        String domainValidatorInfoPath =
-                StratosConstants.DOMAIN_VALIDATOR_INFO_PATH + RegistryConstants.PATH_SEPARATOR +
-                domain + RegistryConstants.PATH_SEPARATOR +
-                StratosConstants.VALIDATION_KEY_RESOURCE_NAME;
-        if (governanceSystemRegistry.resourceExists(domainValidatorInfoPath)) {
-            Resource resource = governanceSystemRegistry.get(domainValidatorInfoPath);
-            String actualSuccessKey = resource.getProperty("successKey");
-            if (actualSuccessKey != null && successKey != null &&
-                actualSuccessKey.trim().equals(successKey.trim())) {
-                // the domain is correct
-                return true;
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Returns the configurations from the stratos configuration file.
-     *
-     * @return stratos configurations
-     */
-    public static StratosConfiguration loadStratosConfiguration() {
-        // gets the configuration file name from the StratosConstants.
-        String StratosConfigFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + 
-                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
-                StratosConstants.STRATOS_CONF_FILE;
-        return loadStratosConfiguration(StratosConfigFileName);
-    }
-
-    /**
-     * Loads the given Stratos Configuration file.
-     *
-     * @param configFilename Name of the configuration file
-     * @return the stratos configuration data.
-     */
-    private static StratosConfiguration loadStratosConfiguration(String configFilename) {
-        StratosConfiguration config = new StratosConfiguration();
-        File configFile = new File(configFilename);
-        if (configFile.exists()) {
-            FileInputStream inputStream = null;
-            try {
-                inputStream = new FileInputStream(configFile);
-                XMLStreamReader parser =
-                        XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
-                StAXOMBuilder builder = new StAXOMBuilder(parser);
-                OMElement documentElement = builder.getDocumentElement();
-                Iterator it = documentElement.getChildElements();
-                while (it.hasNext()) {
-                    OMElement element = (OMElement) it.next();
-
-                    if ("DisableTenantManagementEmails".equals(element.getLocalName())) {
-                        String disableEmails = element.getText();
-                        // by default, make the email validation mandatory.
-                        boolean isEmailsDisabled = true;
-                        if (disableEmails.trim().equalsIgnoreCase("false")) {
-                            isEmailsDisabled = false;
-                        }
-                        config.setEmailsDisabled(isEmailsDisabled);
-                    }
-                    // Checks whether Email Validation is mandatory to log in and use the registered
-                    // tenants.
-                    else if ("EmailValidationMandatoryForLogin".equals(element.getLocalName())) {
-                        String emailValidation = element.getText();
-                        //by default, make the email validation not mandatory.
-                        boolean isEmailValidationRequired = false;
-                        if (emailValidation.trim().equalsIgnoreCase("true")) {
-                            isEmailValidationRequired = true;
-                        }
-                        config.setEmailValidationRequired(isEmailValidationRequired);
-                    } else if ("ChargeOnRegistration".equals(element.getLocalName())) {
-                        String chargeOnRegistration = element.getText();
-                        boolean isChargedOnRegistration = false;
-                        if (chargeOnRegistration.trim().equalsIgnoreCase("true")) {
-                            isChargedOnRegistration = true;
-                        }
-                        config.setChargeOnRegistration(isChargedOnRegistration);
-                    } else if ("NotificationEmail".equals(element.getLocalName())) {
-                        config.setNotificationEmail(element.getText());
-                    } else if ("SuperAdminEmail".equals(element.getLocalName())) {
-                        config.setSuperAdminEmail(element.getText());
-                    } else if ("TenantActivationModerated".equals(element.getLocalName())){
-                        String isTenantActivationModerated = element.getText();
-                        boolean tenantActivationModerated = false;
-                        if (isTenantActivationModerated.trim().equalsIgnoreCase("true")) {
-                            tenantActivationModerated = true;
-                        }
-                        config.setTenantActivationModerated(tenantActivationModerated);
-                    }
-                    //Checks whether it is public cloud deployment.
-                    else if ("StratosPublicCloudSetup".equals(element.getLocalName())) {
-                        String cloudSetup = element.getText();
-                        //by default, make the email validation mandatory.
-                        boolean isStratosPublicCloudSetup = true;
-                        if (cloudSetup.trim().equalsIgnoreCase("false")) {
-                            isStratosPublicCloudSetup = false;
-                        }
-                        config.setPublicCloudSetup(isStratosPublicCloudSetup);
-                        //Setting the paypal url
-                    } else if ("PaypalUrl".equals(element.getLocalName())) {
-                        String paypalUrl = element.getText();
-                        config.setPaypalUrl(paypalUrl);
-                    } else if ("SkipSummaryGenerator".equals(element.getLocalName())) {
-                        String summaryGenerator = element.getText();
-                        boolean skipSummaryGenerator = false;
-                        if (summaryGenerator.trim().equalsIgnoreCase("true")) {
-                            skipSummaryGenerator = true;
-                        }
-                        config.setSkipSummaryGenerator(skipSummaryGenerator);
-                    }
-                    else if ("PaypalAPIUsername".equals(element.getLocalName())) {
-                        config.setPaypalAPIUsername(element.getText());
-                    } else if ("PaypalAPIPassword".equals(element.getLocalName())) {
-                        config.setPaypalAPIPassword(element.getText());
-                    } else if ("PaypalAPISignature".equals(element.getLocalName())) {
-                        config.setPaypalAPISignature(element.getText());
-                    }else if ("PaypalEnvironment".equals(element.getLocalName())){
-                        config.setPaypalEnvironment(element.getText());
-                    }else if("FinanceNotificationEmail".equals(element.getLocalName())){
-                        config.setFinanceNotificationEmail(element.getText());    
-                    }else if("UsagePlanUrl".equals(element.getLocalName())){
-                        config.setUsagePlanURL(element.getText());
-                    }else if("PaidJIRAUrl".equals(element.getLocalName())) {
-                        config.setPaidJIRAUrl(element.getText());
-                    }else if("PaidJIRAProject".equals(element.getLocalName())) {
-                        config.setPaidJIRAProject(element.getText());
-                    }else if("ForumUrl".equals(element.getLocalName())) {
-                        config.setForumUrl(element.getText());
-                    }else if("PaidUserGroup".equals(element.getLocalName())) {
-                        config.setPaidUserGroup(element.getText());
-                    }else if("NonpaidUserGroup".equals(element.getLocalName())) {
-                        config.setNonpaidUserGroup(element.getText());
-                    } else if("SupportInfoUrl".equals(element.getLocalName())) {
-                        config.setSupportInfoUrl(element.getText());
-                    }else if("IncidentCustomFieldId".equals(element.getLocalName())) {
-                        config.setIncidentCustomFieldId(element.getText());
-                    } else if("IncidentImpactCustomFieldId".equals(element.getLocalName())) {
-                        config.setIncidentImpactCustomFieldId(element.getText());
-                    } else if ("GoogleAnalyticsURL".equals(element.getLocalName())) {
-                        config.setGoogleAnalyticsURL(element.getText());
-                    } else if("StratosEventListener".equals(element.getLocalName())) {
-                        populateEventListenerProperties(config, element);
-                    } else if ("managerServiceUrl".equals(element.getLocalName())) {
-                        config.setManagerServiceUrl(element.getText());
-                    } else if ("adminUserName".equals(element.getLocalName())) {
-                        config.setAdminUserName(element.getText());
-                    } else if ("adminPassword".equals(element.getLocalName())) {
-                        config.setAdminPassword(element.getText());
-                    } else if("SSOLoadingMessage".equals(element.getLocalName())){
-                        config.setSsoLoadingMessage(element.getText());
-                    }
-                }
-                return config;
-            } catch (Exception e) {
-                String msg = "Error in loading Stratos Configurations File: " + configFilename + ".";
-                log.error(msg, e);
-                return config; //returns the default configurations, if the file could not be loaded.
-            } finally {
-                if (inputStream != null) {
-                    try {
-                        inputStream.close();
-                    } catch (IOException e) {
-                        log.error("Could not close the Configuration File " + configFilename);
-                    }
-                }
-            }
-        }
-        log.error("Unable to locate the stratos configurations file. " +
-                  "Default Settings will be used.");
-        return config; // return the default configuratiosn, if the file not found.
-    }
-    
-    
-    private static void populateEventListenerProperties(StratosConfiguration config,
-                                                        OMElement element) throws RegistryException {
-        config.setStratosEventListenerName(element.getAttributeValue(new QName("class")));
-        Iterator<?> ite =
-                          element.getChildrenWithName(new QName("Property"));
-        while (ite.hasNext()) {
-            OMElement propElem = (OMElement) ite.next();
-            String propName = propElem.getAttributeValue(new QName("name"));
-            String propValue = propElem.getText();
-            config.setStratosEventListenerProperty(propName, propValue);
-        }
-    }
-
-    /**
-     * Loading the EULA.
-     * ultimately we shall be loading the eula from the web page itself.
-     * But loading from file should be there to customize the EULA based on the private deployments,
-     * etc.
-     *
-     * @return eula
-     */
-    public static String loadTermsOfUsage() {
-        // currently loads from the file; gets the eula file name from the StratosConstants.
-        String StratosEULAFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator +
-                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
-                StratosConstants.STRATOS_EULA;
-        return loadTermsOfUsage(StratosEULAFileName);
-    }
-
-    private static String loadTermsOfUsage(String eulaFile) {
-        String eula = StratosConstants.STRATOS_EULA_DEFAULT_TEXT;
-        File configFile = new File(eulaFile);
-        if (configFile.exists()) {
-            FileInputStream inputStream = null;
-            try {
-                inputStream = new FileInputStream(configFile);
-                XMLStreamReader parser =
-                        XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
-                StAXOMBuilder builder = new StAXOMBuilder(parser);
-                OMElement documentElement = builder.getDocumentElement();
-                Iterator it = documentElement.getChildElements();
-                while (it.hasNext()) {
-                    OMElement element = (OMElement) it.next();
-
-                    //Checks whether Email Validation is mandatory for tenant registration complete.
-                    if ("EULA".equalsIgnoreCase(element.getLocalName())) {
-                        eula = element.getText();
-                    }
-                }
-                return eula;
-            } catch (Exception e) {
-                String msg = "Error in loading Stratos Terms and Conditions File.";
-                log.error(msg, e);
-                return eula; //returns the default text, if the file could not be loaded.
-            } finally {
-                if (inputStream != null) {
-                    try {
-                        inputStream.close();
-                    } catch (IOException e) {
-                        log.error("Could not close the EULA File " + eulaFile);
-                    }
-                }
-            }
-        }
-        if (log.isDebugEnabled()) {
-            log.debug("Unable to locate the stratos EULA file. Default value will be used.");
-        }
-        return eula; // return the default, if the file not found.
-    }
-
-
-    /**
-     * method to check whether a domain name is available to register given a domain name
-     * @param tenantDomain, domain name
-     * @return true, if the domain is available to register
-     * @throws Exception, if checking the existence of the tenant is failed.
-     */
-    public static boolean isDomainNameAvailable(String tenantDomain) throws Exception {
-
-        TenantManager tenantManager = CloudCommonServiceComponent.getTenantManager();
-          // The registry reserved words are checked first.
-          if (tenantDomain.equals("atom") || tenantDomain.equals("registry")
-                  || tenantDomain.equals("resource")) {
-              String msg = "You can not use a registry reserved word:" + tenantDomain +
-                           ":as a tenant domain. Please choose a different one.";
-              log.error(msg);
-              throw new Exception(msg);
-          }
-
-          int tenantId;
-          try {
-              tenantId = tenantManager.getTenantId(tenantDomain);
-          } catch (UserStoreException e) {
-              String msg = "Error in getting the tenant id for the given domain  " +
-                           tenantDomain + ".";
-              log.error(msg);
-              throw new Exception(msg, e);
-          }
-
-          // check a tenant with same domain exist.
-          if ((tenantId != MultitenantConstants.INVALID_TENANT_ID && tenantId != MultitenantConstants.SUPER_TENANT_ID) ||
-                  tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
-              String msg =
-                           "A tenant with same domain already exist. " +
-                                   "Please use a different domain name. tenant domain: " +
-                                   tenantDomain + ".";
-              log.info(msg);
-              return false;
-          }
-          return true;
-      }
-}
-
-
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java
deleted file mode 100644
index 4dc269e..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.util;
-
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-
-public class MeteringAccessValidationUtils {
-
-	public static final String ERROR_MSG_PROPERTY_KEY_POST_FIX = "error_msg";
-	public static final String IS_BLOCKED_PROPERTY_KEY_POST_FIX = "is_blocked";
-
-	public static String generateIsBlockedPropertyKey(String action) {
-		return action + "_" + IS_BLOCKED_PROPERTY_KEY_POST_FIX;
-	}
-
-	public static String generateErrorMsgPropertyKey(String action) {
-		return action + "_" + ERROR_MSG_PROPERTY_KEY_POST_FIX;
-	}
-
-	public static Set<String> getAvailableActions(Properties properties) {
-		Set propertyKeys = properties.keySet();
-		Set<String> actions = new HashSet<String>();
-		for (Object propertyKeyObj : propertyKeys) {
-			String propertyKey = (String) propertyKeyObj;
-			if (propertyKey.endsWith(IS_BLOCKED_PROPERTY_KEY_POST_FIX)) {
-			    // -1 for the length of the '_'
-				String action =
-				        propertyKey.substring(0, propertyKey.length() -
-				                IS_BLOCKED_PROPERTY_KEY_POST_FIX.length() - 1);
-				actions.add(action);
-			}
-		}
-		return actions;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/StratosConfiguration.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/StratosConfiguration.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/StratosConfiguration.java
deleted file mode 100644
index 2226593..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/StratosConfiguration.java
+++ /dev/null
@@ -1,319 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.util;
-
-import java.lang.String;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Class for the stratos specific parameters configuration
- */
-public class StratosConfiguration {
-
-    // By default email sending is disabled. Changed according to the configuration file.
-    private boolean emailsDisabled = true;
-
-    private boolean emailValidationRequired = false;
-    private boolean isPublicCloudSetup = true;
-    private boolean isTenantActivationModerated = false;
-    private boolean chargeOnRegistration = false;
-    private String SuperAdminEmail = "";
-    private String paypalUrl = "";
-    private String paypalAPIUsername = "";
-    private String paypalAPIPassword = "";
-    private String paypalAPISignature = "";
-    private String paypalEnvironment="";
-    private String usagePlanURL = "";
-    private String paidJIRAUrl = "";
-    private String paidJIRAProject = "";
-    private String forumUrl = "";
-    private String paidUserGroup = "";
-    private String nonpaidUserGroup = "";
-    private String supportInfoUrl = "";
-    private String incidentCustomFieldId = ""; // todo this is a custom field id of JIRA, this need to be dynamically get in jira reporting component
-    private String incidentImpactCustomFieldId = "";
-    private String stratosEventListenerName ="";
-    private Map<String, String> stratosEventProperties = new HashMap<String, String>();
-    private String googleAnalyticsURL;
-    private String managerServiceUrl = "";
-    private String adminUserName = "";
-    private String adminPassword = "";
-    private String ssoLoadingMessage="";
-
-    /**
-     * @return Stratos Manager service url
-     */
-    public String getManagerServiceUrl() {
-        return managerServiceUrl;
-    }
-
-    public void setManagerServiceUrl(String managerServiceUrl) {
-        this.managerServiceUrl = managerServiceUrl;
-    }
-
-    /**
-     * @return Super admin User name
-     */
-    public String getAdminUserName() {
-        return adminUserName;
-    }
-
-    public void setAdminUserName(String adminUserName) {
-        this.adminUserName = adminUserName;
-    }
-
-    /**
-     * @return super admin password
-     */
-    public String getAdminPassword() {
-        return adminPassword;
-    }
-
-    public void setAdminPassword(String adminPassword) {
-        this.adminPassword = adminPassword;
-    }
-
-    //This parameter used to skip usage summary generator
-     private boolean skipSummaryGenerator = false;
-
-    public boolean isSkipSummaryGenerator() {
-        return skipSummaryGenerator;
-    }
-
-    public void setSkipSummaryGenerator(boolean skipSummaryGenerator) {
-        this.skipSummaryGenerator = skipSummaryGenerator;
-    }
-    //This is the url that we pointed users when they need to aware about usage plans
-
-    public String getUsagePlanURL() {
-        return usagePlanURL;
-    }
-
-    public void setUsagePlanURL(String usagePlanURL) {
-        this.usagePlanURL = usagePlanURL;
-    }
-
-    //Email address for general notifications
-    private String notificationEmail = "";
-    //Email address for finance related notifications
-    private String financeNotificationEmail = "";
-
-    public boolean isTenantActivationModerated() {
-        return isTenantActivationModerated;
-    }
-
-    public void setTenantActivationModerated(boolean tenantActivationModerated) {
-        isTenantActivationModerated = tenantActivationModerated;
-    }
-
-    public String getSuperAdminEmail() {
-        return SuperAdminEmail;
-    }
-
-    public void setSuperAdminEmail(String superAdminEmail) {
-        SuperAdminEmail = superAdminEmail;
-    }
-
-    public boolean getEmailValidationRequired() {
-        return emailValidationRequired;
-    }
-
-    public String getPaypalUrl() {
-        return paypalUrl;
-    }
-
-    public void setPaypalUrl(String paypalUrl) {
-        this.paypalUrl = paypalUrl;
-    }
-
-    public void setEmailValidationRequired(boolean emailValidationRequired) {
-        this.emailValidationRequired = emailValidationRequired;
-    }
-
-    public boolean isPublicCloudSetup() {
-        return isPublicCloudSetup;
-    }
-
-    public void setPublicCloudSetup(boolean publicCloudSetup) {
-        isPublicCloudSetup = publicCloudSetup;
-    }
-
-    public String getNotificationEmail() {
-        return notificationEmail;
-    }
-
-    public void setNotificationEmail(String notificationEmail) {
-        this.notificationEmail = notificationEmail;
-    }
-
-    public String getPaypalAPIUsername() {
-        return paypalAPIUsername;
-    }
-
-    public void setPaypalAPIUsername(String paypalAPIUsername) {
-        this.paypalAPIUsername = paypalAPIUsername;
-    }
-
-    public String getPaypalAPIPassword() {
-        return paypalAPIPassword;
-    }
-
-    public void setPaypalAPIPassword(String paypalAPIPassword) {
-        this.paypalAPIPassword = paypalAPIPassword;
-    }
-
-    public String getPaypalAPISignature() {
-        return paypalAPISignature;
-    }
-
-    public void setPaypalAPISignature(String paypalAPISignature) {
-        this.paypalAPISignature = paypalAPISignature;
-    }
-
-    public String getFinanceNotificationEmail() {
-        return financeNotificationEmail;
-    }
-
-    public void setFinanceNotificationEmail(String financeNotificationEmail) {
-        this.financeNotificationEmail = financeNotificationEmail;
-    }
-
-    public String getPaidJIRAUrl() {
-        return paidJIRAUrl;
-    }
-
-    public void setPaidJIRAUrl(String paidJIRAUrl) {
-        this.paidJIRAUrl = paidJIRAUrl;
-    }
-
-    public String getPaidJIRAProject() {
-        return paidJIRAProject;
-    }
-
-    public void setPaidJIRAProject(String paidJIRAProject) {
-        this.paidJIRAProject = paidJIRAProject;
-    }
-
-    public String getForumUrl() {
-        return forumUrl;
-    }
-
-    public void setForumUrl(String forumUrl) {
-        this.forumUrl = forumUrl;
-    }
-
-    public String getPaidUserGroup() {
-        return paidUserGroup;
-    }
-
-    public void setPaidUserGroup(String paidUserGroup) {
-        this.paidUserGroup = paidUserGroup;
-    }
-
-    public String getNonpaidUserGroup() {
-        return nonpaidUserGroup;
-    }
-
-    public void setNonpaidUserGroup(String nonpaidUserGroup) {
-        this.nonpaidUserGroup = nonpaidUserGroup;
-    }
-
-    public String getSupportInfoUrl() {
-        return supportInfoUrl;
-    }
-
-    public void setSupportInfoUrl(String supportInfoUrl) {
-        this.supportInfoUrl = supportInfoUrl;
-    }
-
-    public String getIncidentCustomFieldId() {
-        return incidentCustomFieldId;
-    }
-
-    public void setIncidentCustomFieldId(String incidentCustomFieldId) {
-        this.incidentCustomFieldId = incidentCustomFieldId;
-    }
-
-    public String getIncidentImpactCustomFieldId() {
-        return incidentImpactCustomFieldId;
-    }
-
-    public void setIncidentImpactCustomFieldId(String incidentImpactCustomFieldId) {
-        this.incidentImpactCustomFieldId = incidentImpactCustomFieldId;
-    }
-    
-    public String getStratosEventListenerName() {
-        return stratosEventListenerName;
-    }
-
-    public void setStratosEventListenerName(String stratosEventListenerName) {
-        this.stratosEventListenerName = stratosEventListenerName;
-    }
-
-    public String getStratosEventListenerPropertyValue(String key) {
-        return stratosEventProperties.get(key);
-    }
-
-    public void setStratosEventListenerProperty(String key, String value) {
-        stratosEventProperties.put(key, value);
-    }
-
-    public String getPaypalEnvironment() {
-        return paypalEnvironment;
-    }
-
-    public void setPaypalEnvironment(String paypalEnvironment) {
-        this.paypalEnvironment = paypalEnvironment;
-    }
-
-    public String getGoogleAnalyticsURL() {
-        return googleAnalyticsURL;
-    }
-
-    public void setGoogleAnalyticsURL(String googleAnalyticsURL) {
-        this.googleAnalyticsURL = googleAnalyticsURL;
-    }
-
-    public boolean isEmailsDisabled() {
-        return emailsDisabled;
-    }
-
-    public void setEmailsDisabled(boolean emailsDisabled) {
-        this.emailsDisabled = emailsDisabled;
-    }
-
-    public boolean isChargeOnRegistration() {
-        return chargeOnRegistration;
-    }
-
-    public void setChargeOnRegistration(boolean chargeOnRegistration) {
-        this.chargeOnRegistration = chargeOnRegistration;
-    }
-
-    public String getSsoLoadingMessage() {
-        return ssoLoadingMessage;
-    }
-
-    public void setSsoLoadingMessage(String ssoLoadingMessage) {
-        this.ssoLoadingMessage = ssoLoadingMessage;
-    }
-    
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.common/2.1.2/src/main/resources/META-INF/services.xml
deleted file mode 100644
index 7f0bcf3..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  ~ Licensed to the Apache Software Foundation (ASF) under one
-  ~ or more contributor license agreements. See the NOTICE file
-  ~ distributed with this work for additional information
-  ~ regarding copyright ownership. The ASF licenses this file
-  ~ to you under the Apache License, Version 2.0 (the
-  ~ "License"); you may not use this file except in compliance
-  ~ with the License. You may obtain a copy of the License at
-  ~
-  ~ http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing,
-  ~ software distributed under the License is distributed on an
-  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-  ~ KIND, either express or implied. See the License for the
-  ~ specific language governing permissions and limitations
-  ~ under the License.
-  -->
-<serviceGroup>
-
-    <service name="PackageInfoService" scope="transportsession">
-        <transports>
-            <transport>https</transport>
-        </transports>
-        <parameter name="ServiceClass" locked="false">
-            org.apache.stratos.common.services.PackageInfoService
-        </parameter>
-        <parameter name="adminService" locked="ture">false</parameter>
-    </service>
-
-    <parameter name="hiddenService" locked="ture">true</parameter>
-    
-</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/resources/cloud-services-desc.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/resources/cloud-services-desc.xml b/components/org.apache.stratos.common/2.1.2/src/main/resources/cloud-services-desc.xml
deleted file mode 100644
index 15fb4b9..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/resources/cloud-services-desc.xml
+++ /dev/null
@@ -1,109 +0,0 @@
-<!--
- ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- ~
- ~ WSO2 Inc. licenses this file to you under the Apache License,
- ~ Version 2.0 (the "License"); you may not use this file except
- ~ in compliance with the License.
- ~ You may obtain a copy of the License at
- ~
- ~    http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing,
- ~ software distributed under the License is distributed on an
- ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- ~ KIND, either express or implied.  See the License for the
- ~ specific language governing permissions and limitations
- ~ under the License.
- -->
-<cloudServices xmlns="http://wso2.com/carbon/cloud/mgt/services">
-    <cloudService name="WSO2 Stratos Manager">
-    </cloudService>
-    <cloudService name="WSO2 Enterprise Service Bus" default="true">
-      <label>Enterprise Service Bus</label>
-      <link>https://esb.stratoslive.wso2.com</link>
-      <icon>
-        https://localhost:9443/cloud-services-icons/esb.gif
-      </icon>
-      <description>Enterprise Service Bus in the cloud.</description>
-    </cloudService>
-    <cloudService name="WSO2 Application Server" default="true">
-        <label>Application Server</label>
-        <link>https://appserver.stratoslive.wso2.com</link>
-        <icon>
-            https://localhost:9443/cloud-services-icons/appserver.gif
-        </icon>
-        <description>Application Server in the cloud.</description>
-    </cloudService>
-    <cloudService name="WSO2 Data Services Server" default="true">
-      <label>Data Services Server</label>
-      <link>https://dss.stratoslive.wso2.com</link>
-      <icon>
-        https://localhost:9443/cloud-services-icons/ds.gif
-      </icon>
-      <description>Data Services Server in the cloud.</description>
-    </cloudService>
-    <cloudService name="WSO2 Governance" default="true">
-        <label>Governance</label>
-        <link>https://governance.stratoslive.wso2.com</link>
-        <description>Governance in the cloud.</description>
-        <icon>
-            https://localhost:9443/cloud-services-icons/governance.gif
-        </icon>
-    </cloudService>
-    <cloudService name="WSO2 Identity" default="true">
-        <label>Identity</label>
-        <link>https://identity.stratoslive.wso2.com</link>
-        <icon>
-            https://localhost:9443/cloud-services-icons/identity.gif
-        </icon>
-        <description>Identity in the cloud.</description>
-    </cloudService>
-	<cloudService name="WSO2 Business Activity Monitor" default="true">
-        <label>Business Activity Monitor</label>
-        <link>https://bam.stratoslive.wso2.com</link>
-        <icon>
-            https://localhost:9443/cloud-services-icons/bam.gif
-        </icon>
-        <description>Business Activity Monitor in the cloud.</description>
-	</cloudService>
-    <cloudService name="WSO2 Business Process Server" default="true">
-      <label>Business Process Server</label>
-      <link>https://bps.stratoslive.wso2.com</link>
-      <icon>
-        https://localhost:9443/cloud-services-icons/bps.gif
-      </icon>
-      <description>Business Process Server in the cloud.</description>
-    </cloudService>
-	<cloudService name="WSO2 Business Rule Server" default="true">
-        <label>Business Rule Server</label>
-        <link>https://brs.stratoslive.wso2.com</link>
-        <icon>
-            https://localhost:9443/cloud-services-icons/brs.gif
-        </icon>
-        <description>Business Rule Server in the cloud.</description>
-	</cloudService>
-	<cloudService name="WSO2 Mashup Server" default="true">
-        <label>Mashup Server</label>
-        <link>https://mashup.stratoslive.wso2.com</link>
-        <icon>
-            https://localhost:9443/cloud-services-icons/mashup.gif
-        </icon>
-        <description>Mashup Server in the cloud.</description>
-    </cloudService>
-    <cloudService name="WSO2 Gadgets" default="true">
-        <label>Gadgets</label>
-        <link>https://gadget.stratoslive.wso2.com</link>
-        <icon>
-            https://localhost:9443/cloud-services-icons/gadget.gif
-        </icon>
-        <description>Gadgets in the cloud.</description>
-    </cloudService>
-    <cloudService name="WSO2 Cloud Services Gateway" default="true">
-        <label>Cloud Gateway</label>
-	<link>https://csg.stratoslive.wso2.com</link>
-	<icon>
-            https://localhost:9443/cloud-services-icons/csg.gif
-	</icon>
-	<description>WSO2 Cloud Services Gateway in the cloud.</description>
-    </cloudService>
-</cloudServices>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/test/java/org/apache/stratos/common/test/CommonTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/test/java/org/apache/stratos/common/test/CommonTest.java b/components/org.apache.stratos.common/2.1.2/src/test/java/org/apache/stratos/common/test/CommonTest.java
deleted file mode 100644
index dc61fc4..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/test/java/org/apache/stratos/common/test/CommonTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.test;
-
-import junit.framework.TestCase;
-import org.apache.stratos.common.util.CommonUtil;
-
-public class CommonTest extends TestCase {
-    public void testEmailValidation() throws Exception {
-        try {
-            CommonUtil.validateEmail("damn@right.com");
-            assertTrue(true);
-        } catch (Exception e) {
-            assertTrue(false);
-        }
-
-        try {
-            CommonUtil.validateEmail("damn@right].com");
-            assertTrue(false);
-        } catch (Exception e) {
-            assertTrue(true);
-            assertEquals("Wrong characters in the email.", e.getMessage());
-        }
-
-        try {
-            CommonUtil.validateEmail("damn@right@wrong.com");
-            assertTrue(false);
-        } catch (Exception e) {
-            assertTrue(true);
-            assertEquals("Invalid email address is provided.", e.getMessage());
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/pom.xml b/components/org.apache.stratos.common/pom.xml
new file mode 100644
index 0000000..2342449
--- /dev/null
+++ b/components/org.apache.stratos.common/pom.xml
@@ -0,0 +1,85 @@
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one
+  ~ or more contributor license agreements. See the NOTICE file
+  ~ distributed with this work for additional information
+  ~ regarding copyright ownership. The ASF licenses this file
+  ~ to you under the Apache License, Version 2.0 (the
+  ~ "License"); you may not use this file except in compliance
+  ~ with the License. You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing,
+  ~ software distributed under the License is distributed on an
+  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~ KIND, either express or implied. See the License for the
+  ~ specific language governing permissions and limitations
+  ~ under the License.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.common</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Common</name>
+
+    <build>
+
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.apache.stratos.common.*,
+                        </Export-Package>
+                        <Import-Package>
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.user.core.*,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.mgt</artifactId>
+        </dependency>
+        <dependency>
+             <groupId>junit</groupId>
+             <artifactId>junit</artifactId>
+             <scope>test</scope>
+         </dependency>        
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/TenantBillingService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/TenantBillingService.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/TenantBillingService.java
new file mode 100644
index 0000000..23cb7ae
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/TenantBillingService.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common;
+
+import org.apache.stratos.common.exception.StratosException;
+import org.wso2.carbon.user.api.Tenant;
+
+/**
+ * The OSGI service interface that enables tenant related billing actions.
+ */
+public interface TenantBillingService {
+    
+    public void addUsagePlan(Tenant tenant, String usagePlan) throws StratosException;
+    
+    public String getActiveUsagePlan(String tenantDomain) throws StratosException;
+    
+    public void updateUsagePlan(String tenantDomain, String usagePlan) throws StratosException;
+    
+    public void activateUsagePlan(String tenantDomain) throws StratosException;
+    
+    public void deactivateActiveUsagePlan(String tenantDomain) throws StratosException;
+
+    public void deleteBillingData(int tenantId) throws StratosException;
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/beans/TenantInfoBean.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/beans/TenantInfoBean.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/beans/TenantInfoBean.java
new file mode 100755
index 0000000..447814d
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/beans/TenantInfoBean.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.common.beans;
+
+import java.util.Calendar;
+
+/**
+ * Bean class for Tenant Information
+ */
+public class TenantInfoBean {
+
+    private String admin; //admin's user name
+    private String firstname;
+    private String lastname;
+    private String adminPassword;
+    private String tenantDomain;
+    private int tenantId;
+    private String email;
+    private boolean active;
+    private String successKey;
+    Calendar createdDate;
+    private String originatedService;
+    private String usagePlan;
+
+    public String getFirstname() {
+        return firstname;
+    }
+
+    public void setFirstname(String firstname) {
+        this.firstname = firstname;
+    }
+
+    public String getLastname() {
+        return lastname;
+    }
+
+    public void setLastname(String lastname) {
+        this.lastname = lastname;
+    }
+
+    public String getEmail() {
+
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
+
+    public int getTenantId() {
+        return tenantId;
+    }
+
+    public void setTenantId(int tenantId) {
+        this.tenantId = tenantId;
+    }
+
+    public String getTenantDomain() {
+        return tenantDomain;
+    }
+
+    public void setTenantDomain(String tenantDomain) {
+        this.tenantDomain = tenantDomain;
+    }
+
+    public String getAdmin() {
+        return admin;
+    }
+
+    public void setAdmin(String admin) {
+        this.admin = admin;
+    }
+
+    public String getAdminPassword() {
+        return adminPassword;
+    }
+
+    public void setAdminPassword(String adminPassword) {
+        this.adminPassword = adminPassword;
+    }
+
+    public boolean isActive() {
+        return active;
+    }
+
+    public void setActive(boolean active) {
+        this.active = active;
+    }
+
+    public String getSuccessKey() {
+        return successKey;
+    }
+
+    public void setSuccessKey(String successKey) {
+        this.successKey = successKey;
+    }
+
+    public Calendar getCreatedDate() {
+        return createdDate;
+    }
+
+    public void setCreatedDate(Calendar createdDate) {
+        this.createdDate = createdDate;
+    }
+
+    public String getOriginatedService() {
+        return originatedService;
+    }
+
+    public void setOriginatedService(String originatedService) {
+        this.originatedService = originatedService;
+    }
+
+    public String getUsagePlan() {
+        return usagePlan;
+    }
+
+    public void setUsagePlan(String usagePlan) {
+        this.usagePlan = usagePlan;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServiceConfig.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServiceConfig.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServiceConfig.java
new file mode 100644
index 0000000..62c1664
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServiceConfig.java
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+
+import javax.xml.namespace.QName;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public class CloudServiceConfig {
+    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
+
+    private static final String NAME_ATTR_NAME = "name";
+    private static final String DEFAULT_ATTR_NAME = "default";
+    private static final String LABEL_ELEMENT_NAME = "label";
+    private static final String LINK_ELEMENT_NAME = "link";
+    private static final String ICON_ELEMENT_NAME = "icon";
+    private static final String DESCRIPTION_ELEMENT_NAME = "description";
+    private static final String PERMISSIONS_ELEMENT_NAME = "permissions";
+    private static final String PERMISSION_ELEMENT_NAME = "permission";
+    private static final String PRODUCT_PAGE_URL_ELEMENT_NAME = "productPageURL";
+
+    private String name;
+    private String label;
+    private String link;
+    private String icon;
+    private String description;
+    private List<PermissionConfig> permissionConfigs;
+    boolean defaultActive;
+    private String productPageURL;
+
+    public CloudServiceConfig(OMElement configEle) {
+        permissionConfigs = new ArrayList<PermissionConfig>();
+        serialize(configEle);
+    }
+
+    public void serialize(OMElement configEle) {
+        Iterator cloudServiceChildIt = configEle.getChildElements();
+        name = configEle.getAttributeValue(new QName(null, NAME_ATTR_NAME));
+        defaultActive = "true".equals(configEle.
+                getAttributeValue(new QName(null, DEFAULT_ATTR_NAME)));
+        while (cloudServiceChildIt.hasNext()) {
+            Object cloudServiceChildObj = cloudServiceChildIt.next();
+            if (!(cloudServiceChildObj instanceof OMElement)) {
+                continue;
+            }
+            OMElement cloudServiceChildEle = (OMElement) cloudServiceChildObj;
+            if (new QName(CONFIG_NS, LABEL_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                label = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, ICON_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                icon = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, LINK_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                link = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, PRODUCT_PAGE_URL_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                productPageURL = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, DESCRIPTION_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                description = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, PERMISSIONS_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                Iterator permissionChildIt = cloudServiceChildEle.getChildElements();
+                while (permissionChildIt.hasNext()) {
+                    Object permissionChildObj = permissionChildIt.next();
+                    if (!(permissionChildObj instanceof OMElement)) {
+                        continue;
+                    }
+                    OMElement permissionChildEle = (OMElement) permissionChildObj;
+
+                    if (new QName(CONFIG_NS, PERMISSION_ELEMENT_NAME, "").
+                            equals(permissionChildEle.getQName())) {
+                        PermissionConfig permissionConfig =
+                                new PermissionConfig(permissionChildEle);
+                        permissionConfigs.add(permissionConfig);
+                    }
+                }
+            }
+
+        }
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getLabel() {
+        return label;
+    }
+
+    public void setLabel(String label) {
+        this.label = label;
+    }
+
+    public String getLink() {
+        return link;
+    }
+
+    public void setLink(String link) {
+        this.link = link;
+    }
+
+    public String getIcon() {
+        return icon;
+    }
+
+    public void setIcon(String icon) {
+        this.icon = icon;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public List<PermissionConfig> getPermissionConfigs() {
+        return permissionConfigs;
+    }
+
+    public void setPermissionConfigs(List<PermissionConfig> permissionConfigs) {
+        this.permissionConfigs = permissionConfigs;
+    }
+
+    public boolean isDefaultActive() {
+        return defaultActive;
+    }
+
+    public void setDefaultActive(boolean defaultActive) {
+        this.defaultActive = defaultActive;
+    }
+
+    public String getProductPageURL() {
+        return productPageURL;
+    }
+
+    public void setProductPageURL(String productPageURL) {
+        this.productPageURL = productPageURL;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServiceConfigParser.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServiceConfigParser.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServiceConfigParser.java
new file mode 100644
index 0000000..3cedeff
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServiceConfigParser.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.util.CommonUtil;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.io.FileInputStream;
+
+public class CloudServiceConfigParser {
+
+    private static Log log = LogFactory.getLog(CloudServiceConfigParser.class);
+
+    private static class SynchronizingClass {
+    }
+
+    private static final SynchronizingClass loadlock = new SynchronizingClass();
+
+    private static CloudServicesDescConfig cloudServicesDescConfig = null;
+
+    private static final String CONFIG_FILENAME = "cloud-services-desc.xml";
+
+    public static CloudServicesDescConfig loadCloudServicesConfiguration() throws Exception {
+        if (cloudServicesDescConfig != null) {
+            return cloudServicesDescConfig;
+        }
+
+        synchronized (loadlock) {
+            if (cloudServicesDescConfig == null) {
+                try {
+                    String configFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + 
+                            StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator + CONFIG_FILENAME;
+                    OMElement configElement = CommonUtil.buildOMElement(new FileInputStream(configFileName));
+                    cloudServicesDescConfig = new CloudServicesDescConfig(configElement);
+                } catch (Exception e) {
+                    String msg = "Error in building the cloud service configuration.";
+                    log.error(msg, e);
+                    throw new Exception(msg, e);
+                }
+            }
+        }
+        return cloudServicesDescConfig;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServicesDescConfig.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServicesDescConfig.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServicesDescConfig.java
new file mode 100644
index 0000000..1bbd7aa
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/CloudServicesDescConfig.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.xml.namespace.QName;
+import java.util.*;
+
+public class CloudServicesDescConfig {
+    private static final Log log = LogFactory.getLog(CloudServicesDescConfig.class);
+    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
+    private static final String CLOUD_SERVICE_ELEMENT_NAME = "cloudService";
+
+    Map<String, CloudServiceConfig> cloudServiceConfigs;
+
+    public CloudServicesDescConfig(OMElement configEle) {
+        // as the cloud service configs are kept in an order, we use an ordered map.
+        cloudServiceConfigs = new LinkedHashMap<String, CloudServiceConfig>();
+        serialize(configEle);
+    }
+
+    public void serialize(OMElement configEle) {
+        Iterator configChildIt = configEle.getChildElements();
+        while (configChildIt.hasNext()) {
+            Object configChildObj = configChildIt.next();
+            if (!( configChildObj instanceof OMElement)) {
+                continue;
+            }
+            OMElement configChildEle = (OMElement)configChildObj;
+            if (new QName(CONFIG_NS, CLOUD_SERVICE_ELEMENT_NAME, "").
+                    equals(configChildEle.getQName())) {
+                CloudServiceConfig cloudServiceConfig = new CloudServiceConfig(configChildEle);
+                String name = cloudServiceConfig.getName();
+                cloudServiceConfigs.put(name, cloudServiceConfig);
+            }
+        }
+    }
+
+    public Map<String, CloudServiceConfig> getCloudServiceConfigs() {
+        return cloudServiceConfigs;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/PermissionConfig.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/PermissionConfig.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/PermissionConfig.java
new file mode 100644
index 0000000..f4d4716
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/config/PermissionConfig.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+
+import javax.xml.namespace.QName;
+import java.util.Iterator;
+
+public class PermissionConfig {
+    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
+    private static final String PATH = "path";
+    private static final String NAME = "name";
+    String name;
+    String path;
+
+    public PermissionConfig(OMElement configEle) {
+        serialize(configEle);
+    }
+
+    public void serialize(OMElement configEle) {
+
+        Iterator configChildIt = configEle.getChildElements();
+        while (configChildIt.hasNext()) {
+            Object configChildObj = configChildIt.next();
+            if (!( configChildObj instanceof OMElement)) {
+                continue;
+            }
+            OMElement configChildEle = (OMElement)configChildObj;
+            if (new QName(CONFIG_NS, NAME, "").
+                    equals(configChildEle.getQName())) {
+                name = configChildEle.getText();
+            } else if (new QName(CONFIG_NS, PATH, "").
+                    equals(configChildEle.getQName())) {
+                path = configChildEle.getText();
+            }
+        }
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getPath() {
+        return path;
+    }
+
+    public void setPath(String path) {
+        this.path = path;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/StratosConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/StratosConstants.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/StratosConstants.java
new file mode 100644
index 0000000..800206a
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/StratosConstants.java
@@ -0,0 +1,143 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.constants;
+
+
+public class StratosConstants {
+
+    public static final String CLOUD_SERVICE_IS_ACTIVE_PROP_KEY = "active";
+
+    public static final String CLOUD_SERVICE_INFO_STORE_PATH =
+            "/repository/components/org.wso2.stratos/cloud-manager/cloud-services";
+
+    public static final String TENANT_USER_VALIDATION_STORE_PATH =
+            "/repository/components/org.wso2.carbon.validations";
+    public static final String ADMIN_EMAIL_VERIFICATION_FLAG_PATH =
+            "/repository/components/org.wso2.carbon.email-confirmation-flag";
+    public static final String TENANT_DOMAIN_VERIFICATION_FLAG_PATH =
+            "/repository/components/org.wso2.carbon.domain-confirmation-flag";
+
+    public static final String DOMAIN_VALIDATOR_INFO_PATH =
+            "/repository/components/org.wso2.carbon.domain-validator-info";
+
+    public static final String TENANT_CREATION_THEME_PAGE_TOKEN =
+            "/repository/components/org.wso2.carbon.theme-page-token";
+
+    public static final String TENANT_PACKAGE_INFO_PATH =
+            "/repository/components/org.wso2.carbon.package-info";
+
+    public static final String ALL_THEMES_PATH =
+            "/repository/components/org.wso2.carbon.all-themes";
+
+    public static final String THROTTLING_RULES_PATH =
+            "/repository/components/org.wso2.carbon.throttling-rules";
+
+    public static final String ORIGINATED_SERVICE_PATH =
+            "/repository/components/org.wso2.carbon.originated-service";
+
+    public static final String PATH_SEPARATOR = "/";
+
+    public static final String CLOUD_SERVICE_ICONS_STORE_PATH =
+            "/repository/components/org.wso2.carbon.cloud-manager/" +
+                    "cloud-services-icons";
+
+    public static final String VALIDATION_KEY_RESOURCE_NAME = "validation-key";
+    public static final String INCOMING_PATH_DIR = "incoming";
+    public static final String OUTGOING_PATH_DIR = "outgoing";
+    public static final String MULTITENANCY_SCHEDULED_TASK_ID = "multitenancyScheduledTask";
+    public static final String MULTITENANCY_VIEWING_TASK_ID = "multitenancyViewingTask";
+
+    public static final String INVALID_TENANT = "invalidTenant";
+    public static final String INACTIVE_TENANT = "inactiveTenant";
+    public static final String ACTIVE_TENANT = "activeTenant";
+    public static final String IS_EMAIL_VALIDATED = "isEmailValidated";
+    public static final String IS_CREDENTIALS_ALREADY_RESET = "isCredentialsReset";
+    public static final String TENANT_ADMIN = "tenantAdminUsername";
+
+    public static final String CLOUD_MANAGER_SERVICE = "WSO2 Stratos Manager";
+    public static final String CLOUD_IDENTITY_SERVICE = "WSO2 Stratos Identity";
+    public static final String CLOUD_GOVERNANCE_SERVICE = "WSO2 Stratos Governance";
+    public static final String CLOUD_ESB_SERVICE = "WSO2 Stratos Enterprise Service Bus";
+
+    // keystore mgt related Constants
+    public static final String TENANT_KS = "/repository/security/key-stores/";
+    public static final String TENANT_PUB_KEY = "/repository/security/pub-key";
+    public static final String PROP_TENANT_KS_TYPE = "key-store-type";
+    public static final String PROP_TENANT_KS_PASSWD = "key-store-password";
+    public static final String PROP_TENANT_KS_PRIV_KEY_PASSWD = "priv-key-password";
+    public static final String PROP_TENANT_KS_ALIAS = "alias";
+
+    // constants related to redirection
+
+    public static final String UNVERIFIED_ACCOUNT_DOMAIN_SUFFIX = "-unverified";
+    public static final String TENANT_SPECIFIC_URL_RESOLVED = "tenant-sepcific-url-resolved";
+    public static final String SUFFIXED_UNVERIFIED_SESSION_FLAG = "temp-suffixed-unverified";
+
+    // metering constants
+    public static final String THROTTLING_ALL_ACTION = "all_actions";
+    public static final String THROTTLING_IN_DATA_ACTION = "in_data_action"; //this covers registry capacity + registry bandwidth
+    public static final String THROTTLING_OUT_DATA_ACTION = "out_data_action"; //this covers registry bandwidth
+    public static final String THROTTLING_ADD_USER_ACTION = "add_user_action";
+    public static final String THROTTLING_SERVICE_IN_BANDWIDTH_ACTION = "service_in_bandwith_action";
+    public static final String THROTTLING_SERVICE_OUT_BANDWIDTH_ACTION = "service_out_bandwith_action";
+    public static final String THROTTLING_WEBAPP_IN_BANDWIDTH_ACTION = "webapp_in_bandwith_action";
+    public static final String THROTTLING_WEBAPP_OUT_BANDWIDTH_ACTION = "webapp_out_bandwith_action";
+    public static final String THROTTLING_SERVICE_REQUEST_ACTION = "service_request_action";
+    public static final String THROTTLING_SERVICE_RESPONSE_ACTION = "service_response_action";
+
+    // the session attribute to keep track whether the registry action validated
+    // and the usage persisted
+    public static final String REGISTRY_ACTION_VALIDATED_SESSION_ATTR = "registryActionValidated";
+    public static final String REGISTRY_USAGE_PERSISTED_SESSION_ATTR = "usagePersited";
+
+    // Metering servlet attributes
+    public static final String SERVICE_NAME_SERVLET_ATTR = "meteringServiceName";
+    public static final String TENANT_ID_SERVLET_ATTR = "tenantId";
+    public static final String ADMIN_SERVICE_SERVLET_ATTR = "adminService";
+
+    // * as a Service impl related constants
+    public static final String ORIGINATED_SERVICE = "originatedService";
+
+    // Configuration file name
+    public static final String STRATOS_CONF_FILE = "stratos.xml";
+    //public static final String STRATOS_CONF_LOC = "repository/conf/";
+    //public static final String STRATOS_CONF_FILE_WITH_PATH = STRATOS_CONF_LOC + STRATOS_CONF_FILE;
+
+    // EULA location
+    public static final String STRATOS_EULA = "eula.xml";
+
+    // EULA default text.
+    public static final String STRATOS_EULA_DEFAULT_TEXT =
+            "Please refer to: " + StratosConstants.STRATOS_TERMS_OF_USAGE +
+                    " for terms and usage and " + StratosConstants.STRATOS_PRIVACY_POLICY +
+                    " for privacy policy of WSO2 Stratos.";
+
+    // Web location of Terms of Usage and privacy policy
+    public static final String STRATOS_TERMS_OF_USAGE =
+            "http://wso2.com/cloud/services/terms-of-use/";
+    public static final String STRATOS_PRIVACY_POLICY =
+            "http://wso2.com/cloud/services/privacy-policy/";
+    public static final String MULTITENANCY_FREE_PLAN = "Demo";
+    public static final String MULTITENANCY_SMALL_PLAN = "SMB";
+    public static final String MULTITENANCY_MEDIUM_PLAN = "Professional";
+    public static final String MULTITENANCY_LARGE_PLAN = "Enterprise";
+    public static final String EMAIL_CONFIG= "email";
+    public static final String MULTITENANCY_CONFIG_FOLDER = "multitenancy";
+
+}


[38/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologySubscriber.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologySubscriber.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologySubscriber.java
deleted file mode 100644
index 0c127a1..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologySubscriber.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint.subscriber;
-
-import java.util.Properties;
-
-import javax.jms.*;
-import javax.naming.InitialContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.endpoint.util.ConfigHolder;
-import org.apache.stratos.lb.endpoint.util.TopologyConstants;
-
-public class TopologySubscriber {
-
-	private static final Log log = LogFactory.getLog(TopologySubscriber.class);
-	
-    public static void subscribe(String topicName) {
-        Properties initialContextProperties = new Properties();
-        TopicSubscriber topicSubscriber = null;
-        TopicSession topicSession = null;
-        TopicConnection topicConnection = null;
-        InitialContext initialContext = null;
-
-        initialContextProperties.put("java.naming.factory.initial",
-            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");
-
-        String mbServerUrl = null;
-        if (ConfigHolder.getInstance().getLbConfig() != null) {
-            mbServerUrl = ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl();
-        }
-        String connectionString =
-            "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" +
-                (mbServerUrl == null ? TopologyConstants.DEFAULT_MB_SERVER_URL : mbServerUrl) + "'&reconnect='true'";
-        initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);
-
-        try {
-            initialContext = new InitialContext(initialContextProperties);
-            TopicConnectionFactory topicConnectionFactory =
-                (TopicConnectionFactory) initialContext.lookup("qpidConnectionfactory");
-            topicConnection = topicConnectionFactory.createTopicConnection();
-            topicConnection.start();
-            topicSession =
-                topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
-
-            Topic topic = topicSession.createTopic(topicName);
-            topicSubscriber =
-                topicSession.createSubscriber(topic);
-
-            topicSubscriber.setMessageListener(new TopologyListener());
-
-        } catch (Exception e) {
-            log.error(e.getMessage(), e);
-
-            try {
-                if (topicSubscriber != null) {
-                    topicSubscriber.close();
-                }
-
-                if (topicSession != null) {
-                    topicSession.close();
-                }
-
-                if (topicConnection != null) {
-                    topicConnection.close();
-                }
-            } catch (JMSException e1) {
-                // ignore
-            }
-
-        } 
-        finally {
-            // start the health checker
-            Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
-            healthChecker.start();
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/util/ConfigHolder.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/util/ConfigHolder.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/util/ConfigHolder.java
deleted file mode 100644
index 3817579..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/util/ConfigHolder.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.lb.endpoint.util;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.config.SynapseConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
-import org.apache.stratos.lb.endpoint.TenantAwareLoadBalanceEndpointException;
-import org.apache.stratos.lb.endpoint.TenantLoadBalanceMembershipHandler;
-import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
-import org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.user.core.service.RealmService;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-
-/**
- *
- */
-public class ConfigHolder {
-
-    private static ConfigHolder instance;
-    private static final Log log = LogFactory.getLog(ConfigHolder.class);
-
-    private SynapseConfiguration synapseConfiguration;
-    private ConfigurationContext configCtxt;
-    private AxisConfiguration axisConfiguration;
-    private UserRegistry configRegistry;
-    private UserRegistry governanceRegistry;
-    private DependencyManagementService dependencyManager;
-    private TenantLoadBalanceMembershipHandler tenantMembershipHandler;
-    private LoadBalancerConfigurationService lbConfigService;
-    private BlockingQueue<String> sharedTopologyQueue = new LinkedBlockingQueue<String>();
-    private String previousMsg;
-    
-
-    private Map<Integer, SynapseEnvironmentService> synapseEnvironmentServices =
-            new HashMap<Integer, SynapseEnvironmentService>();
-
-    public RealmService getRealmService() {
-        return realmService;
-    }
-
-    public void setRealmService(RealmService realmService) {
-        this.realmService = realmService;
-    }
-
-    private RealmService realmService;
-
-    private ConfigHolder() {
-    }
-
-    public static ConfigHolder getInstance() {
-        if (instance == null) {
-            instance = new ConfigHolder();
-        }
-        return instance;
-    }
-
-    public SynapseConfiguration getSynapseConfiguration() throws TenantAwareLoadBalanceEndpointException{
-        assertNull("SynapseConfiguration", synapseConfiguration);
-        return synapseConfiguration;
-    }
-
-    public void setSynapseConfiguration(SynapseConfiguration synapseConfiguration) {
-        this.synapseConfiguration = synapseConfiguration;
-    }
-
-    public AxisConfiguration getAxisConfiguration() throws TenantAwareLoadBalanceEndpointException {
-        assertNull("AxisConfiguration", axisConfiguration);
-        return axisConfiguration;
-    }
-
-    public void setAxisConfiguration(AxisConfiguration axisConfiguration) {
-        this.axisConfiguration = axisConfiguration;
-    }
-
-    public UserRegistry getConfigRegistry() throws TenantAwareLoadBalanceEndpointException {
-        assertNull("Registry", configRegistry);
-        return configRegistry;
-    }
-
-    public void setConfigRegistry(UserRegistry configRegistry) {
-        this.configRegistry = configRegistry;
-    }
-
-    public DependencyManagementService getDependencyManager() {
-        return dependencyManager;
-    }
-
-    public void setDependencyManager(DependencyManagementService dependencyManager) {
-        this.dependencyManager = dependencyManager;
-    }
-
-    private void assertNull(String name, Object object) throws TenantAwareLoadBalanceEndpointException {
-        if (object == null) {
-            String message = name + " reference in the proxy admin config holder is null";
-            log.error(message);
-            throw new TenantAwareLoadBalanceEndpointException(message);
-        }
-    }
-
-    public UserRegistry getGovernanceRegistry() {
-        return governanceRegistry;
-    }
-
-    public void setGovernanceRegistry(UserRegistry governanceRegistry) {
-        this.governanceRegistry = governanceRegistry;
-    }
-
-    public SynapseEnvironmentService getSynapseEnvironmentService(int id) {
-        return synapseEnvironmentServices.get(id);
-    }
-
-    public void addSynapseEnvironmentService(int id,
-                                             SynapseEnvironmentService synapseEnvironmentService) {
-        synapseEnvironmentServices.put(id, synapseEnvironmentService);
-    }
-
-    public void removeSynapseEnvironmentService(int id) {
-        synapseEnvironmentServices.remove(id);
-    }
-
-    public Map<Integer, SynapseEnvironmentService> getSynapseEnvironmentServices() {
-        return synapseEnvironmentServices;
-    }
-    
-    public void setTenantLoadBalanceMembershipHandler(TenantLoadBalanceMembershipHandler handler) {
-        tenantMembershipHandler = handler;
-    }
-    
-    public TenantLoadBalanceMembershipHandler getTenantLoadBalanceMembershipHandler() {
-        return tenantMembershipHandler;
-    }
-
-    public ConfigurationContext getConfigCtxt() {
-        return configCtxt;
-    }
-
-    public void setConfigCtxt(ConfigurationContext configCtxt) {
-        this.configCtxt = configCtxt;
-    }
-    
-    public void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
-        this.lbConfigService = lbConfigSer;
-    }
-
-    public LoadBalancerConfiguration getLbConfig() {
-        return (LoadBalancerConfiguration) lbConfigService.getLoadBalancerConfig();
-    }
-
-	public BlockingQueue<String> getSharedTopologyDiffQueue() {
-	    return sharedTopologyQueue;
-    }
-
-	public void setSharedTopologyDiffQueue(BlockingQueue<String> sharedTopologyDiffQueue) {
-	    this.sharedTopologyQueue = sharedTopologyDiffQueue;
-    }
-
-	public String getPreviousMsg() {
-	    return previousMsg;
-    }
-
-	public void setPreviousMsg(String previousMsg) {
-	    this.previousMsg = previousMsg;
-    }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/util/TopologyConstants.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/util/TopologyConstants.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/util/TopologyConstants.java
deleted file mode 100644
index 970e4b9..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/util/TopologyConstants.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint.util;
-
-public class TopologyConstants {
-    
-    public static final String TOPIC_NAME = "cloud-controller-topology";
-    public static final String MB_SERVER_URL = "mb.server.ip";
-    public static final String DEFAULT_MB_SERVER_URL = "localhost:5672";
-    
-    public static final String TOPOLOGY_SYNC_CRON = "1 * * * * ? *";
-	public static final String TOPOLOGY_SYNC_TASK_NAME = "TopologySubscriberTaskOfADC";
-	public static final String TOPOLOGY_SYNC_TASK_TYPE = "TOPOLOGY_SUBSCRIBER_TASK";
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/2.1.2/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/2.1.2/pom.xml b/components/org.apache.stratos.activation/2.1.2/pom.xml
deleted file mode 100644
index 1723267..0000000
--- a/components/org.apache.stratos.activation/2.1.2/pom.xml
+++ /dev/null
@@ -1,96 +0,0 @@
-<!--
-# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-  -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-    <parent>
-       <groupId>org.apache.stratos</groupId>
-       <artifactId>stratos-components-parent</artifactId>
-       <version>3.0.0-SNAPSHOT</version>
-       <relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.activation</artifactId>
-    <version>2.1.2</version>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Activation</name>
-
-    <build>
-
-        <plugins>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Axis2Module>${project.artifactId}-${project.version}</Axis2Module>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Export-Package>
-                            org.apache.stratos.activation.activation.*,
-                        </Export-Package>
-                        <Import-Package>
-                            org.apache.stratos.common.*,
-                            org.wso2.carbon.registry.core.*;version=1.0.1,
-                            org.wso2.carbon.registry.resource.*,
-                            !javax.xml.namespace,
-                            javax.xml.namespace; version=0.0.0,
-                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
-                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
-                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
-                            *;resolution:=optional
-                        </Import-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.utils</artifactId>
-	    <version>4.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.registry.core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>commons-logging</groupId>
-            <artifactId>commons-logging</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.stratos</groupId>
-            <artifactId>org.apache.stratos.common</artifactId>
-	    <version>2.1.2</version>
-        </dependency>
-    </dependencies>
-
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/internal/ActivationServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/internal/ActivationServiceComponent.java b/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/internal/ActivationServiceComponent.java
deleted file mode 100644
index bcb1901..0000000
--- a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/internal/ActivationServiceComponent.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.activation.activation.internal;
-
-import org.apache.axis2.AxisFault;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.utils.ConfigurationContextService;
-import org.apache.stratos.activation.activation.service.ActivationService;
-import org.apache.stratos.activation.activation.utils.ActivationManager;
-import org.apache.stratos.activation.activation.utils.Util;
-
-/**
- * The Declarative Service Component for the Service Activation Module for Tenants.
- *
- * @scr.component name="org.wso2.carbon.metering" immediate="true"
- * @scr.reference name="registry.service"
- * interface="org.wso2.carbon.registry.core.service.RegistryService"
- * cardinality="1..1" policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
- * @scr.reference name="user.realmservice.default"
- * interface="org.wso2.carbon.user.core.service.RealmService"
- * cardinality="1..1" policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
- * @scr.reference name="config.context.service"
- * interface="org.wso2.carbon.utils.ConfigurationContextService"
- * cardinality="0..1" policy="dynamic"  bind="setConfigurationContextService"
- * unbind="unsetConfigurationContextService"
- */
-@SuppressWarnings({"JavaDoc", "unused"})
-public class ActivationServiceComponent {
-
-    private static final Log log = LogFactory.getLog(ActivationServiceComponent.class);
-
-    private static ServiceRegistration registration = null;
-
-    /**
-     * Activates the Registry Kernel bundle.
-     *
-     * @param context the OSGi component context.
-     */
-    protected void activate(ComponentContext context) {
-        try {
-            ActivationManager.startCacheCleaner();
-            if (registration == null) {
-                registration = context.getBundleContext().registerService(
-                        ActivationService.class.getName(), new ActivationService(), null);
-            }
-            log.debug("******* Stratos Activation bundle is activated ******* ");
-        } catch (Exception e) {
-            log.error("******* Stratos Activation bundle failed activating ****", e);
-        }
-    }
-
-    /**
-     * Deactivates the Registry Kernel bundle.
-     *
-     * @param context the OSGi component context.
-     */
-    protected void deactivate(ComponentContext context) {
-        registration.unregister();
-        registration = null;
-        ActivationManager.stopCacheCleaner();
-        log.debug("******* Stratos Activation bundle is deactivated ******* ");
-    }
-
-    /**
-     * Method to set the registry service used. This will be used when accessing the registry. This
-     * method is called when the OSGi Registry Service is available.
-     *
-     * @param registryService the registry service.
-     */
-    protected void setRegistryService(RegistryService registryService) {
-        Util.setRegistryService(registryService);
-    }
-
-    /**
-     * This method is called when the current registry service becomes un-available.
-     *
-     * @param registryService the current registry service instance, to be used for any
-     *                        cleaning-up.
-     */
-    protected void unsetRegistryService(RegistryService registryService) {
-        Util.setRegistryService(null);
-    }
-
-    /**
-     * Method to set the realm service used. This will be used when accessing the user realm. This
-     * method is called when the OSGi Realm Service is available.
-     *
-     * @param realmService the realm service.
-     */
-    protected void setRealmService(RealmService realmService) {
-        Util.setRealmService(realmService);
-    }
-
-    /**
-     * This method is called when the current realm service becomes un-available.
-     *
-     * @param realmService the current realm service instance, to be used for any cleaning-up.
-     */
-    protected void unsetRealmService(RealmService realmService) {
-        Util.setRealmService(null);
-    }
-
-    /**
-     * Method to set the configuration context service used. This method is called when the OSGi
-     * ConfigurationContext Service is available.
-     *
-     * @param contextService the configuration context service.
-     */
-    protected void setConfigurationContextService(ConfigurationContextService contextService) {
-        try {
-            if (contextService.getServerConfigContext() != null &&
-                    contextService.getServerConfigContext().getAxisConfiguration() != null) {
-                contextService.getServerConfigContext().getAxisConfiguration().engageModule(
-                        "activation");
-            } else {
-                log.error("Failed to engage Activation Module.");
-            }
-        } catch (AxisFault e) {
-            log.error("Failed to engage Activation Module", e);
-        }
-    }
-
-    /**
-     * This method is called when the current configuration context service becomes un-available.
-     *
-     * @param contextService the current configuration context service instance, to be used for any
-     *                       cleaning-up.
-     */
-    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/module/ActivationHandler.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/module/ActivationHandler.java b/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/module/ActivationHandler.java
deleted file mode 100644
index 732d8de..0000000
--- a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/module/ActivationHandler.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.activation.activation.module;
-
-import javax.xml.namespace.QName;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.soap.SOAPBody;
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.context.MessageContext;
-import org.apache.axis2.description.AxisService;
-import org.apache.axis2.engine.Handler;
-import org.apache.axis2.handlers.AbstractHandler;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.activation.activation.utils.ActivationManager;
-import org.apache.stratos.activation.activation.utils.Util;
-import org.wso2.carbon.context.PrivilegedCarbonContext;
-import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
-import org.apache.stratos.common.util.CloudServicesUtil;
-import org.wso2.carbon.utils.ServerConstants;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
-
-public class ActivationHandler extends AbstractHandler implements Handler {
-
-    private static final Log log = LogFactory.getLog(ActivationHandler.class);
-
-    private String name = "ActivationHandler";
-
-    /**
-     * {@inheritDoc}
-     */
-    public InvocationResponse invoke(MessageContext messageContext) throws AxisFault {
-        String serviceName = Util.getServiceName();
-        //TODO - tenant id and domain should retrieve from thread local carbon context
-        //If service is api manager then we will pass activation handler check
-        if(serviceName.equalsIgnoreCase("WSO2 API Manager")) {
-            return InvocationResponse.CONTINUE;
-        }
-        if(log.isDebugEnabled()){
-            log.debug("Starting Activation Handler invocation. Incoming Message: " +
-                    messageContext.getEnvelope().toString());
-        }
-
-        AxisService service = messageContext.getAxisService();
-        int tenantId = getTenantId(messageContext);
-        if (service != null && "ActivationService".equals(service.getName())) {
-            log.debug("Granted access to the Activation Service");
-            if (tenantId > 0) {
-                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
-                        messageContext.getConfigurationContext());
-                log.debug("Loaded Tenant Configuration");
-            }
-            return InvocationResponse.CONTINUE;
-        }
-        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
-            log.debug("Granted access for super tenant");
-            return InvocationResponse.CONTINUE;
-        }
-        if (ActivationManager.activationRecorded(tenantId)) {
-            if (ActivationManager.getActivation(tenantId)) {
-                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
-                        messageContext.getConfigurationContext());
-                log.debug("Loaded Tenant Configuration");
-                return InvocationResponse.CONTINUE;
-            } else {
-                if (log.isWarnEnabled()) {
-                    log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
-                }
-                return InvocationResponse.ABORT;
-            }
-        }
-
-        try {
-            if (CloudServicesUtil.isCloudServiceActive(serviceName, tenantId)) {
-                log.debug("Successful attempt to access " + serviceName + " by tenant " + tenantId);
-                ActivationManager.setActivation(tenantId, true);
-                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
-                        messageContext.getConfigurationContext());
-                log.debug("Loaded Tenant Configuration");
-                return InvocationResponse.CONTINUE;
-            }
-        } catch (Exception e) {
-            throw new AxisFault("Failed to determine Activation status.", e);
-        }
-        log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
-        ActivationManager.setActivation(tenantId, false);
-        return InvocationResponse.ABORT;
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    public String getName() {
-        return name;
-    }
-
-    /**
-     * Method to set the name of the activation handler.
-     *
-     * @param name the name.
-     */
-    @SuppressWarnings("unused")
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    private String getTenantDomain(MessageContext messageContext) {
-        //Ideally this should take from thread local carbon context change this temporary
-        return PrivilegedCarbonContext.getCurrentContext(messageContext).getTenantDomain();
-    }
-
-    private int getTenantId(MessageContext messageContext) {
-        //Ideally this should take from thread local carbon context change this temporary
-        PrivilegedCarbonContext carbonContext =
-                PrivilegedCarbonContext.getCurrentContext(messageContext);
-        int tenantId = carbonContext.getTenantId();
-        if (tenantId > -1 || tenantId == MultitenantConstants.SUPER_TENANT_ID) {
-            return tenantId;
-        }
-        String domain = carbonContext.getTenantDomain();
-        if (domain == null) {
-            SOAPBody soapBody = messageContext.getEnvelope().getBody();
-            if (soapBody != null && soapBody.getFirstElement() != null) {
-                OMElement usernameElem = soapBody.getFirstElement().getFirstChildWithName(
-                        new QName(ServerConstants.AUTHENTICATION_SERVICE_NS,
-                                ServerConstants.AUTHENTICATION_SERVICE_USERNAME));
-                if (usernameElem != null) {
-                    String userName = usernameElem.getText();
-                    domain = MultitenantUtils.getTenantDomain(userName);
-                }
-            }
-        }
-        if (domain != null) {
-            try {
-                tenantId = Util.getRealmService().getTenantManager().getTenantId(domain);
-            } catch (org.wso2.carbon.user.api.UserStoreException e) {
-                log.error("An error occurred while obtaining the tenant id.", e);
-            }
-        }
-        return tenantId;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/module/ActivationModule.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/module/ActivationModule.java b/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/module/ActivationModule.java
deleted file mode 100644
index e76d0ea..0000000
--- a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/module/ActivationModule.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.activation.activation.module;
-
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.description.AxisDescription;
-import org.apache.axis2.description.AxisModule;
-import org.apache.axis2.modules.Module;
-import org.apache.neethi.Assertion;
-import org.apache.neethi.Policy;
-
-/**
- * Module used to engage the activation handler.
- */
-public class ActivationModule implements Module {
-
-    /**
-     * {@inheritDoc}
-     */
-    public void init(ConfigurationContext configurationContext, AxisModule axisModule)
-            throws AxisFault {
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    public void engageNotify(AxisDescription axisDescription) throws AxisFault {
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    public boolean canSupportAssertion(Assertion assertion) {
-        return true;
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    public void applyPolicy(Policy policy, AxisDescription axisDescription) throws AxisFault {
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    public void shutdown(ConfigurationContext configurationContext) throws AxisFault {
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/service/ActivationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/service/ActivationService.java b/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/service/ActivationService.java
deleted file mode 100644
index e993703..0000000
--- a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/service/ActivationService.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.activation.activation.service;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.activation.activation.utils.ActivationManager;
-import org.apache.stratos.activation.activation.utils.Util;
-import org.apache.stratos.common.config.CloudServiceConfigParser;
-import org.apache.stratos.common.config.CloudServicesDescConfig;
-import org.apache.stratos.common.util.CloudServicesUtil;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-/**
- * Admin Service to handle activation of cloud services used by tenants.
- */
-public class ActivationService {
-
-    private static final Log log = LogFactory.getLog(ActivationService.class);
-
-    /**
-     * Method to update an activation record.
-     *
-     * @param tenantId the tenant identifier.
-     *
-     * @throws Exception if the operation failed.
-     */
-    public static void updateActivation(int tenantId) throws Exception {
-        if (tenantId != 0) {
-            String serviceName = Util.getServiceName();
-            boolean isActive = CloudServicesUtil.isCloudServiceActive(serviceName, tenantId);
-            CloudServicesDescConfig cloudServicesDesc =
-                                                        CloudServiceConfigParser.loadCloudServicesConfiguration();
-            CloudServicesUtil.setCloudServiceActive(!isActive,
-                                                    serviceName,
-                                                    tenantId,
-                                                    cloudServicesDesc.getCloudServiceConfigs()
-                                                                     .get(serviceName));
-            ActivationManager.setActivation(tenantId, !isActive);
-        }
-    }
-
-    /**
-     * Method to determine whether a service is active for the given tenant.
-     *
-     * @param tenantId tenantId the tenant identifier.
-     *
-     * @return whether the service is active.
-     * @throws Exception if the operation failed.
-     */
-    public boolean isActive(int tenantId) throws Exception {
-        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
-            return true;
-        }
-        if (ActivationManager.activationRecorded(tenantId)) {
-            return ActivationManager.getActivation(tenantId);
-        }
-        String serviceName = Util.getServiceName();
-        if (CloudServicesUtil.isCloudServiceActive(serviceName, tenantId)) {
-            log.debug("Successful attempt to access " + serviceName + " by tenant " + tenantId);
-            ActivationManager.setActivation(tenantId, true);
-            return true;
-        }
-        log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
-        ActivationManager.setActivation(tenantId, false);
-        return false;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/utils/ActivationManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/utils/ActivationManager.java b/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/utils/ActivationManager.java
deleted file mode 100644
index 91a0ad9..0000000
--- a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/utils/ActivationManager.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.activation.activation.utils;
-
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * Manages Activations of Services for Tenants.
- */
-public class ActivationManager {
-
-    private static final ConcurrentHashMap<Integer, Boolean> activations =
-            new ConcurrentHashMap<Integer, Boolean>();
-    private static Timer timer = null;
-
-    /**
-     * Starts cleaning up cached activation records at periodic intervals.
-     */
-    public static void startCacheCleaner() {
-        TimerTask faultyServiceRectifier = new CacheCleaner();
-        timer = new Timer();
-        // Retry in 1 minute
-        long retryIn = 1000 * 60;
-        timer.schedule(faultyServiceRectifier, 0, retryIn);
-    }
-
-    /**
-     * Stops cleaning up cached activation records.
-     */
-    public static void stopCacheCleaner() {
-        timer.cancel();
-        timer = null;
-    }
-
-    /**
-     * Method to set an activation record.
-     *
-     * @param tenantId the tenant identifier.
-     * @param status   true if the service is active or false if not.
-     */
-    public static void setActivation(int tenantId, boolean status) {
-        ActivationManager.activations.put(tenantId, status);
-    }
-
-    /**
-     * Method to check whether an activation record exists for the given tenant.
-     *
-     * @param tenantId the tenant identifier.
-     *
-     * @return true if a record exists.
-     */
-    public static boolean activationRecorded(int tenantId) {
-        return ActivationManager.activations.get(tenantId) != null;
-    }
-
-    /**
-     * Method to retrieve an activation record.
-     *
-     * @param tenantId the tenant identifier.
-     *
-     * @return true if the service is active or false if not.
-     */
-    public static boolean getActivation(int tenantId) {
-        return ActivationManager.activations.get(tenantId) != null &&
-                ActivationManager.activations.get(tenantId);
-    }
-
-    private static class CacheCleaner extends TimerTask {
-
-        /**
-         * {@inheritDoc}
-         */
-        public void run() {
-            ActivationManager.activations.clear();
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/utils/Util.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/utils/Util.java b/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/utils/Util.java
deleted file mode 100644
index 98bb716..0000000
--- a/components/org.apache.stratos.activation/2.1.2/src/main/java/org/apache/stratos/activation/activation/utils/Util.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.activation.activation.utils;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.base.ServerConfiguration;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.user.core.service.RealmService;
-
-/**
- * Utilities for the Service Activation Module for Tenants.
- */
-public class Util {
-
-    private static RegistryService registryService = null;
-    private static RealmService realmService = null;
-    private static String serviceName = null;
-    private static final Log log = LogFactory.getLog(Util.class);
-
-    private static boolean cloudServiceInfoPathSanityChecked = false;
-
-    /**
-     * Stores an instance of the Registry Service that can be used to access the registry.
-     *
-     * @param service the Registry Service instance.
-     */
-    public static synchronized void setRegistryService(RegistryService service) {
-        if (registryService == null) {
-            registryService = service;
-        }
-    }
-
-    /**
-     * Method to retrieve the Registry Service instance.
-     *
-     * @return the Registry Service instance if it has been stored or null if not.
-     */
-    @SuppressWarnings("unused")
-    public static RegistryService getRegistryService() {
-        return registryService;
-    }
-
-    /**
-     * Stores an instance of the Realm Service that can be used to access the user realm.
-     *
-     * @param service the Realm Service instance.
-     */
-    public static synchronized void setRealmService(RealmService service) {
-        if (realmService == null) {
-            realmService = service;
-        }
-    }
-
-    /**
-     * Method to retrieve the Realm Service instance.
-     *
-     * @return the Realm Service instance if it has been stored or null if not.
-     */
-    public static RealmService getRealmService() {
-        return realmService;
-    }
-
-    private static UserRegistry getSuperTenantGovernanceSystemRegistry() throws RegistryException {
-        return registryService.getGovernanceSystemRegistry();
-    }
-
-//    /**
-//     * Method to determine whether the given cloud service is active.
-//     *
-//     * @param cloudServiceName the name of the cloud service.
-//     * @param tenantId         the tenant identifier.
-//     * @param systemRegistry   the super tenant's governance system registry
-//     *
-//     * @return true if the service is active or false if not.
-//     * @throws Exception if the operation failed.
-//     */
-//    public static boolean isCloudServiceActive(String cloudServiceName,
-//                                               int tenantId, UserRegistry systemRegistry)
-//            throws Exception {
-//        // The cloud manager is always active
-//        if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
-//            return true;
-//        }
-//
-//        if(!cloudServiceInfoPathSanityChecked) {
-//            if(!systemRegistry.resourceExists(StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH)) {
-//                throw new RuntimeException("Cloud services list resource " +
-//                                           StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH + " does not exist");
-//            }
-//            cloudServiceInfoPathSanityChecked = true;
-//        }
-//
-//        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
-//                RegistryConstants.PATH_SEPARATOR + tenantId +
-//                RegistryConstants.PATH_SEPARATOR + cloudServiceName;
-//        Resource cloudServiceInfoResource;
-//        if (systemRegistry.resourceExists(cloudServiceInfoPath)) {
-//            cloudServiceInfoResource = systemRegistry.get(cloudServiceInfoPath);
-//            String isActiveStr =
-//                cloudServiceInfoResource.getProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
-//            return Boolean.toString(true).equals(isActiveStr);
-//        }
-//        return false;
-//    }
-//
-
-    /**
-     * Method to obtain the name of the cloud service in which this module is running.
-     *
-     * @return the name of the service as defined in the server configuration.
-     */
-    public static String getServiceName() {
-        if (serviceName == null) {
-            serviceName = ServerConfiguration.getInstance().getFirstProperty("Name");
-        }
-        return serviceName;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/2.1.2/src/main/resources/META-INF/module.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/2.1.2/src/main/resources/META-INF/module.xml b/components/org.apache.stratos.activation/2.1.2/src/main/resources/META-INF/module.xml
deleted file mode 100644
index 220e0e5..0000000
--- a/components/org.apache.stratos.activation/2.1.2/src/main/resources/META-INF/module.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<!--
- ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- ~
- ~ WSO2 Inc. licenses this file to you under the Apache License,
- ~ Version 2.0 (the "License"); you may not use this file except
- ~ in compliance with the License.
- ~ You may obtain a copy of the License at
- ~
- ~    http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing,
- ~ software distributed under the License is distributed on an
- ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- ~ KIND, either express or implied.  See the License for the
- ~ specific language governing permissions and limitations
- ~ under the License.
- -->
-<module name="activation" class="org.apache.stratos.activation.activation.module.ActivationModule">
-   <InFlow>
-        <handler name="InFlowActivationHandler"
-                 class="org.apache.stratos.activation.activation.module.ActivationHandler">
-        <order phase="Validation" phaseFirst="true"/>
-        </handler>
-   </InFlow>
-
-   <InFaultFlow>
-        <handler name="FaultInFlowActivationHandler"
-                 class="org.apache.stratos.activation.activation.module.ActivationHandler">
-        <order phase="Validation" phaseFirst="true"/>
-        </handler>
-   </InFaultFlow>
-  <parameter name="adminModule" locked="true">true</parameter>
-</module>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/2.1.2/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/2.1.2/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.activation/2.1.2/src/main/resources/META-INF/services.xml
deleted file mode 100644
index 01c4d91..0000000
--- a/components/org.apache.stratos.activation/2.1.2/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- !
- ! Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- !
- ! WSO2 Inc. licenses this file to you under the Apache License,
- ! Version 2.0 (the "License"); you may not use this file except
- ! in compliance with the License.
- ! You may obtain a copy of the License at
- !
- ! http://www.apache.org/licenses/LICENSE-2.0
- !
- ! Unless required by applicable law or agreed to in writing,
- ! software distributed under the License is distributed on an
- ! "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- ! KIND, either express or implied.  See the License for the
- ! specific language governing permissions and limitations
- ! under the License.
- !-->
-<serviceGroup>
-    <service name="ActivationService" scope="transportsession">
-        <transports>
-            <transport>https</transport>
-        </transports>
-        <parameter name="ServiceClass" locked="false">
-            org.apache.stratos.activation.activation.service.ActivationService
-        </parameter>
-    </service>
-    <parameter name="hiddenService" locked="true">true</parameter>
-</serviceGroup>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/pom.xml b/components/org.apache.stratos.activation/pom.xml
new file mode 100644
index 0000000..81e69ac
--- /dev/null
+++ b/components/org.apache.stratos.activation/pom.xml
@@ -0,0 +1,94 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+       <groupId>org.apache.stratos</groupId>
+       <artifactId>stratos-components-parent</artifactId>
+       <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.activation</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Activation</name>
+
+    <build>
+
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Axis2Module>${project.artifactId}-${project.version}</Axis2Module>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.apache.stratos.activation.activation.*,
+                        </Export-Package>
+                        <Import-Package>
+                            org.apache.stratos.common.*,
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.registry.resource.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+	    <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+	    <version>${apache.stratos.version}</version>
+        </dependency>
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/internal/ActivationServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/internal/ActivationServiceComponent.java b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/internal/ActivationServiceComponent.java
new file mode 100644
index 0000000..bcb1901
--- /dev/null
+++ b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/internal/ActivationServiceComponent.java
@@ -0,0 +1,152 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.activation.activation.internal;
+
+import org.apache.axis2.AxisFault;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+import org.apache.stratos.activation.activation.service.ActivationService;
+import org.apache.stratos.activation.activation.utils.ActivationManager;
+import org.apache.stratos.activation.activation.utils.Util;
+
+/**
+ * The Declarative Service Component for the Service Activation Module for Tenants.
+ *
+ * @scr.component name="org.wso2.carbon.metering" immediate="true"
+ * @scr.reference name="registry.service"
+ * interface="org.wso2.carbon.registry.core.service.RegistryService"
+ * cardinality="1..1" policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
+ * @scr.reference name="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
+ * @scr.reference name="config.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService"
+ * cardinality="0..1" policy="dynamic"  bind="setConfigurationContextService"
+ * unbind="unsetConfigurationContextService"
+ */
+@SuppressWarnings({"JavaDoc", "unused"})
+public class ActivationServiceComponent {
+
+    private static final Log log = LogFactory.getLog(ActivationServiceComponent.class);
+
+    private static ServiceRegistration registration = null;
+
+    /**
+     * Activates the Registry Kernel bundle.
+     *
+     * @param context the OSGi component context.
+     */
+    protected void activate(ComponentContext context) {
+        try {
+            ActivationManager.startCacheCleaner();
+            if (registration == null) {
+                registration = context.getBundleContext().registerService(
+                        ActivationService.class.getName(), new ActivationService(), null);
+            }
+            log.debug("******* Stratos Activation bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("******* Stratos Activation bundle failed activating ****", e);
+        }
+    }
+
+    /**
+     * Deactivates the Registry Kernel bundle.
+     *
+     * @param context the OSGi component context.
+     */
+    protected void deactivate(ComponentContext context) {
+        registration.unregister();
+        registration = null;
+        ActivationManager.stopCacheCleaner();
+        log.debug("******* Stratos Activation bundle is deactivated ******* ");
+    }
+
+    /**
+     * Method to set the registry service used. This will be used when accessing the registry. This
+     * method is called when the OSGi Registry Service is available.
+     *
+     * @param registryService the registry service.
+     */
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    /**
+     * This method is called when the current registry service becomes un-available.
+     *
+     * @param registryService the current registry service instance, to be used for any
+     *                        cleaning-up.
+     */
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    /**
+     * Method to set the realm service used. This will be used when accessing the user realm. This
+     * method is called when the OSGi Realm Service is available.
+     *
+     * @param realmService the realm service.
+     */
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    /**
+     * This method is called when the current realm service becomes un-available.
+     *
+     * @param realmService the current realm service instance, to be used for any cleaning-up.
+     */
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    /**
+     * Method to set the configuration context service used. This method is called when the OSGi
+     * ConfigurationContext Service is available.
+     *
+     * @param contextService the configuration context service.
+     */
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        try {
+            if (contextService.getServerConfigContext() != null &&
+                    contextService.getServerConfigContext().getAxisConfiguration() != null) {
+                contextService.getServerConfigContext().getAxisConfiguration().engageModule(
+                        "activation");
+            } else {
+                log.error("Failed to engage Activation Module.");
+            }
+        } catch (AxisFault e) {
+            log.error("Failed to engage Activation Module", e);
+        }
+    }
+
+    /**
+     * This method is called when the current configuration context service becomes un-available.
+     *
+     * @param contextService the current configuration context service instance, to be used for any
+     *                       cleaning-up.
+     */
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/module/ActivationHandler.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/module/ActivationHandler.java b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/module/ActivationHandler.java
new file mode 100644
index 0000000..732d8de
--- /dev/null
+++ b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/module/ActivationHandler.java
@@ -0,0 +1,161 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.activation.activation.module;
+
+import javax.xml.namespace.QName;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.soap.SOAPBody;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.engine.Handler;
+import org.apache.axis2.handlers.AbstractHandler;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.activation.activation.utils.ActivationManager;
+import org.apache.stratos.activation.activation.utils.Util;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
+import org.apache.stratos.common.util.CloudServicesUtil;
+import org.wso2.carbon.utils.ServerConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+public class ActivationHandler extends AbstractHandler implements Handler {
+
+    private static final Log log = LogFactory.getLog(ActivationHandler.class);
+
+    private String name = "ActivationHandler";
+
+    /**
+     * {@inheritDoc}
+     */
+    public InvocationResponse invoke(MessageContext messageContext) throws AxisFault {
+        String serviceName = Util.getServiceName();
+        //TODO - tenant id and domain should retrieve from thread local carbon context
+        //If service is api manager then we will pass activation handler check
+        if(serviceName.equalsIgnoreCase("WSO2 API Manager")) {
+            return InvocationResponse.CONTINUE;
+        }
+        if(log.isDebugEnabled()){
+            log.debug("Starting Activation Handler invocation. Incoming Message: " +
+                    messageContext.getEnvelope().toString());
+        }
+
+        AxisService service = messageContext.getAxisService();
+        int tenantId = getTenantId(messageContext);
+        if (service != null && "ActivationService".equals(service.getName())) {
+            log.debug("Granted access to the Activation Service");
+            if (tenantId > 0) {
+                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
+                        messageContext.getConfigurationContext());
+                log.debug("Loaded Tenant Configuration");
+            }
+            return InvocationResponse.CONTINUE;
+        }
+        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            log.debug("Granted access for super tenant");
+            return InvocationResponse.CONTINUE;
+        }
+        if (ActivationManager.activationRecorded(tenantId)) {
+            if (ActivationManager.getActivation(tenantId)) {
+                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
+                        messageContext.getConfigurationContext());
+                log.debug("Loaded Tenant Configuration");
+                return InvocationResponse.CONTINUE;
+            } else {
+                if (log.isWarnEnabled()) {
+                    log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
+                }
+                return InvocationResponse.ABORT;
+            }
+        }
+
+        try {
+            if (CloudServicesUtil.isCloudServiceActive(serviceName, tenantId)) {
+                log.debug("Successful attempt to access " + serviceName + " by tenant " + tenantId);
+                ActivationManager.setActivation(tenantId, true);
+                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
+                        messageContext.getConfigurationContext());
+                log.debug("Loaded Tenant Configuration");
+                return InvocationResponse.CONTINUE;
+            }
+        } catch (Exception e) {
+            throw new AxisFault("Failed to determine Activation status.", e);
+        }
+        log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
+        ActivationManager.setActivation(tenantId, false);
+        return InvocationResponse.ABORT;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * Method to set the name of the activation handler.
+     *
+     * @param name the name.
+     */
+    @SuppressWarnings("unused")
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    private String getTenantDomain(MessageContext messageContext) {
+        //Ideally this should take from thread local carbon context change this temporary
+        return PrivilegedCarbonContext.getCurrentContext(messageContext).getTenantDomain();
+    }
+
+    private int getTenantId(MessageContext messageContext) {
+        //Ideally this should take from thread local carbon context change this temporary
+        PrivilegedCarbonContext carbonContext =
+                PrivilegedCarbonContext.getCurrentContext(messageContext);
+        int tenantId = carbonContext.getTenantId();
+        if (tenantId > -1 || tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            return tenantId;
+        }
+        String domain = carbonContext.getTenantDomain();
+        if (domain == null) {
+            SOAPBody soapBody = messageContext.getEnvelope().getBody();
+            if (soapBody != null && soapBody.getFirstElement() != null) {
+                OMElement usernameElem = soapBody.getFirstElement().getFirstChildWithName(
+                        new QName(ServerConstants.AUTHENTICATION_SERVICE_NS,
+                                ServerConstants.AUTHENTICATION_SERVICE_USERNAME));
+                if (usernameElem != null) {
+                    String userName = usernameElem.getText();
+                    domain = MultitenantUtils.getTenantDomain(userName);
+                }
+            }
+        }
+        if (domain != null) {
+            try {
+                tenantId = Util.getRealmService().getTenantManager().getTenantId(domain);
+            } catch (org.wso2.carbon.user.api.UserStoreException e) {
+                log.error("An error occurred while obtaining the tenant id.", e);
+            }
+        }
+        return tenantId;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/module/ActivationModule.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/module/ActivationModule.java b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/module/ActivationModule.java
new file mode 100644
index 0000000..e76d0ea
--- /dev/null
+++ b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/module/ActivationModule.java
@@ -0,0 +1,65 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.activation.activation.module;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.AxisDescription;
+import org.apache.axis2.description.AxisModule;
+import org.apache.axis2.modules.Module;
+import org.apache.neethi.Assertion;
+import org.apache.neethi.Policy;
+
+/**
+ * Module used to engage the activation handler.
+ */
+public class ActivationModule implements Module {
+
+    /**
+     * {@inheritDoc}
+     */
+    public void init(ConfigurationContext configurationContext, AxisModule axisModule)
+            throws AxisFault {
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void engageNotify(AxisDescription axisDescription) throws AxisFault {
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public boolean canSupportAssertion(Assertion assertion) {
+        return true;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void applyPolicy(Policy policy, AxisDescription axisDescription) throws AxisFault {
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void shutdown(ConfigurationContext configurationContext) throws AxisFault {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/service/ActivationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/service/ActivationService.java b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/service/ActivationService.java
new file mode 100644
index 0000000..e993703
--- /dev/null
+++ b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/service/ActivationService.java
@@ -0,0 +1,85 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.activation.activation.service;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.activation.activation.utils.ActivationManager;
+import org.apache.stratos.activation.activation.utils.Util;
+import org.apache.stratos.common.config.CloudServiceConfigParser;
+import org.apache.stratos.common.config.CloudServicesDescConfig;
+import org.apache.stratos.common.util.CloudServicesUtil;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+/**
+ * Admin Service to handle activation of cloud services used by tenants.
+ */
+public class ActivationService {
+
+    private static final Log log = LogFactory.getLog(ActivationService.class);
+
+    /**
+     * Method to update an activation record.
+     *
+     * @param tenantId the tenant identifier.
+     *
+     * @throws Exception if the operation failed.
+     */
+    public static void updateActivation(int tenantId) throws Exception {
+        if (tenantId != 0) {
+            String serviceName = Util.getServiceName();
+            boolean isActive = CloudServicesUtil.isCloudServiceActive(serviceName, tenantId);
+            CloudServicesDescConfig cloudServicesDesc =
+                                                        CloudServiceConfigParser.loadCloudServicesConfiguration();
+            CloudServicesUtil.setCloudServiceActive(!isActive,
+                                                    serviceName,
+                                                    tenantId,
+                                                    cloudServicesDesc.getCloudServiceConfigs()
+                                                                     .get(serviceName));
+            ActivationManager.setActivation(tenantId, !isActive);
+        }
+    }
+
+    /**
+     * Method to determine whether a service is active for the given tenant.
+     *
+     * @param tenantId tenantId the tenant identifier.
+     *
+     * @return whether the service is active.
+     * @throws Exception if the operation failed.
+     */
+    public boolean isActive(int tenantId) throws Exception {
+        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            return true;
+        }
+        if (ActivationManager.activationRecorded(tenantId)) {
+            return ActivationManager.getActivation(tenantId);
+        }
+        String serviceName = Util.getServiceName();
+        if (CloudServicesUtil.isCloudServiceActive(serviceName, tenantId)) {
+            log.debug("Successful attempt to access " + serviceName + " by tenant " + tenantId);
+            ActivationManager.setActivation(tenantId, true);
+            return true;
+        }
+        log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
+        ActivationManager.setActivation(tenantId, false);
+        return false;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/utils/ActivationManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/utils/ActivationManager.java b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/utils/ActivationManager.java
new file mode 100644
index 0000000..91a0ad9
--- /dev/null
+++ b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/utils/ActivationManager.java
@@ -0,0 +1,96 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.activation.activation.utils;
+
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Manages Activations of Services for Tenants.
+ */
+public class ActivationManager {
+
+    private static final ConcurrentHashMap<Integer, Boolean> activations =
+            new ConcurrentHashMap<Integer, Boolean>();
+    private static Timer timer = null;
+
+    /**
+     * Starts cleaning up cached activation records at periodic intervals.
+     */
+    public static void startCacheCleaner() {
+        TimerTask faultyServiceRectifier = new CacheCleaner();
+        timer = new Timer();
+        // Retry in 1 minute
+        long retryIn = 1000 * 60;
+        timer.schedule(faultyServiceRectifier, 0, retryIn);
+    }
+
+    /**
+     * Stops cleaning up cached activation records.
+     */
+    public static void stopCacheCleaner() {
+        timer.cancel();
+        timer = null;
+    }
+
+    /**
+     * Method to set an activation record.
+     *
+     * @param tenantId the tenant identifier.
+     * @param status   true if the service is active or false if not.
+     */
+    public static void setActivation(int tenantId, boolean status) {
+        ActivationManager.activations.put(tenantId, status);
+    }
+
+    /**
+     * Method to check whether an activation record exists for the given tenant.
+     *
+     * @param tenantId the tenant identifier.
+     *
+     * @return true if a record exists.
+     */
+    public static boolean activationRecorded(int tenantId) {
+        return ActivationManager.activations.get(tenantId) != null;
+    }
+
+    /**
+     * Method to retrieve an activation record.
+     *
+     * @param tenantId the tenant identifier.
+     *
+     * @return true if the service is active or false if not.
+     */
+    public static boolean getActivation(int tenantId) {
+        return ActivationManager.activations.get(tenantId) != null &&
+                ActivationManager.activations.get(tenantId);
+    }
+
+    private static class CacheCleaner extends TimerTask {
+
+        /**
+         * {@inheritDoc}
+         */
+        public void run() {
+            ActivationManager.activations.clear();
+        }
+    }
+
+}


[04/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/internal/TenantMgtServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/internal/TenantMgtServiceComponent.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/internal/TenantMgtServiceComponent.java
deleted file mode 100644
index ae8411b..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/internal/TenantMgtServiceComponent.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.tenant.mgt.internal;
-
-import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.stratos.common.TenantBillingService;
-import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
-import org.wso2.carbon.stratos.common.util.CommonUtil;
-import org.wso2.carbon.stratos.common.util.StratosConfiguration;
-import org.apache.stratos.tenant.mgt.internal.util.TenantMgtRampartUtil;
-import org.wso2.carbon.user.api.RealmConfiguration;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.description.AxisService;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.neethi.Policy;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-
-import org.osgi.service.component.ComponentContext;
-
-/**
- * @scr.component name="org.wso2.carbon.tenant.mgt" immediate="true"
- * @scr.reference name="registry.service"
- *                interface="org.wso2.carbon.registry.core.service.RegistryService"
- *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
- *                unbind="unsetRegistryService"
- * @scr.reference name="user.realmservice.default"
- *                interface="org.wso2.carbon.user.core.service.RealmService"
- *                cardinality="1..1" policy="dynamic" bind="setRealmService"
- *                unbind="unsetRealmService"
- * @scr.reference name="configuration.context.service"
- *                interface="org.wso2.carbon.utils.ConfigurationContextService"
- *                cardinality="1..1" policy="dynamic"
- *                bind="setConfigurationContextService"
- *                unbind="unsetConfigurationContextService"
- * @scr.reference name="org.wso2.carbon.tenant.mgt.listener.service"
- *                interface="org.wso2.carbon.stratos.common.listeners.TenantMgtListener"
- *                cardinality="0..n" policy="dynamic"
- *                bind="setTenantMgtListenerService"
- *                unbind="unsetTenantMgtListenerService"
- * @scr.reference name="default.tenant.billing.service"
- *                interface="org.wso2.carbon.stratos.common.TenantBillingService"
- *                cardinality="0..1" policy="dynamic"
- *                bind="setTenantBillingService"
- *                unbind="unsetTenantBillingService"
- * @scr.reference name="default.tenant.persistor"
- *                interface="org.wso2.carbon.core.multitenancy.persistence.TenantPersistor"
- *                cardinality="1..1" policy="dynamic"
- *                bind="setTenantPersistor"
- *                unbind="unsetTenantPersistor"
- */
-public class TenantMgtServiceComponent {
-    private static Log log = LogFactory.getLog(TenantMgtServiceComponent.class);
-
-    private static final String GAPP_TENANT_REG_SERVICE_NAME = "GAppTenantRegistrationService";
-
-    private static RealmService realmService;
-    private static RegistryService registryService;
-    
-    private static ConfigurationContextService configurationContextService;
-    
-    private static List<TenantMgtListener> tenantMgtListeners = new ArrayList<TenantMgtListener>();
-    private static TenantPersistor tenantPersistor = null;
-    private static TenantBillingService billingService = null;
-
-    protected void activate(ComponentContext context) {
-        try {
-
-            // Loading the stratos configurations from Stratos.xml
-            if (CommonUtil.getStratosConfig() == null) {
-                StratosConfiguration stratosConfig = CommonUtil.loadStratosConfiguration();
-                CommonUtil.setStratosConfig(stratosConfig);
-            }
-
-            // Loading the EULA
-            if (CommonUtil.getEula() == null) {
-                String eula = CommonUtil.loadTermsOfUsage();
-                CommonUtil.setEula(eula);
-            }
-            
-            populateRampartConfig(configurationContextService.
-					              getServerConfigContext().getAxisConfiguration());
-
-            log.debug("******* Tenant Config bundle is activated ******* ");
-        } catch (Exception e) {
-            log.error("******* Tenant Config bundle failed activating ****", e);
-        }
-    }
-
-    protected void setTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
-        addTenantMgtListener(tenantMgtListener);
-    }
-
-    protected void unsetTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
-        removeTenantMgtListener(tenantMgtListener);
-    }
-
-    protected void deactivate(ComponentContext context) {
-        log.debug("******* Governance Tenant Config bundle is deactivated ******* ");
-    }
-
-    protected void setRegistryService(RegistryService registryService) {
-        TenantMgtServiceComponent.registryService = registryService;
-    }
-
-    protected void unsetRegistryService(RegistryService registryService) {
-        setRegistryService(null);
-    }
-
-    protected void setRealmService(RealmService realmService) {
-        TenantMgtServiceComponent.realmService = realmService;
-    }
-
-    protected void unsetRealmService(RealmService realmService) {
-        setRealmService(null);
-    }
-
-    protected void setConfigurationContextService(ConfigurationContextService configurationContextService) {
-        log.debug("Receiving ConfigurationContext Service");
-        TenantMgtServiceComponent.configurationContextService = configurationContextService;
-
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
-        log.debug("Unsetting ConfigurationContext Service");
-        setConfigurationContextService(null);
-    }
-
-    public static void addTenantMgtListener(TenantMgtListener tenantMgtListener) {
-        tenantMgtListeners.add(tenantMgtListener);
-        sortTenantMgtListeners();
-    }
-
-    public static void removeTenantMgtListener(TenantMgtListener tenantMgtListener) {
-        tenantMgtListeners.remove(tenantMgtListener);
-        sortTenantMgtListeners();
-    }
-
-    public static void sortTenantMgtListeners() {
-        Collections.sort(tenantMgtListeners, new Comparator<TenantMgtListener>() {
-            public int compare(TenantMgtListener o1, TenantMgtListener o2) {
-                return o1.getListenerOrder() - o2.getListenerOrder();
-            }
-        });
-    }
-
-    public static List<TenantMgtListener> getTenantMgtListeners() {
-        return tenantMgtListeners;
-    }
-
-    public static ConfigurationContextService getConfigurationContextService() {
-        return configurationContextService;
-    }
-
-    public static ConfigurationContext getConfigurationContext() {
-        if (configurationContextService.getServerConfigContext() == null) {
-            return null;
-        }
-        return configurationContextService.getServerConfigContext();
-    }
-
-    public static RegistryService getRegistryService() {
-        return registryService;
-    }
-
-
-    public static RealmService getRealmService() {
-        return realmService;
-    }
-
-    public static TenantManager getTenantManager() {
-        return realmService.getTenantManager();
-    }
-
-    public static RealmConfiguration getBootstrapRealmConfiguration() {
-        return realmService.getBootstrapRealmConfiguration();
-    }
-
-    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
-        return registryService.getGovernanceSystemRegistry(tenantId);
-    }
-
-    public static UserRegistry getConfigSystemRegistry(int tenantId) throws RegistryException {
-        return registryService.getConfigSystemRegistry(tenantId);
-    }
-
-    public static TenantPersistor getTenantPersistor() {
-        return tenantPersistor;
-    }
-
-    protected void setTenantPersistor(TenantPersistor defaultTenantPersistor) {
-        tenantPersistor = defaultTenantPersistor;
-    }
-
-    public void unsetTenantPersistor(TenantPersistor defaultTenantPersistor) {
-        tenantPersistor = null;
-    }
-
-    
-   /** Updates RelyingPartyService with Crypto information
-    *
-    * @param config AxisConfiguration
-    * @throws Exception
-    */
-   private void populateRampartConfig(AxisConfiguration config) throws Exception {
-       AxisService service;
-       // Get the RelyingParty Service to update security policy with keystore information
-       service = config.getService(GAPP_TENANT_REG_SERVICE_NAME);
-       if (service == null) {
-           String msg = GAPP_TENANT_REG_SERVICE_NAME + " is not available in the Configuration Context";
-           log.error(msg);
-           throw new Exception(msg);
-       }
-       // Create a Rampart Config with default crypto information
-       Policy rampartConfig = TenantMgtRampartUtil.getDefaultRampartConfig();
-       // Add the RampartConfig to service policy
-       service.getPolicySubject().attachPolicy(rampartConfig);
-
-   }
-   
-   protected void setTenantBillingService(TenantBillingService tenantBillingService) {
-       billingService = tenantBillingService;
-   }
-   
-   protected void unsetTenantBillingService(TenantBillingService tenantBilling) {
-       setTenantBillingService(null);
-   }
-   
-   public static TenantBillingService getBillingService() {
-       return billingService;
-   }
-   
-   
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/internal/util/TenantMgtRampartUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/internal/util/TenantMgtRampartUtil.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/internal/util/TenantMgtRampartUtil.java
deleted file mode 100644
index 7cc40c7..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/internal/util/TenantMgtRampartUtil.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.apache.stratos.tenant.mgt.internal.util;
-
-import java.util.Properties;
-
-import org.apache.stratos.tenant.mgt.services.InMemoryPasswordcallbackHandler;
-import org.apache.neethi.Policy;
-import org.apache.rampart.policy.model.CryptoConfig;
-import org.apache.rampart.policy.model.RampartConfig;
-import org.wso2.carbon.base.ServerConfiguration;
-
-public class TenantMgtRampartUtil {
-	
-	public static Policy getDefaultRampartConfig() {
-        //Extract the primary keystore information from server configuration
-        ServerConfiguration serverConfig = ServerConfiguration.getInstance();
-        String keyStore = serverConfig.getFirstProperty("Security.KeyStore.Location");
-        String keyStoreType = serverConfig.getFirstProperty("Security.KeyStore.Type");
-        String keyStorePassword = serverConfig.getFirstProperty("Security.KeyStore.Password");
-        String privateKeyAlias = serverConfig.getFirstProperty("Security.KeyStore.KeyAlias");
-        String privateKeyPassword = serverConfig.getFirstProperty("Security.KeyStore.KeyPassword");
-
-        //Populate Rampart Configuration
-        RampartConfig rampartConfig = new RampartConfig();
-        rampartConfig.setUser(privateKeyAlias);
-        rampartConfig.setPwCbClass("org.wso2.carbon.tenant.mgt.services.InMemoryPasswordcallbackHandler");
-
-        //Set the private key alias and private key password in the password callback handler
-        InMemoryPasswordcallbackHandler.addUser(privateKeyAlias, privateKeyPassword);
-
-        CryptoConfig sigCrypto = new CryptoConfig();
-        Properties props = new Properties();
-        sigCrypto.setProvider("org.apache.ws.security.components.crypto.Merlin");
-        props.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", keyStoreType);
-        props.setProperty("org.apache.ws.security.crypto.merlin.file", keyStore);
-        props.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", keyStorePassword);
-        sigCrypto.setProp(props);
-
-        rampartConfig.setSigCryptoConfig(sigCrypto);
-        Policy policy = new Policy();
-        policy.addAssertion(rampartConfig);
-
-        return policy;
-
-    }
-	
-	
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/realm/CloudWSRealmConfigBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/realm/CloudWSRealmConfigBuilder.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/realm/CloudWSRealmConfigBuilder.java
deleted file mode 100644
index 171f9a3..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/realm/CloudWSRealmConfigBuilder.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.tenant.mgt.realm;
-
-import java.util.Map;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.util.UUIDGenerator;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.um.ws.api.WSRealm;
-import org.wso2.carbon.um.ws.api.WSRemoteUserMgtConstants;
-import org.wso2.carbon.user.api.RealmConfiguration;
-import org.wso2.carbon.user.api.TenantMgtConfiguration;
-import org.wso2.carbon.user.core.UserStoreException;
-import org.wso2.carbon.user.core.config.RealmConfigXMLProcessor;
-import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
-import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants;
-import org.wso2.carbon.user.core.tenant.Tenant;
-
-/**
- * This class is no more used by cloud manager or elsewhere.
- * Hence deprecated and will be removed eventually.
- */
-@Deprecated
-public class CloudWSRealmConfigBuilder implements MultiTenantRealmConfigBuilder {
-
-    private static final Log log = LogFactory.getLog(CloudWSRealmConfigBuilder.class);
-
-
-    /**
-     * This method is called on server startup by DefaultRealmService by non-Idaas cloud services
-     * 
-     * This is not called on ws.api startup.
-     */
-    public RealmConfiguration getRealmConfigForTenantToCreateRealm(
-            RealmConfiguration bootStrapConfig, RealmConfiguration persistedConfig, int tenantId)
-            throws UserStoreException {
-        RealmConfiguration realmConfig;
-        try {
-            if (persistedConfig.getRealmClassName().equals(WSRealm.class.getName())) {
-                realmConfig = persistedConfig;
-            } else {
-                realmConfig = bootStrapConfig.cloneRealmConfiguration();
-                realmConfig.setTenantId(tenantId);
-            }
-            if (log.isDebugEnabled()) {
-                OMElement omElement = RealmConfigXMLProcessor.serialize(realmConfig);
-                log.debug("Creating realm from **** " + omElement.toString());
-            }
-        } catch (Exception e) {
-            String msg = e.getMessage();
-            log.error(msg, e);
-            throw new UserStoreException(msg);
-        }
-        return realmConfig;
-    }
-
-    public RealmConfiguration getRealmConfigForTenantToCreateRealmOnTenantCreation(
-            RealmConfiguration bootStrapConfig, RealmConfiguration persistedConfig, int tenantId)
-            throws UserStoreException{
-        RealmConfiguration realmConfig;
-        try {
-            realmConfig = bootStrapConfig.cloneRealmConfiguration();
-            realmConfig.setRealmClassName("org.wso2.carbon.um.ws.api.WSRealm");
-            
-            realmConfig.setAdminPassword(UUIDGenerator.getUUID());
-            Map<String, String> realmProps = realmConfig.getRealmProperties();
-            realmProps.remove(JDBCRealmConstants.URL);
-            realmProps.remove(JDBCRealmConstants.DRIVER_NAME);
-            realmProps.remove(JDBCRealmConstants.USER_NAME);
-            realmProps.remove(JDBCRealmConstants.PASSWORD);
-            
-            realmConfig.setTenantId(tenantId);
-
-            if (log.isDebugEnabled()) {
-                OMElement omElement = RealmConfigXMLProcessor.serialize(realmConfig);
-                log.debug("Creating realm from (On tenant creation)**** " + omElement.toString());
-            }
-
-        } catch (Exception e) {
-            String msg = e.getMessage();
-            log.error(msg, e);
-            throw new UserStoreException(msg);
-        }
-        return realmConfig;
-    }
-
-
-    public RealmConfiguration getRealmConfigForTenantToPersist(RealmConfiguration bootStrapConfig,
-                                                               TenantMgtConfiguration tenantMgtConfig,
-                                                               Tenant tenantInfo, int tenantId)
-            throws UserStoreException {
-        RealmConfiguration realmConfig;
-        try {
-            realmConfig = bootStrapConfig.cloneRealmConfiguration();
-            realmConfig.setAdminUserName(tenantInfo.getAdminName());
-            realmConfig.setAdminPassword(UUIDGenerator.getUUID());
-            Map<String, String> realmProps = realmConfig.getRealmProperties();
-            realmProps.remove(JDBCRealmConstants.URL);
-            realmProps.remove(JDBCRealmConstants.DRIVER_NAME);
-            realmProps.remove(JDBCRealmConstants.USER_NAME);
-            realmProps.remove(JDBCRealmConstants.PASSWORD);
-            realmProps.remove(WSRemoteUserMgtConstants.SERVER_URL);
-            realmProps.remove(WSRemoteUserMgtConstants.USER_NAME);
-            realmProps.remove(WSRemoteUserMgtConstants.PASSWORD);
-            realmProps.remove(WSRemoteUserMgtConstants.SINGLE_USER_AUTHENTICATION);
-            realmProps.put("MultiTenantRealmConfigBuilder", IdaasWSRealmConfigBuilder.class.getName());
-            realmConfig.setTenantId(tenantId);
-            if (log.isDebugEnabled()) {
-                OMElement omElement = RealmConfigXMLProcessor.serialize(realmConfig);
-                log.debug("Saving RealmConfiguration **** " + omElement.toString());
-            }
-
-        } catch (Exception e) {
-            String msg = e.getMessage();
-            log.error(msg, e);
-            throw new UserStoreException(msg);
-        }
-        return realmConfig;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/realm/IdaasWSRealmConfigBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/realm/IdaasWSRealmConfigBuilder.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/realm/IdaasWSRealmConfigBuilder.java
deleted file mode 100644
index a213ee9..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/realm/IdaasWSRealmConfigBuilder.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.tenant.mgt.realm;
-
-import java.util.Map;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.user.api.RealmConfiguration;
-import org.wso2.carbon.user.api.TenantMgtConfiguration;
-import org.wso2.carbon.user.core.UserStoreException;
-import org.wso2.carbon.user.core.config.RealmConfigXMLProcessor;
-import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
-import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants;
-import org.wso2.carbon.user.core.tenant.Tenant;
-
-public class IdaasWSRealmConfigBuilder implements MultiTenantRealmConfigBuilder {
-    
-    private static final Log log = LogFactory.getLog(CloudWSRealmConfigBuilder.class);
-
-    /**
-     * This method is called, on server startup by DefaultRealmService by Idaas only
-     * 
-     * This is not called on ws.api startup or by any non-Idaas servers
-     */
-    public RealmConfiguration getRealmConfigForTenantToCreateRealm(
-            RealmConfiguration bootStrapConfig, RealmConfiguration persistedConfig, int tenantId)
-            throws UserStoreException {
-        RealmConfiguration realmConfig;
-        try {
-                realmConfig = persistedConfig;
-               // now this is Idaas
-                Map<String, String> realmProps = realmConfig.getRealmProperties();
-                Map<String, String> bootStrapProps = bootStrapConfig.getRealmProperties();
-                realmProps.put(JDBCRealmConstants.URL, bootStrapProps.get(JDBCRealmConstants.URL));
-                realmProps.put(JDBCRealmConstants.DRIVER_NAME, bootStrapProps.get(
-                        JDBCRealmConstants.DRIVER_NAME));
-                realmProps.put(JDBCRealmConstants.USER_NAME, bootStrapProps.get(
-                        JDBCRealmConstants.USER_NAME));
-                realmProps.put(JDBCRealmConstants.PASSWORD, bootStrapProps.get(
-                        JDBCRealmConstants.PASSWORD));
-                realmConfig.setTenantId(tenantId);
-
-                if(log.isDebugEnabled()) {
-                    OMElement omElement = RealmConfigXMLProcessor.serialize(realmConfig);
-                    log.debug("Creating realm from **** " + omElement.toString());
-                }
-                
-        } catch (Exception e) {
-            String msg = e.getMessage();
-            log.error(msg, e);
-            throw new UserStoreException(msg);
-        }
-        return realmConfig;
-    }
-    
-    public RealmConfiguration getRealmConfigForTenantToCreateRealmOnTenantCreation(
-            RealmConfiguration bootStrapConfig, RealmConfiguration persistedConfig, int tenantId)
-            throws UserStoreException{
-        //never called
-        return null;
-    }
-
-    public RealmConfiguration getRealmConfigForTenantToPersist(RealmConfiguration bootStrapConfig,
-                                                               TenantMgtConfiguration tenantMgtConfig,
-                                                               Tenant tenantInfo, int tenantId)
-            throws UserStoreException {
-        //never called
-        return null;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/GAppTenantRegistrationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/GAppTenantRegistrationService.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/GAppTenantRegistrationService.java
deleted file mode 100644
index 369ea4c..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/GAppTenantRegistrationService.java
+++ /dev/null
@@ -1,120 +0,0 @@
-package org.apache.stratos.tenant.mgt.services;
-
-import org.apache.stratos.tenant.mgt.exception.TenantManagementException;
-import org.apache.stratos.tenant.mgt.internal.TenantMgtServiceComponent;
-import org.apache.stratos.tenant.mgt.util.TenantMgtUtil;
-import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
-import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
-import org.wso2.carbon.stratos.common.exception.StratosException;
-import org.wso2.carbon.user.api.RealmConfiguration;
-import org.wso2.carbon.user.api.TenantMgtConfiguration;
-import org.wso2.carbon.user.api.UserStoreException;
-import org.wso2.carbon.user.core.UserCoreConstants;
-import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
-import org.wso2.carbon.user.core.tenant.Tenant;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.ws.security.util.UUIDGenerator;
-
-public class GAppTenantRegistrationService {
-	
-    private static final String GOOGLE_APPS_IDP_NAME = "GoogleApps";
-    
-    private static final Log log = LogFactory.getLog(GAppTenantRegistrationService.class);
-    
-    
-    public boolean isRegisteredAsGoogleAppDomain(String domain) throws TenantManagementException {
-
-        TenantManager tenantManager = 
-            TenantMgtServiceComponent.getRealmService().getTenantManager();
-        try {
-            int tenantId = tenantManager.getTenantId(domain);
-
-            if (tenantId == -1) {
-                return false;
-            }
-
-            Tenant tenant = (Tenant) tenantManager.getTenant(tenantId);
-            RealmConfiguration realmConfig = tenant.getRealmConfig();
-            String value = realmConfig.getUserStoreProperties().get(
-                            UserCoreConstants.RealmConfig.PROPERTY_EXTERNAL_IDP);
-
-            if (value == null) {
-                throw new TenantManagementException(
-                        "This domain has been already registered as a non-Google App domain");
-            }
-
-            if (value.equals(GOOGLE_APPS_IDP_NAME)) {
-                return true;
-            }
-            
-            throw new TenantManagementException(
-                    "This domain has been already registered with a different External IdP");
-        } catch (UserStoreException e) {
-            log.error(e.getMessage(), e);
-            throw new TenantManagementException("System error occured while connecting user store");
-        }
-    }
-    
-    public boolean registerGoogleAppsTenant(
-                                TenantInfoBean tenantInfoBean)throws TenantManagementException {
-        try {
-            int tenantId = -1;
-            Tenant tenant = TenantMgtUtil.initializeTenant(tenantInfoBean);
-            TenantPersistor tenantPersistor = TenantMgtServiceComponent.getTenantPersistor();
-
-            MultiTenantRealmConfigBuilder builder =
-                    TenantMgtServiceComponent.getRealmService().getMultiTenantRealmConfigBuilder();
-            TenantMgtConfiguration tenantMgtConfiguration =
-                    TenantMgtServiceComponent.getRealmService().getTenantMgtConfiguration();
-            RealmConfiguration bootStrapRealmConfig =
-                    TenantMgtServiceComponent.getRealmService().getBootstrapRealmConfiguration();
-            RealmConfiguration realmConfigToPersist =
-                    builder.getRealmConfigForTenantToPersist(bootStrapRealmConfig,
-                            tenantMgtConfiguration, tenant, -1);
-            realmConfigToPersist.getUserStoreProperties().put(
-                    UserCoreConstants.RealmConfig.PROPERTY_EXTERNAL_IDP, GOOGLE_APPS_IDP_NAME);
-            tenant.setRealmConfig(realmConfigToPersist);
-            tenant.setAdminPassword(UUIDGenerator.getUUID());
-
-            tenantId = tenantPersistor.persistTenant(tenant);
-            tenantInfoBean.setTenantId(tenantId);
-
-            TenantMgtUtil.addClaimsToUserStoreManager(tenant);
-
-            // Notify tenant addition
-            try {
-                TenantMgtUtil.triggerAddTenant(tenantInfoBean);
-            } catch (StratosException e) {
-                String msg = "Error in notifying tenant addition.";
-                log.error(msg, e);
-                throw new Exception(msg, e);
-            }
-
-            // adding the subscription entry
-            try {
-                if (TenantMgtServiceComponent.getBillingService() != null) {
-                    tenantInfoBean.setTenantId(tenantId); // required for the following method
-                    TenantMgtServiceComponent.getBillingService().addUsagePlan(tenant,
-                            tenantInfoBean.getUsagePlan());
-                    if (log.isDebugEnabled()) {
-                        log.debug("Subscription added successfully for the tenant: " +
-                                  tenantInfoBean.getTenantDomain());
-                    }
-                }
-            } catch (Exception e) {
-                log.error("Error occurred while adding the subscription for tenant: " +
-                          tenantInfoBean.getTenantDomain() + " " + e.getMessage(), e);
-            }
-
-            TenantMgtServiceComponent.getRealmService().getTenantManager().activateTenant(tenantId);
-            return true;
-        } catch (Exception e) {
-            log.error("Error creating tenant for GooogleApp market place implementation", e);
-            throw new TenantManagementException(
-                    "Error creating tenant for GooogleApp market place implementation", e);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/InMemoryPasswordcallbackHandler.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/InMemoryPasswordcallbackHandler.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/InMemoryPasswordcallbackHandler.java
deleted file mode 100644
index fec72a1..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/InMemoryPasswordcallbackHandler.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package org.apache.stratos.tenant.mgt.services;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-import org.apache.ws.security.WSPasswordCallback;
-
-public class InMemoryPasswordcallbackHandler  implements CallbackHandler {
-
-    private static Map<String, String> keystorePassword = new HashMap<String, String>();
-
-    public void handle(Callback[] callbacks)
-            throws IOException, UnsupportedCallbackException {
-
-        for (int i = 0; i < callbacks.length; i++) {
-
-            if (callbacks[i] instanceof WSPasswordCallback) {
-                WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
-                String id = pc.getIdentifier();
-                if (keystorePassword.get(id) != null) {
-                    pc.setPassword(keystorePassword.get(id));
-                } else {
-                    throw new UnsupportedCallbackException(callbacks[i], "no password found for " + id);
-                }
-            }
-
-        }
-    }
-
-    public static void addUser(String username, String password) {
-        keystorePassword.put(username, password);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/TenantMgtAdminService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/TenantMgtAdminService.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/TenantMgtAdminService.java
deleted file mode 100644
index 65d7e8c..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/TenantMgtAdminService.java
+++ /dev/null
@@ -1,496 +0,0 @@
-/*
- * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- * http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.stratos.tenant.mgt.services;
-
-import org.wso2.carbon.core.AbstractAdmin;
-import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
-import org.wso2.carbon.stratos.common.exception.StratosException;
-import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil;
-import org.wso2.carbon.stratos.common.util.CommonUtil;
-import org.apache.stratos.tenant.mgt.beans.PaginatedTenantInfoBean;
-import org.wso2.carbon.tenant.mgt.core.internal.TenantMgtCoreServiceComponent;
-import org.apache.stratos.tenant.mgt.internal.TenantMgtServiceComponent;
-import org.apache.stratos.tenant.mgt.util.TenantMgtUtil;
-import org.wso2.carbon.user.core.UserRealm;
-import org.wso2.carbon.user.core.UserStoreException;
-import org.wso2.carbon.user.core.UserStoreManager;
-import org.wso2.carbon.user.core.tenant.Tenant;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-import org.wso2.carbon.utils.DataPaginator;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * This is the admin Web service which is used for managing tenants
- */
-public class TenantMgtAdminService extends AbstractAdmin {
-    private static final Log log = LogFactory.getLog(TenantMgtAdminService.class);
-
-    /**
-     * super admin adds a tenant
-     *
-     * @param tenantInfoBean tenant info bean
-     * @return UUID
-     * @throws Exception if error in adding new tenant.
-     */
-    public String addTenant(TenantInfoBean tenantInfoBean) throws Exception {
-        try {
-            CommonUtil.validateEmail(tenantInfoBean.getEmail());
-        } catch (Exception e) {
-            String msg = "Invalid email is provided.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-        String tenantDomain = tenantInfoBean.getTenantDomain();
-        TenantMgtUtil.validateDomain(tenantDomain);
-        UserRegistry userRegistry = (UserRegistry) getGovernanceRegistry();
-        if (userRegistry == null) {
-            log.error("Security Alert! User registry is null. A user is trying create a tenant "
-                      + " without an authenticated session.");
-            throw new Exception("Invalid data."); // obscure error message.
-        }
-
-        if (userRegistry.getTenantId() != MultitenantConstants.SUPER_TENANT_ID) {
-            log.error("Security Alert! Non super tenant trying to create a tenant.");
-            throw new Exception("Invalid data."); // obscure error message.
-        }
-        Tenant tenant = TenantMgtUtil.initializeTenant(tenantInfoBean);
-        TenantPersistor persistor = TenantMgtServiceComponent.getTenantPersistor();
-        // not validating the domain ownership, since created by super tenant
-        int tenantId = persistor.persistTenant(tenant, false, tenantInfoBean.getSuccessKey(),
-                                tenantInfoBean.getOriginatedService());
-        tenantInfoBean.setTenantId(tenantId);
-        
-        TenantMgtUtil.addClaimsToUserStoreManager(tenant);
-        
-        //Notify tenant addition
-        try {
-            TenantMgtUtil.triggerAddTenant(tenantInfoBean);
-        } catch (StratosException e) {
-            String msg = "Error in notifying tenant addition.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-        //adding the subscription entry
-        /*try {
-            if (TenantMgtServiceComponent.getBillingService() != null) {
-                TenantMgtServiceComponent.getBillingService().
-                        addUsagePlan(tenant, tenantInfoBean.getUsagePlan());
-                if (log.isDebugEnabled()) {
-                    log.debug("Subscription added successfully for the tenant: " +
-                            tenantInfoBean.getTenantDomain());
-                }
-            }
-        } catch (Exception e) {
-            String msg = "Error occurred while adding the subscription for tenant: " + tenantDomain;
-            log.error(msg, e);
-        }*/
-
-        // For the super tenant tenant creation, tenants are always activated as they are created.
-        TenantMgtUtil.activateTenantInitially(tenantInfoBean, tenantId);
-
-        return TenantMgtUtil.prepareStringToShowThemeMgtPage(tenant.getId());
-    }
-
-    /**
-     * Get the list of the tenants
-     *
-     * @return List<TenantInfoBean>
-     * @throws Exception UserStorException
-     */
-    private List<TenantInfoBean> getAllTenants() throws Exception {
-        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
-        Tenant[] tenants;
-        try {
-            tenants = (Tenant[]) tenantManager.getAllTenants();
-        } catch (UserStoreException e) {
-            String msg = "Error in retrieving the tenant information.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        List<TenantInfoBean> tenantList = new ArrayList<TenantInfoBean>();
-        for (Tenant tenant : tenants) {
-            TenantInfoBean bean = TenantMgtUtil.getTenantInfoBeanfromTenant(tenant.getId(), tenant);
-            tenantList.add(bean);
-        }
-        return tenantList;
-    }
-    
-    /**
-     * Get the list of the tenants
-     *
-     * @return List<TenantInfoBean>
-     * @throws Exception UserStorException
-     */
-    private List<TenantInfoBean> searchPartialTenantsDomains(String domain) throws Exception {
-        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
-        Tenant[] tenants;
-        try {
-        	domain = domain.trim();
-            tenants = (Tenant[]) tenantManager.getAllTenantsForTenantDomainStr(domain);
-        } catch (UserStoreException e) {
-            String msg = "Error in retrieving the tenant information.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        List<TenantInfoBean> tenantList = new ArrayList<TenantInfoBean>();
-        for (Tenant tenant : tenants) {
-            TenantInfoBean bean = TenantMgtUtil.getTenantInfoBeanfromTenant(tenant.getId(), tenant);
-            tenantList.add(bean);
-        }
-        return tenantList;
-    }
-
-    /**
-     * Retrieve all the tenants
-     *
-     * @return tenantInfoBean[]
-     * @throws Exception if failed to get Tenant Manager
-     */
-    public TenantInfoBean[] retrieveTenants() throws Exception {
-        List<TenantInfoBean> tenantList = getAllTenants();
-        return tenantList.toArray(new TenantInfoBean[tenantList.size()]);
-    }
-    
-    /**
-     * Retrieve all the tenants which matches the partial search domain
-     *
-     * @return tenantInfoBean[]
-     * @throws Exception if failed to get Tenant Manager
-     */
-    public TenantInfoBean[] retrievePartialSearchTenants(String domain) throws Exception {
-        List<TenantInfoBean> tenantList = searchPartialTenantsDomains(domain);
-        return tenantList.toArray(new TenantInfoBean[tenantList.size()]);
-    }
-
-    /**
-     * Method to retrieve all the partial search domain tenants paginated
-     *
-     * @param pageNumber Number of the page.
-     * @return PaginatedTenantInfoBean
-     * @throws Exception if failed to getTenantManager;
-     */
-    public PaginatedTenantInfoBean retrievePaginatedPartialSearchTenants(String domain,int pageNumber) throws Exception {
-        List<TenantInfoBean> tenantList = searchPartialTenantsDomains(domain);
-
-        // Pagination
-        PaginatedTenantInfoBean paginatedTenantInfoBean = new PaginatedTenantInfoBean();
-        DataPaginator.doPaging(pageNumber, tenantList, paginatedTenantInfoBean);
-        return paginatedTenantInfoBean;
-    }
-    
-    /**
-     * Method to retrieve all the tenants paginated
-     *
-     * @param pageNumber Number of the page.
-     * @return PaginatedTenantInfoBean
-     * @throws Exception if failed to getTenantManager;
-     */
-    public PaginatedTenantInfoBean retrievePaginatedTenants(int pageNumber) throws Exception {
-        List<TenantInfoBean> tenantList = getAllTenants();
-
-        // Pagination
-        PaginatedTenantInfoBean paginatedTenantInfoBean = new PaginatedTenantInfoBean();
-        DataPaginator.doPaging(pageNumber, tenantList, paginatedTenantInfoBean);
-        return paginatedTenantInfoBean;
-    }
-
-    /**
-     * Get a specific tenant
-     *
-     * @param tenantDomain tenant domain
-     * @return tenantInfoBean
-     * @throws Exception UserStoreException
-     */
-    public TenantInfoBean getTenant(String tenantDomain) throws Exception {
-        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
-
-        int tenantId;
-        try {
-            tenantId = tenantManager.getTenantId(tenantDomain);
-        } catch (UserStoreException e) {
-            String msg = "Error in retrieving the tenant id for the tenant domain: " +
-                         tenantDomain + ".";
-            log.error(msg);
-            throw new Exception(msg, e);
-        }
-        Tenant tenant;
-        try {
-            tenant = (Tenant) tenantManager.getTenant(tenantId);
-        } catch (UserStoreException e) {
-            String msg = "Error in retrieving the tenant from the tenant manager.";
-            log.error(msg);
-            throw new Exception(msg, e);
-        }
-
-        TenantInfoBean bean = TenantMgtUtil.initializeTenantInfoBean(tenantId, tenant);
-
-        // retrieve first and last names from the UserStoreManager
-        bean.setFirstname(ClaimsMgtUtil.getFirstNamefromUserStoreManager(
-                TenantMgtServiceComponent.getRealmService(), tenantId));
-        bean.setLastname(ClaimsMgtUtil.getLastNamefromUserStoreManager(
-                TenantMgtServiceComponent.getRealmService(), tenantId));
-
-        //getting the subscription plan
-        String activePlan = "";
-        if(TenantMgtServiceComponent.getBillingService() != null){
-            activePlan = TenantMgtServiceComponent.getBillingService().
-                    getActiveUsagePlan(tenantDomain);
-        }
-
-        if(activePlan != null && activePlan.trim().length() > 0){
-            bean.setUsagePlan(activePlan);
-        }else{
-            bean.setUsagePlan("");
-        }
-
-        return bean;
-    }
-
-    /**
-     * Updates a given tenant
-     *
-     * @param tenantInfoBean tenant information
-     * @throws Exception UserStoreException
-     */
-    public void updateTenant(TenantInfoBean tenantInfoBean) throws Exception {
-        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
-        UserStoreManager userStoreManager;
-
-        // filling the non-set admin and admin password first
-        UserRegistry configSystemRegistry = TenantMgtServiceComponent.getConfigSystemRegistry(
-                tenantInfoBean.getTenantId());
-
-        String tenantDomain = tenantInfoBean.getTenantDomain();
-
-        int tenantId;
-        try {
-            tenantId = tenantManager.getTenantId(tenantDomain);
-        } catch (UserStoreException e) {
-            String msg = "Error in retrieving the tenant id for the tenant domain: " + tenantDomain
-                         + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        Tenant tenant;
-        try {
-            tenant = (Tenant) tenantManager.getTenant(tenantId);
-        } catch (UserStoreException e) {
-            String msg = "Error in retrieving the tenant id for the tenant domain: " +
-                         tenantDomain + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        // filling the first and last name values
-        if (tenantInfoBean.getFirstname() != null &&
-            !tenantInfoBean.getFirstname().trim().equals("")) {
-            try {
-                CommonUtil.validateName(tenantInfoBean.getFirstname(), "First Name");
-            } catch (Exception e) {
-                String msg = "Invalid first name is provided.";
-                log.error(msg, e);
-                throw new Exception(msg, e);
-            }
-        }
-        if (tenantInfoBean.getLastname() != null &&
-            !tenantInfoBean.getLastname().trim().equals("")) {
-            try {
-                CommonUtil.validateName(tenantInfoBean.getLastname(), "Last Name");
-            } catch (Exception e) {
-                String msg = "Invalid last name is provided.";
-                log.error(msg, e);
-                throw new Exception(msg, e);
-            }
-        }
-
-        tenant.setAdminFirstName(tenantInfoBean.getFirstname());
-        tenant.setAdminLastName(tenantInfoBean.getLastname());
-        TenantMgtUtil.addClaimsToUserStoreManager(tenant);
-
-        // filling the email value
-        if (tenantInfoBean.getEmail() != null && !tenantInfoBean.getEmail().equals("")) {
-            // validate the email
-            try {
-                CommonUtil.validateEmail(tenantInfoBean.getEmail());
-            } catch (Exception e) {
-                String msg = "Invalid email is provided.";
-                log.error(msg, e);
-                throw new Exception(msg, e);
-            }
-            tenant.setEmail(tenantInfoBean.getEmail());
-        }
-
-        UserRealm userRealm = configSystemRegistry.getUserRealm();
-        try {
-            userStoreManager = userRealm.getUserStoreManager();
-        } catch (UserStoreException e) {
-            String msg = "Error in getting the user store manager for tenant, tenant domain: " +
-                         tenantDomain + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        boolean updatePassword = false;
-        if (tenantInfoBean.getAdminPassword() != null
-            && !tenantInfoBean.getAdminPassword().equals("")) {
-            updatePassword = true;
-        }
-        if (!userStoreManager.isReadOnly() && updatePassword) {
-            // now we will update the tenant admin with the admin given
-            // password.
-            try {
-                userStoreManager.updateCredentialByAdmin(tenantInfoBean.getAdmin(),
-                                                         tenantInfoBean.getAdminPassword());
-            } catch (UserStoreException e) {
-                String msg = "Error in changing the tenant admin password, tenant domain: " +
-                             tenantInfoBean.getTenantDomain() + ". " + e.getMessage() + " for: " +
-                             tenantInfoBean.getAdmin();
-                log.error(msg, e);
-                throw new Exception(msg, e);
-            }
-        } else {
-            //Password should be empty since no password update done
-            tenantInfoBean.setAdminPassword("");
-        }
-
-        try {
-            tenantManager.updateTenant(tenant);
-        } catch (UserStoreException e) {
-            String msg = "Error in updating the tenant for tenant domain: " + tenantDomain + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-        
-        //Notify tenant update to all listeners
-        try {
-            TenantMgtUtil.triggerUpdateTenant(tenantInfoBean);
-        } catch (StratosException e) {
-            String msg = "Error in notifying tenant update.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        //updating the usage plan
-        /*try{
-            if(TenantMgtServiceComponent.getBillingService() != null){
-                TenantMgtServiceComponent.getBillingService().
-                        updateUsagePlan(tenantInfoBean.getTenantDomain(), tenantInfoBean.getUsagePlan());
-            }
-        }catch(Exception e){
-            String msg = "Error when updating the usage plan: " + e.getMessage();
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }*/
-    }
-
-    /**
-     * Activate a deactivated tenant, by the super tenant.
-     *
-     * @param tenantDomain tenant domain
-     * @throws Exception UserStoreException.
-     */
-    public void activateTenant(String tenantDomain) throws Exception {
-        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
-        int tenantId;
-        try {
-            tenantId = tenantManager.getTenantId(tenantDomain);
-        } catch (UserStoreException e) {
-            String msg = "Error in retrieving the tenant id for the tenant domain: " + tenantDomain
-                         + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        TenantMgtUtil.activateTenant(tenantDomain, tenantManager, tenantId);
-
-        //Notify tenant activation all listeners
-        try {
-            TenantMgtUtil.triggerTenantActivation(tenantId);
-        } catch (StratosException e) {
-            String msg = "Error in notifying tenant activate.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-    }
-
-    /**
-     * Deactivate the given tenant
-     *
-     * @param tenantDomain tenant domain
-     * @throws Exception UserStoreException
-     */
-    public void deactivateTenant(String tenantDomain) throws Exception {
-        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
-        int tenantId;
-        try {
-            tenantId = tenantManager.getTenantId(tenantDomain);
-        } catch (UserStoreException e) {
-            String msg =
-                    "Error in retrieving the tenant id for the tenant domain: " +
-                    tenantDomain + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        TenantMgtUtil.deactivateTenant(tenantDomain, tenantManager, tenantId);
-
-        //Notify tenant deactivation all listeners
-        try {
-            TenantMgtUtil.triggerTenantDeactivation(tenantId);
-        } catch (StratosException e) {
-            String msg = "Error in notifying tenant deactivate.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-    }
-
-    /**
-     * Delete a specific tenant
-     *
-     * @param tenantDomain The domain name of the tennat that needs to be deleted
-     */
-    public void deleteTenant(String tenantDomain) throws Exception {
-        TenantManager tenantManager = TenantMgtCoreServiceComponent.getTenantManager();
-        int tenantId = tenantManager.getTenantId(tenantDomain);
-        try {
-            TenantMgtServiceComponent.getBillingService().deleteBillingData(tenantId);
-            TenantMgtUtil.deleteTenantRegistryData(tenantId);
-            TenantMgtUtil.deleteTenantUMData(tenantId);
-            tenantManager.deleteTenant(tenantId);
-            log.info("Deleted tenant with domain: " + tenantDomain + " and tenant id: " + tenantId + 
-                     " from the system.");
-        } catch (Exception e) {
-            String msg = "Error deleting tenant with domain: " + tenantDomain + " and tenant id: " +
-                    tenantId + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/TenantSelfRegistrationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/TenantSelfRegistrationService.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/TenantSelfRegistrationService.java
deleted file mode 100644
index d6243df..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/services/TenantSelfRegistrationService.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *    http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.tenant.mgt.services;
-
-import org.wso2.carbon.captcha.mgt.beans.CaptchaInfoBean;
-import org.wso2.carbon.captcha.mgt.constants.CaptchaMgtConstants;
-import org.wso2.carbon.captcha.mgt.util.CaptchaUtil;
-import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
-import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
-import org.wso2.carbon.stratos.common.exception.StratosException;
-import org.wso2.carbon.stratos.common.util.CommonUtil;
-import org.apache.stratos.tenant.mgt.internal.TenantMgtServiceComponent;
-import org.apache.stratos.tenant.mgt.util.TenantMgtUtil;
-import org.wso2.carbon.user.core.tenant.Tenant;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import org.apache.axis2.AxisFault;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-
-/**
- * TenantSelfRegistration - This is the Web service that will be called when
- * tenants register themselves
- */
-public class TenantSelfRegistrationService {
-    private static final Log log = LogFactory.getLog(TenantSelfRegistrationService.class);
-
-    /**
-     * Registers a tenant - Tenant Self Registration
-     *
-     * @param tenantInfoBean  - tenantInformation
-     * @param captchaInfoBean - captchaInformation
-     * @return String UUID
-     * @throws Exception if the tenant registration fails.
-     */
-    public String registerTenant(TenantInfoBean tenantInfoBean, CaptchaInfoBean captchaInfoBean)
-            throws Exception {
-        // validate the email
-        try {
-            CommonUtil.validateEmail(tenantInfoBean.getEmail());
-        } catch (Exception e) {
-            String msg = "Invalid email is provided.";
-            log.error(msg, e);
-            throw new AxisFault(msg);
-        }
-        // validate the domain
-        String domainName = tenantInfoBean.getTenantDomain();
-        try {
-            TenantMgtUtil.validateDomain(domainName);
-        } catch (Exception e) {
-            String msg = "Domain Validation Failed.";
-            log.error(msg, e);
-            throw new AxisFault(msg);
-        }
-        // validate the first/last names
-        String firstname = tenantInfoBean.getFirstname();
-        String lastname = tenantInfoBean.getLastname();
-        try {
-            CommonUtil.validateName(firstname, "First Name");
-            CommonUtil.validateName(lastname, "Last Name");
-        } catch (Exception e) {
-            String msg = "First/Last Name Validation Failed.";
-            log.error(msg, e);
-            throw new AxisFault(msg);
-        } // now validate the captcha
-        try {
-            CaptchaUtil.validateCaptcha(captchaInfoBean);
-            if (log.isDebugEnabled()) {
-                log.debug("Captcha Successfully Validated.");
-            }
-        } catch (Exception e) {
-            String msg = CaptchaMgtConstants.CAPTCHA_ERROR_MSG;
-            log.error(msg, e);
-            throw new AxisFault(msg);
-        } finally {
-            try {
-                CaptchaUtil.cleanCaptcha(captchaInfoBean.getSecretKey());
-            } catch (Exception e) {
-                String msg = "Error in cleaning captcha. ";
-                log.error(msg, e);
-                // not throwing the exception in finally more up.
-            }
-        }
-        // persists the tenant.
-        Tenant tenant = TenantMgtUtil.initializeTenant(tenantInfoBean);
-        TenantPersistor persistor = TenantMgtServiceComponent.getTenantPersistor();
-        int tenantId = persistor.persistTenant(tenant, true, tenantInfoBean.getSuccessKey(), 
-                tenantInfoBean.getOriginatedService());
-        tenantInfoBean.setTenantId(tenantId);
-        TenantMgtUtil.addClaimsToUserStoreManager(tenant);
-        
-        //Notify tenant addition
-        try {
-            TenantMgtUtil.triggerAddTenant(tenantInfoBean);
-        } catch (StratosException e) {
-            String msg = "Error in notifying tenant addition.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        //adding the subscription entry
-        try {
-            if (TenantMgtServiceComponent.getBillingService() != null) {
-                TenantMgtServiceComponent.getBillingService().addUsagePlan(tenant,
-                        tenantInfoBean.getUsagePlan());
-                if (log.isDebugEnabled()) {
-                    log.debug("Subscription added successfully for the tenant: " +
-                              tenantInfoBean.getTenantDomain());
-                }
-            }
-        } catch (Exception e) {
-            String msg = "Error occurred while adding the subscription for tenant: " + domainName;
-            log.error(msg, e);
-        }
-
-        // If Email Validation is made optional, tenant will be activated now.
-        if (CommonUtil.isTenantManagementEmailsDisabled() ||
-                !CommonUtil.isEmailValidationMandatory()) {
-            TenantMgtUtil.activateTenantInitially(tenantInfoBean, tenantId);
-        }
-        return TenantMgtUtil.prepareStringToShowThemeMgtPage(tenant.getId());
-    }
-
-    /**
-     * Check if the selected domain is available to register
-     *
-     * @param domainName domain name
-     * @return true, if the domain is available to register
-     * @throws Exception, if unable to get the tenant manager, or get the tenant id
-     *                    from manager.
-     */
-    public boolean checkDomainAvailability(String domainName) throws Exception {
-        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
-        int tenantId = tenantManager.getTenantId(domainName);
-        if (log.isDebugEnabled()) {
-            log.debug("Tenant Domain is available to register.");
-        }
-        return tenantId < 0; // no tenant exists with the same tenant domain
-    }
-
-    // use a boolean instead of string.
-
-    /**
-     * Validates or Suggests a domain.
-     *
-     * @param domain     tenant domain
-     * @param successKey success key
-     * @return domain name
-     * @throws Exception if exception in validating or suggesting the tenant domain.
-     */
-    public String validateOrSuggestDomain(String domain, String successKey) throws Exception {
-        if (successKey != null && !successKey.equals("")) {
-            if (CommonUtil.validateDomainFromSuccessKey(
-                    TenantMgtServiceComponent.getGovernanceSystemRegistry(
-                            MultitenantConstants.SUPER_TENANT_ID), domain, successKey)) {
-                return domain;
-            }
-        }
-        // otherwise domain is not correct
-
-        return "null";
-    }
-
-    /**
-     * Generates a random Captcha
-     *
-     * @return captchaInfoBean
-     * @throws Exception, if exception in cleaning old captchas or generating new
-     *                    captcha image.
-     */
-    public CaptchaInfoBean generateRandomCaptcha() throws Exception {
-        // we will clean the old captchas asynchronously
-        CaptchaUtil.cleanOldCaptchas();
-        return CaptchaUtil.generateCaptchaImage();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantMgtUtil.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantMgtUtil.java
deleted file mode 100644
index 48ccdfb..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantMgtUtil.java
+++ /dev/null
@@ -1,443 +0,0 @@
-/*
- * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- * http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.stratos.tenant.mgt.util;
-
-import org.apache.stratos.tenant.mgt.internal.TenantMgtServiceComponent;
-import org.apache.commons.dbcp.BasicDataSource;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.registry.core.RegistryConstants;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.jdbc.dataaccess.JDBCDataAccessManager;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.registry.core.utils.UUIDGenerator;
-import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
-import org.wso2.carbon.stratos.common.constants.StratosConstants;
-import org.wso2.carbon.stratos.common.exception.StratosException;
-import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
-import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil;
-import org.wso2.carbon.stratos.common.util.CommonUtil;
-import org.wso2.carbon.user.api.RealmConfiguration;
-import org.wso2.carbon.user.api.TenantMgtConfiguration;
-import org.wso2.carbon.user.core.UserCoreConstants;
-import org.wso2.carbon.user.core.UserRealm;
-import org.wso2.carbon.user.core.UserStoreException;
-import org.wso2.carbon.user.core.UserStoreManager;
-import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
-import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants;
-import org.wso2.carbon.user.core.tenant.Tenant;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Utility methods for tenant management.
- */
-public class TenantMgtUtil {
-
-    private static final Log log = LogFactory.getLog(TenantMgtUtil.class);
-    private static final String ILLEGAL_CHARACTERS_FOR_TENANT_DOMAIN = ".*[^a-zA-Z0-9\\._\\-].*";
-
-    /**
-     * Prepares string to show theme management page.
-     *
-     * @param tenantId - tenant id
-     * @return UUID
-     * @throws RegistryException, if failed.
-     */
-    public static String prepareStringToShowThemeMgtPage(int tenantId) throws RegistryException {
-        // first we generate a UUID
-        UserRegistry systemRegistry =
-                TenantMgtServiceComponent.getRegistryService().getGovernanceSystemRegistry();
-        String uuid = UUIDGenerator.generateUUID();
-        // store it in the registry.
-        Resource resource = systemRegistry.newResource();
-        String tenantIdStr = Integer.toString(tenantId);
-        resource.setProperty(MultitenantConstants.TENANT_ID, tenantIdStr);
-        String uuidPath = StratosConstants.TENANT_CREATION_THEME_PAGE_TOKEN
-                          + RegistryConstants.PATH_SEPARATOR + uuid;
-        systemRegistry.put(uuidPath, resource);
-
-        // restrict access
-        CommonUtil.denyAnonAuthorization(uuidPath, systemRegistry.getUserRealm());
-        return uuid;
-    }
-
-    /**
-     * Triggers adding the tenant for TenantMgtListener
-     *
-     * @param tenantInfo tenant
-     * @throws StratosException, trigger failed
-     */
-    public static void triggerAddTenant(TenantInfoBean tenantInfo) throws StratosException {
-        // initializeRegistry(tenantInfoBean.getTenantId());
-        for (TenantMgtListener tenantMgtListener :
-                TenantMgtServiceComponent.getTenantMgtListeners()) {
-            tenantMgtListener.onTenantCreate(tenantInfo);
-        }
-    }
-
-    /**
-     * Triggers an update for the tenant for TenantMgtListener
-     *
-     * @param tenantInfoBean tenantInfoBean
-     * @throws org.wso2.carbon.stratos.common.exception.StratosException, if update failed
-     */
-    public static void triggerUpdateTenant(
-            TenantInfoBean tenantInfoBean) throws StratosException {
-        for (TenantMgtListener tenantMgtListener :
-                TenantMgtServiceComponent.getTenantMgtListeners()) {
-            tenantMgtListener.onTenantUpdate(tenantInfoBean);
-        }
-    }
-    
-    public static void triggerTenantInitialActivation(
-                                  TenantInfoBean tenantInfoBean) throws StratosException {
-        for (TenantMgtListener tenantMgtListener :
-                TenantMgtServiceComponent.getTenantMgtListeners()) {
-            tenantMgtListener.onTenantInitialActivation(tenantInfoBean.getTenantId());
-        }
-    }
-    
-    public static void triggerTenantActivation(int tenantId) throws StratosException {
-        for (TenantMgtListener tenantMgtListener : 
-                TenantMgtServiceComponent.getTenantMgtListeners()) {
-            tenantMgtListener.onTenantActivation(tenantId);
-        }
-    }
-    
-    public static void triggerTenantDeactivation(int tenantId) throws StratosException {
-        for (TenantMgtListener tenantMgtListener : 
-                TenantMgtServiceComponent.getTenantMgtListeners()) {
-            tenantMgtListener.onTenantDeactivation(tenantId);
-        }
-    }
-
-    /**
-     * Validate the tenant domain
-     *
-     * @param domainName tenant domain
-     * @throws Exception , if invalid tenant domain name is given
-     */
-    public static void validateDomain(String domainName) throws Exception {
-        if (domainName == null || domainName.equals("")) {
-            String msg = "Provided domain name is empty.";
-            log.error(msg);
-            throw new Exception(msg);
-        }
-        // ensures the .ext for the public clouds.
-        if (CommonUtil.isPublicCloudSetup()) {
-            int lastIndexOfDot = domainName.lastIndexOf(".");
-            if (lastIndexOfDot <= 0) {
-                String msg = "You should have an extension to your domain.";
-                log.error(msg);
-                throw new Exception(msg);
-            }
-        }
-        int indexOfDot = domainName.indexOf(".");
-        if (indexOfDot == 0) {
-            // can't start a domain starting with ".";
-            String msg = "Invalid domain, starting with '.'";
-            log.error(msg);
-            throw new Exception(msg);
-        }
-        // check the tenant domain contains any illegal characters
-        if (domainName.matches(ILLEGAL_CHARACTERS_FOR_TENANT_DOMAIN)) {
-            String msg = "The tenant domain ' " + domainName +
-                         " ' contains one or more illegal characters. the valid characters are " +
-                         "letters, numbers, '.', '-' and '_'";
-            log.error(msg);
-            throw new Exception(msg);
-        }
-    }
-
-    /**
-     * gets the UserStoreManager for a tenant
-     *
-     * @param tenant   - a tenant
-     * @param tenantId - tenant Id. To avoid the sequences where tenant.getId() may
-     *                 produce the super tenant's tenant Id.
-     * @return UserStoreManager
-     * @throws Exception UserStoreException
-     */
-    public static UserStoreManager getUserStoreManager(Tenant tenant, int tenantId)
-            throws Exception {
-        // get the system registry for the tenant
-        RealmConfiguration realmConfig = TenantMgtServiceComponent.getBootstrapRealmConfiguration();
-        TenantMgtConfiguration tenantMgtConfiguration =
-                TenantMgtServiceComponent.getRealmService().getTenantMgtConfiguration();
-        UserRealm userRealm;
-        try {
-            MultiTenantRealmConfigBuilder builder = TenantMgtServiceComponent.getRealmService().
-                    getMultiTenantRealmConfigBuilder();
-            RealmConfiguration realmConfigToPersist = builder.
-                    getRealmConfigForTenantToPersist(realmConfig, tenantMgtConfiguration,
-                                                             tenant, tenantId);
-            RealmConfiguration realmConfigToCreate =
-                    builder.getRealmConfigForTenantToCreateRealmOnTenantCreation(
-                            realmConfig, realmConfigToPersist, tenantId);
-            userRealm = TenantMgtServiceComponent.getRealmService().
-                    getUserRealm(realmConfigToCreate);
-        } catch (UserStoreException e) {
-            String msg = "Error in creating Realm for tenant, tenant domain: " + tenant.getDomain();
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        UserStoreManager userStoreManager;
-        try {
-            userStoreManager = userRealm.getUserStoreManager();
-
-            return userStoreManager;
-        } catch (UserStoreException e) {
-            String msg = "Error in getting the userstore/authorization manager for tenant: " +
-                         tenant.getDomain();
-            log.error(msg);
-            throw new Exception(msg, e);
-        }
-    }
-
-    /**
-     * initializes tenant from the user input (tenant info bean)
-     *
-     * @param tenantInfoBean input
-     * @return tenant
-     */
-    public static Tenant initializeTenant(TenantInfoBean tenantInfoBean) {
-        Tenant tenant = new Tenant();
-        tenant.setDomain(tenantInfoBean.getTenantDomain());
-        tenant.setEmail(tenantInfoBean.getEmail());
-        tenant.setAdminName(tenantInfoBean.getAdmin());
-
-        // we are duplicating the params stored in the claims here as well; they
-        // are in Tenant class
-        // to make it work with LDAP; but they do not make it to the databases.
-        tenant.setAdminFirstName(tenantInfoBean.getFirstname());
-        tenant.setAdminLastName(tenantInfoBean.getLastname());
-
-        tenant.setAdminPassword(tenantInfoBean.getAdminPassword());
-
-        // sets created date.
-        Calendar createdDateCal = tenantInfoBean.getCreatedDate();
-        long createdDate;
-        if (createdDateCal != null) {
-            createdDate = createdDateCal.getTimeInMillis();
-        } else {
-            createdDate = System.currentTimeMillis();
-        }
-        tenant.setCreatedDate(new Date(createdDate));
-
-        if (log.isDebugEnabled()) {
-            log.debug("Tenant object Initialized from the TenantInfoBean");
-        }
-        return tenant;
-    }
-
-    /**
-     * Initializes a tenantInfoBean object for a given tenant.
-     *
-     * @param tenantId tenant id.
-     * @param tenant   a tenant.
-     * @return tenantInfoBean
-     * @throws Exception , exception in getting the adminUserName from tenantId
-     */
-    public static TenantInfoBean initializeTenantInfoBean(
-            int tenantId, Tenant tenant) throws Exception {
-        TenantInfoBean bean = getTenantInfoBeanfromTenant(tenantId, tenant);
-        if (tenant != null) {
-            bean.setAdmin(ClaimsMgtUtil.getAdminUserNameFromTenantId(
-                    TenantMgtServiceComponent.getRealmService(), tenantId));
-        }
-        return bean;
-    }
-
-    /**
-     * initializes a TenantInfoBean object from the tenant
-     * @param tenantId, tenant id
-     * @param tenant, tenant
-     * @return TenantInfoBean.
-     */
-    public static TenantInfoBean getTenantInfoBeanfromTenant(int tenantId, Tenant tenant) {
-        TenantInfoBean bean = new TenantInfoBean();
-        if (tenant != null) {
-            bean.setTenantId(tenantId);
-            bean.setTenantDomain(tenant.getDomain());
-            bean.setEmail(tenant.getEmail());
-
-            /*gets the created date*/
-            Calendar createdDate = Calendar.getInstance();
-            createdDate.setTimeInMillis(tenant.getCreatedDate().getTime());
-            bean.setCreatedDate(createdDate);
-
-            bean.setActive(tenant.isActive());
-            if(log.isDebugEnabled()) {
-                log.debug("The TenantInfoBean object has been created from the tenant.");
-            }
-        } else {
-            if(log.isDebugEnabled()) {
-                log.debug("The tenant is null.");
-            }
-        }
-        return bean;
-    }
-
-    /**
-     * Adds claims to UserStoreManager
-     *
-     * @param tenant a tenant
-     * @throws Exception if error in adding claims to the user.
-     */
-    public static void addClaimsToUserStoreManager(Tenant tenant) throws Exception {
-        try {
-            Map<String, String> claimsMap = new HashMap<String, String>();
-
-            claimsMap.put(UserCoreConstants.ClaimTypeURIs.GIVEN_NAME, tenant.getAdminFirstName());
-            claimsMap.put(UserCoreConstants.ClaimTypeURIs.SURNAME, tenant.getAdminLastName());
-
-            // can be extended to store other user information.
-            UserStoreManager userStoreManager =
-                    (UserStoreManager) TenantMgtServiceComponent.getRealmService().
-                            getTenantUserRealm(tenant.getId()).getUserStoreManager();
-            userStoreManager.setUserClaimValues(tenant.getAdminName(), claimsMap,
-                                                UserCoreConstants.DEFAULT_PROFILE);
-
-        } catch (Exception e) {
-            String msg = "Error in adding claims to the user.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-    }
-
-    /**
-     * Activate a tenant during the time of the tenant creation.
-     *
-     * @param tenantInfoBean tenant information
-     * @param tenantId tenant Id
-     * @throws Exception UserStoreException.
-     */
-    public static void activateTenantInitially(TenantInfoBean tenantInfoBean,
-                                               int tenantId) throws Exception {
-        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
-        String tenantDomain = tenantInfoBean.getTenantDomain();
-
-        TenantMgtUtil.activateTenant(tenantDomain, tenantManager, tenantId);
-        if (log.isDebugEnabled()) {
-            log.debug("Activated the tenant " + tenantDomain + " at the time of tenant creation");
-        }
-
-        //Notify tenant activation
-        try {
-            TenantMgtUtil.triggerTenantInitialActivation(tenantInfoBean);
-        } catch (StratosException e) {
-            String msg = "Error in notifying tenant initial activation.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-    }
-
-    /**
-     * Activate the given tenant, either at the time of tenant creation, or later by super admin.
-     *
-     * @param tenantDomain tenant domain
-     * @param tenantManager TenantManager object
-     * @param tenantId tenant Id
-     * @throws Exception UserStoreException.
-     */
-    public static void activateTenant(String tenantDomain, TenantManager tenantManager,
-                                      int tenantId) throws Exception {
-        try {
-            tenantManager.activateTenant(tenantId);
-        } catch (UserStoreException e) {
-            String msg = "Error in activating the tenant for tenant domain: " + tenantDomain + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        //activating the subscription
-        /*try {
-            if (TenantMgtServiceComponent.getBillingService() != null) {
-                TenantMgtServiceComponent.getBillingService().activateUsagePlan(tenantDomain);
-            }
-        } catch (Exception e) {
-            String msg = "Error while activating subscription for domain: " + tenantDomain + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }*/
-    }
-
-    /**
-     * Deactivate the given tenant, by super admin.
-     *
-     * @param tenantDomain tenant domain
-     * @param tenantManager TenantManager object
-     * @param tenantId tenant Id
-     * @throws Exception UserStoreException.
-     */
-    public static void deactivateTenant(String tenantDomain, TenantManager tenantManager,
-                                        int tenantId) throws Exception {
-        try {
-            tenantManager.deactivateTenant(tenantId);
-        } catch (UserStoreException e) {
-            String msg = "Error in deactivating tenant for tenant domain: " + tenantDomain + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-
-        //deactivating the subscription
-        /*try {
-            if (TenantMgtServiceComponent.getBillingService() != null) {
-                TenantMgtServiceComponent.getBillingService().deactivateActiveUsagePlan(tenantDomain);
-            }
-        } catch (Exception e) {
-            String msg = "Error while deactivating subscription for domain: " + tenantDomain + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }*/
-    }
-
-    public static void deleteTenantRegistryData(int tenantId) throws Exception {
-        // delete data from mounted config registry database
-        JDBCDataAccessManager configMgr = (JDBCDataAccessManager) TenantMgtServiceComponent.getRegistryService().
-                getConfigUserRegistry().getRegistryContext().getDataAccessManager();
-        TenantRegistryDataDeletionUtil.deleteTenantRegistryData(tenantId, configMgr.getDataSource().getConnection());
-
-        // delete data from mounted governance registry database
-        JDBCDataAccessManager govMgr = (JDBCDataAccessManager) TenantMgtServiceComponent.getRegistryService().
-                getGovernanceUserRegistry().getRegistryContext().getDataAccessManager();
-        TenantRegistryDataDeletionUtil.deleteTenantRegistryData(tenantId, govMgr.getDataSource().getConnection());
-
-    }
-
-    public static void deleteTenantUMData(int tenantId) throws Exception {
-        RealmConfiguration realmConfig = TenantMgtServiceComponent.getRealmService().
-                getBootstrapRealmConfiguration();
-        BasicDataSource dataSource = new BasicDataSource();
-        dataSource.setDriverClassName(realmConfig.getRealmProperty(JDBCRealmConstants.DRIVER_NAME));
-        dataSource.setUrl(realmConfig.getRealmProperty(JDBCRealmConstants.URL));
-        dataSource.setUsername(realmConfig.getRealmProperty(JDBCRealmConstants.USER_NAME));
-        dataSource.setPassword(realmConfig.getRealmProperty(JDBCRealmConstants.PASSWORD));
-        dataSource.setMaxActive(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_ACTIVE)));
-        dataSource.setMinIdle(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MIN_IDLE)));
-        dataSource.setMaxWait(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_WAIT)));
-
-        TenantUMDataDeletionUtil.deleteTenantUMData(tenantId, dataSource.getConnection());
-    }
-}


[02/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/TenantSelfRegistrationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/TenantSelfRegistrationService.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/TenantSelfRegistrationService.java
new file mode 100644
index 0000000..0f18ed1
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/TenantSelfRegistrationService.java
@@ -0,0 +1,193 @@
+/*
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.tenant.mgt.services;
+
+import org.wso2.carbon.captcha.mgt.beans.CaptchaInfoBean;
+import org.wso2.carbon.captcha.mgt.constants.CaptchaMgtConstants;
+import org.wso2.carbon.captcha.mgt.util.CaptchaUtil;
+import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
+import org.apache.stratos.common.beans.TenantInfoBean;
+import org.apache.stratos.common.exception.StratosException;
+import org.apache.stratos.common.util.CommonUtil;
+import org.apache.stratos.tenant.mgt.internal.TenantMgtServiceComponent;
+import org.apache.stratos.tenant.mgt.util.TenantMgtUtil;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import org.apache.axis2.AxisFault;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+
+/**
+ * TenantSelfRegistration - This is the Web service that will be called when
+ * tenants register themselves
+ */
+public class TenantSelfRegistrationService {
+    private static final Log log = LogFactory.getLog(TenantSelfRegistrationService.class);
+
+    /**
+     * Registers a tenant - Tenant Self Registration
+     *
+     * @param tenantInfoBean  - tenantInformation
+     * @param captchaInfoBean - captchaInformation
+     * @return String UUID
+     * @throws Exception if the tenant registration fails.
+     */
+    public String registerTenant(TenantInfoBean tenantInfoBean, CaptchaInfoBean captchaInfoBean)
+            throws Exception {
+        // validate the email
+        try {
+            CommonUtil.validateEmail(tenantInfoBean.getEmail());
+        } catch (Exception e) {
+            String msg = "Invalid email is provided.";
+            log.error(msg, e);
+            throw new AxisFault(msg);
+        }
+        // validate the domain
+        String domainName = tenantInfoBean.getTenantDomain();
+        try {
+            TenantMgtUtil.validateDomain(domainName);
+        } catch (Exception e) {
+            String msg = "Domain Validation Failed.";
+            log.error(msg, e);
+            throw new AxisFault(msg);
+        }
+        // validate the first/last names
+        String firstname = tenantInfoBean.getFirstname();
+        String lastname = tenantInfoBean.getLastname();
+        try {
+            CommonUtil.validateName(firstname, "First Name");
+            CommonUtil.validateName(lastname, "Last Name");
+        } catch (Exception e) {
+            String msg = "First/Last Name Validation Failed.";
+            log.error(msg, e);
+            throw new AxisFault(msg);
+        } // now validate the captcha
+        try {
+            CaptchaUtil.validateCaptcha(captchaInfoBean);
+            if (log.isDebugEnabled()) {
+                log.debug("Captcha Successfully Validated.");
+            }
+        } catch (Exception e) {
+            String msg = CaptchaMgtConstants.CAPTCHA_ERROR_MSG;
+            log.error(msg, e);
+            throw new AxisFault(msg);
+        } finally {
+            try {
+                CaptchaUtil.cleanCaptcha(captchaInfoBean.getSecretKey());
+            } catch (Exception e) {
+                String msg = "Error in cleaning captcha. ";
+                log.error(msg, e);
+                // not throwing the exception in finally more up.
+            }
+        }
+        // persists the tenant.
+        Tenant tenant = TenantMgtUtil.initializeTenant(tenantInfoBean);
+        TenantPersistor persistor = TenantMgtServiceComponent.getTenantPersistor();
+        int tenantId = persistor.persistTenant(tenant, true, tenantInfoBean.getSuccessKey(), 
+                tenantInfoBean.getOriginatedService());
+        tenantInfoBean.setTenantId(tenantId);
+        TenantMgtUtil.addClaimsToUserStoreManager(tenant);
+        
+        //Notify tenant addition
+        try {
+            TenantMgtUtil.triggerAddTenant(tenantInfoBean);
+        } catch (StratosException e) {
+            String msg = "Error in notifying tenant addition.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        //adding the subscription entry
+        try {
+            if (TenantMgtServiceComponent.getBillingService() != null) {
+                TenantMgtServiceComponent.getBillingService().addUsagePlan(tenant,
+                        tenantInfoBean.getUsagePlan());
+                if (log.isDebugEnabled()) {
+                    log.debug("Subscription added successfully for the tenant: " +
+                              tenantInfoBean.getTenantDomain());
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while adding the subscription for tenant: " + domainName;
+            log.error(msg, e);
+        }
+
+        // If Email Validation is made optional, tenant will be activated now.
+        if (CommonUtil.isTenantManagementEmailsDisabled() ||
+                !CommonUtil.isEmailValidationMandatory()) {
+            TenantMgtUtil.activateTenantInitially(tenantInfoBean, tenantId);
+        }
+        return TenantMgtUtil.prepareStringToShowThemeMgtPage(tenant.getId());
+    }
+
+    /**
+     * Check if the selected domain is available to register
+     *
+     * @param domainName domain name
+     * @return true, if the domain is available to register
+     * @throws Exception, if unable to get the tenant manager, or get the tenant id
+     *                    from manager.
+     */
+    public boolean checkDomainAvailability(String domainName) throws Exception {
+        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
+        int tenantId = tenantManager.getTenantId(domainName);
+        if (log.isDebugEnabled()) {
+            log.debug("Tenant Domain is available to register.");
+        }
+        return tenantId < 0; // no tenant exists with the same tenant domain
+    }
+
+    // use a boolean instead of string.
+
+    /**
+     * Validates or Suggests a domain.
+     *
+     * @param domain     tenant domain
+     * @param successKey success key
+     * @return domain name
+     * @throws Exception if exception in validating or suggesting the tenant domain.
+     */
+    public String validateOrSuggestDomain(String domain, String successKey) throws Exception {
+        if (successKey != null && !successKey.equals("")) {
+            if (CommonUtil.validateDomainFromSuccessKey(
+                    TenantMgtServiceComponent.getGovernanceSystemRegistry(
+                            MultitenantConstants.SUPER_TENANT_ID), domain, successKey)) {
+                return domain;
+            }
+        }
+        // otherwise domain is not correct
+
+        return "null";
+    }
+
+    /**
+     * Generates a random Captcha
+     *
+     * @return captchaInfoBean
+     * @throws Exception, if exception in cleaning old captchas or generating new
+     *                    captcha image.
+     */
+    public CaptchaInfoBean generateRandomCaptcha() throws Exception {
+        // we will clean the old captchas asynchronously
+        CaptchaUtil.cleanOldCaptchas();
+        return CaptchaUtil.generateCaptchaImage();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantMgtUtil.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantMgtUtil.java
new file mode 100644
index 0000000..36d7507
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantMgtUtil.java
@@ -0,0 +1,443 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stratos.tenant.mgt.util;
+
+import org.apache.stratos.tenant.mgt.internal.TenantMgtServiceComponent;
+import org.apache.commons.dbcp.BasicDataSource;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.jdbc.dataaccess.JDBCDataAccessManager;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.registry.core.utils.UUIDGenerator;
+import org.apache.stratos.common.beans.TenantInfoBean;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.exception.StratosException;
+import org.apache.stratos.common.listeners.TenantMgtListener;
+import org.apache.stratos.common.util.ClaimsMgtUtil;
+import org.apache.stratos.common.util.CommonUtil;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.api.TenantMgtConfiguration;
+import org.wso2.carbon.user.core.UserCoreConstants;
+import org.wso2.carbon.user.core.UserRealm;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.UserStoreManager;
+import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
+import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Utility methods for tenant management.
+ */
+public class TenantMgtUtil {
+
+    private static final Log log = LogFactory.getLog(TenantMgtUtil.class);
+    private static final String ILLEGAL_CHARACTERS_FOR_TENANT_DOMAIN = ".*[^a-zA-Z0-9\\._\\-].*";
+
+    /**
+     * Prepares string to show theme management page.
+     *
+     * @param tenantId - tenant id
+     * @return UUID
+     * @throws RegistryException, if failed.
+     */
+    public static String prepareStringToShowThemeMgtPage(int tenantId) throws RegistryException {
+        // first we generate a UUID
+        UserRegistry systemRegistry =
+                TenantMgtServiceComponent.getRegistryService().getGovernanceSystemRegistry();
+        String uuid = UUIDGenerator.generateUUID();
+        // store it in the registry.
+        Resource resource = systemRegistry.newResource();
+        String tenantIdStr = Integer.toString(tenantId);
+        resource.setProperty(MultitenantConstants.TENANT_ID, tenantIdStr);
+        String uuidPath = StratosConstants.TENANT_CREATION_THEME_PAGE_TOKEN
+                          + RegistryConstants.PATH_SEPARATOR + uuid;
+        systemRegistry.put(uuidPath, resource);
+
+        // restrict access
+        CommonUtil.denyAnonAuthorization(uuidPath, systemRegistry.getUserRealm());
+        return uuid;
+    }
+
+    /**
+     * Triggers adding the tenant for TenantMgtListener
+     *
+     * @param tenantInfo tenant
+     * @throws StratosException, trigger failed
+     */
+    public static void triggerAddTenant(TenantInfoBean tenantInfo) throws StratosException {
+        // initializeRegistry(tenantInfoBean.getTenantId());
+        for (TenantMgtListener tenantMgtListener :
+                TenantMgtServiceComponent.getTenantMgtListeners()) {
+            tenantMgtListener.onTenantCreate(tenantInfo);
+        }
+    }
+
+    /**
+     * Triggers an update for the tenant for TenantMgtListener
+     *
+     * @param tenantInfoBean tenantInfoBean
+     * @throws org.wso2.carbon.stratos.common.exception.StratosException, if update failed
+     */
+    public static void triggerUpdateTenant(
+            TenantInfoBean tenantInfoBean) throws StratosException {
+        for (TenantMgtListener tenantMgtListener :
+                TenantMgtServiceComponent.getTenantMgtListeners()) {
+            tenantMgtListener.onTenantUpdate(tenantInfoBean);
+        }
+    }
+    
+    public static void triggerTenantInitialActivation(
+                                  TenantInfoBean tenantInfoBean) throws StratosException {
+        for (TenantMgtListener tenantMgtListener :
+                TenantMgtServiceComponent.getTenantMgtListeners()) {
+            tenantMgtListener.onTenantInitialActivation(tenantInfoBean.getTenantId());
+        }
+    }
+    
+    public static void triggerTenantActivation(int tenantId) throws StratosException {
+        for (TenantMgtListener tenantMgtListener : 
+                TenantMgtServiceComponent.getTenantMgtListeners()) {
+            tenantMgtListener.onTenantActivation(tenantId);
+        }
+    }
+    
+    public static void triggerTenantDeactivation(int tenantId) throws StratosException {
+        for (TenantMgtListener tenantMgtListener : 
+                TenantMgtServiceComponent.getTenantMgtListeners()) {
+            tenantMgtListener.onTenantDeactivation(tenantId);
+        }
+    }
+
+    /**
+     * Validate the tenant domain
+     *
+     * @param domainName tenant domain
+     * @throws Exception , if invalid tenant domain name is given
+     */
+    public static void validateDomain(String domainName) throws Exception {
+        if (domainName == null || domainName.equals("")) {
+            String msg = "Provided domain name is empty.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        // ensures the .ext for the public clouds.
+        if (CommonUtil.isPublicCloudSetup()) {
+            int lastIndexOfDot = domainName.lastIndexOf(".");
+            if (lastIndexOfDot <= 0) {
+                String msg = "You should have an extension to your domain.";
+                log.error(msg);
+                throw new Exception(msg);
+            }
+        }
+        int indexOfDot = domainName.indexOf(".");
+        if (indexOfDot == 0) {
+            // can't start a domain starting with ".";
+            String msg = "Invalid domain, starting with '.'";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        // check the tenant domain contains any illegal characters
+        if (domainName.matches(ILLEGAL_CHARACTERS_FOR_TENANT_DOMAIN)) {
+            String msg = "The tenant domain ' " + domainName +
+                         " ' contains one or more illegal characters. the valid characters are " +
+                         "letters, numbers, '.', '-' and '_'";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+    }
+
+    /**
+     * gets the UserStoreManager for a tenant
+     *
+     * @param tenant   - a tenant
+     * @param tenantId - tenant Id. To avoid the sequences where tenant.getId() may
+     *                 produce the super tenant's tenant Id.
+     * @return UserStoreManager
+     * @throws Exception UserStoreException
+     */
+    public static UserStoreManager getUserStoreManager(Tenant tenant, int tenantId)
+            throws Exception {
+        // get the system registry for the tenant
+        RealmConfiguration realmConfig = TenantMgtServiceComponent.getBootstrapRealmConfiguration();
+        TenantMgtConfiguration tenantMgtConfiguration =
+                TenantMgtServiceComponent.getRealmService().getTenantMgtConfiguration();
+        UserRealm userRealm;
+        try {
+            MultiTenantRealmConfigBuilder builder = TenantMgtServiceComponent.getRealmService().
+                    getMultiTenantRealmConfigBuilder();
+            RealmConfiguration realmConfigToPersist = builder.
+                    getRealmConfigForTenantToPersist(realmConfig, tenantMgtConfiguration,
+                                                             tenant, tenantId);
+            RealmConfiguration realmConfigToCreate =
+                    builder.getRealmConfigForTenantToCreateRealmOnTenantCreation(
+                            realmConfig, realmConfigToPersist, tenantId);
+            userRealm = TenantMgtServiceComponent.getRealmService().
+                    getUserRealm(realmConfigToCreate);
+        } catch (UserStoreException e) {
+            String msg = "Error in creating Realm for tenant, tenant domain: " + tenant.getDomain();
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        UserStoreManager userStoreManager;
+        try {
+            userStoreManager = userRealm.getUserStoreManager();
+
+            return userStoreManager;
+        } catch (UserStoreException e) {
+            String msg = "Error in getting the userstore/authorization manager for tenant: " +
+                         tenant.getDomain();
+            log.error(msg);
+            throw new Exception(msg, e);
+        }
+    }
+
+    /**
+     * initializes tenant from the user input (tenant info bean)
+     *
+     * @param tenantInfoBean input
+     * @return tenant
+     */
+    public static Tenant initializeTenant(TenantInfoBean tenantInfoBean) {
+        Tenant tenant = new Tenant();
+        tenant.setDomain(tenantInfoBean.getTenantDomain());
+        tenant.setEmail(tenantInfoBean.getEmail());
+        tenant.setAdminName(tenantInfoBean.getAdmin());
+
+        // we are duplicating the params stored in the claims here as well; they
+        // are in Tenant class
+        // to make it work with LDAP; but they do not make it to the databases.
+        tenant.setAdminFirstName(tenantInfoBean.getFirstname());
+        tenant.setAdminLastName(tenantInfoBean.getLastname());
+
+        tenant.setAdminPassword(tenantInfoBean.getAdminPassword());
+
+        // sets created date.
+        Calendar createdDateCal = tenantInfoBean.getCreatedDate();
+        long createdDate;
+        if (createdDateCal != null) {
+            createdDate = createdDateCal.getTimeInMillis();
+        } else {
+            createdDate = System.currentTimeMillis();
+        }
+        tenant.setCreatedDate(new Date(createdDate));
+
+        if (log.isDebugEnabled()) {
+            log.debug("Tenant object Initialized from the TenantInfoBean");
+        }
+        return tenant;
+    }
+
+    /**
+     * Initializes a tenantInfoBean object for a given tenant.
+     *
+     * @param tenantId tenant id.
+     * @param tenant   a tenant.
+     * @return tenantInfoBean
+     * @throws Exception , exception in getting the adminUserName from tenantId
+     */
+    public static TenantInfoBean initializeTenantInfoBean(
+            int tenantId, Tenant tenant) throws Exception {
+        TenantInfoBean bean = getTenantInfoBeanfromTenant(tenantId, tenant);
+        if (tenant != null) {
+            bean.setAdmin(ClaimsMgtUtil.getAdminUserNameFromTenantId(
+                    TenantMgtServiceComponent.getRealmService(), tenantId));
+        }
+        return bean;
+    }
+
+    /**
+     * initializes a TenantInfoBean object from the tenant
+     * @param tenantId, tenant id
+     * @param tenant, tenant
+     * @return TenantInfoBean.
+     */
+    public static TenantInfoBean getTenantInfoBeanfromTenant(int tenantId, Tenant tenant) {
+        TenantInfoBean bean = new TenantInfoBean();
+        if (tenant != null) {
+            bean.setTenantId(tenantId);
+            bean.setTenantDomain(tenant.getDomain());
+            bean.setEmail(tenant.getEmail());
+
+            /*gets the created date*/
+            Calendar createdDate = Calendar.getInstance();
+            createdDate.setTimeInMillis(tenant.getCreatedDate().getTime());
+            bean.setCreatedDate(createdDate);
+
+            bean.setActive(tenant.isActive());
+            if(log.isDebugEnabled()) {
+                log.debug("The TenantInfoBean object has been created from the tenant.");
+            }
+        } else {
+            if(log.isDebugEnabled()) {
+                log.debug("The tenant is null.");
+            }
+        }
+        return bean;
+    }
+
+    /**
+     * Adds claims to UserStoreManager
+     *
+     * @param tenant a tenant
+     * @throws Exception if error in adding claims to the user.
+     */
+    public static void addClaimsToUserStoreManager(Tenant tenant) throws Exception {
+        try {
+            Map<String, String> claimsMap = new HashMap<String, String>();
+
+            claimsMap.put(UserCoreConstants.ClaimTypeURIs.GIVEN_NAME, tenant.getAdminFirstName());
+            claimsMap.put(UserCoreConstants.ClaimTypeURIs.SURNAME, tenant.getAdminLastName());
+
+            // can be extended to store other user information.
+            UserStoreManager userStoreManager =
+                    (UserStoreManager) TenantMgtServiceComponent.getRealmService().
+                            getTenantUserRealm(tenant.getId()).getUserStoreManager();
+            userStoreManager.setUserClaimValues(tenant.getAdminName(), claimsMap,
+                                                UserCoreConstants.DEFAULT_PROFILE);
+
+        } catch (Exception e) {
+            String msg = "Error in adding claims to the user.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+    }
+
+    /**
+     * Activate a tenant during the time of the tenant creation.
+     *
+     * @param tenantInfoBean tenant information
+     * @param tenantId tenant Id
+     * @throws Exception UserStoreException.
+     */
+    public static void activateTenantInitially(TenantInfoBean tenantInfoBean,
+                                               int tenantId) throws Exception {
+        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
+        String tenantDomain = tenantInfoBean.getTenantDomain();
+
+        TenantMgtUtil.activateTenant(tenantDomain, tenantManager, tenantId);
+        if (log.isDebugEnabled()) {
+            log.debug("Activated the tenant " + tenantDomain + " at the time of tenant creation");
+        }
+
+        //Notify tenant activation
+        try {
+            TenantMgtUtil.triggerTenantInitialActivation(tenantInfoBean);
+        } catch (StratosException e) {
+            String msg = "Error in notifying tenant initial activation.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+    }
+
+    /**
+     * Activate the given tenant, either at the time of tenant creation, or later by super admin.
+     *
+     * @param tenantDomain tenant domain
+     * @param tenantManager TenantManager object
+     * @param tenantId tenant Id
+     * @throws Exception UserStoreException.
+     */
+    public static void activateTenant(String tenantDomain, TenantManager tenantManager,
+                                      int tenantId) throws Exception {
+        try {
+            tenantManager.activateTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg = "Error in activating the tenant for tenant domain: " + tenantDomain + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        //activating the subscription
+        /*try {
+            if (TenantMgtServiceComponent.getBillingService() != null) {
+                TenantMgtServiceComponent.getBillingService().activateUsagePlan(tenantDomain);
+            }
+        } catch (Exception e) {
+            String msg = "Error while activating subscription for domain: " + tenantDomain + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }*/
+    }
+
+    /**
+     * Deactivate the given tenant, by super admin.
+     *
+     * @param tenantDomain tenant domain
+     * @param tenantManager TenantManager object
+     * @param tenantId tenant Id
+     * @throws Exception UserStoreException.
+     */
+    public static void deactivateTenant(String tenantDomain, TenantManager tenantManager,
+                                        int tenantId) throws Exception {
+        try {
+            tenantManager.deactivateTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg = "Error in deactivating tenant for tenant domain: " + tenantDomain + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        //deactivating the subscription
+        /*try {
+            if (TenantMgtServiceComponent.getBillingService() != null) {
+                TenantMgtServiceComponent.getBillingService().deactivateActiveUsagePlan(tenantDomain);
+            }
+        } catch (Exception e) {
+            String msg = "Error while deactivating subscription for domain: " + tenantDomain + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }*/
+    }
+
+    public static void deleteTenantRegistryData(int tenantId) throws Exception {
+        // delete data from mounted config registry database
+        JDBCDataAccessManager configMgr = (JDBCDataAccessManager) TenantMgtServiceComponent.getRegistryService().
+                getConfigUserRegistry().getRegistryContext().getDataAccessManager();
+        TenantRegistryDataDeletionUtil.deleteTenantRegistryData(tenantId, configMgr.getDataSource().getConnection());
+
+        // delete data from mounted governance registry database
+        JDBCDataAccessManager govMgr = (JDBCDataAccessManager) TenantMgtServiceComponent.getRegistryService().
+                getGovernanceUserRegistry().getRegistryContext().getDataAccessManager();
+        TenantRegistryDataDeletionUtil.deleteTenantRegistryData(tenantId, govMgr.getDataSource().getConnection());
+
+    }
+
+    public static void deleteTenantUMData(int tenantId) throws Exception {
+        RealmConfiguration realmConfig = TenantMgtServiceComponent.getRealmService().
+                getBootstrapRealmConfiguration();
+        BasicDataSource dataSource = new BasicDataSource();
+        dataSource.setDriverClassName(realmConfig.getRealmProperty(JDBCRealmConstants.DRIVER_NAME));
+        dataSource.setUrl(realmConfig.getRealmProperty(JDBCRealmConstants.URL));
+        dataSource.setUsername(realmConfig.getRealmProperty(JDBCRealmConstants.USER_NAME));
+        dataSource.setPassword(realmConfig.getRealmProperty(JDBCRealmConstants.PASSWORD));
+        dataSource.setMaxActive(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_ACTIVE)));
+        dataSource.setMinIdle(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MIN_IDLE)));
+        dataSource.setMaxWait(Integer.parseInt(realmConfig.getRealmProperty(JDBCRealmConstants.MAX_WAIT)));
+
+        TenantUMDataDeletionUtil.deleteTenantUMData(tenantId, dataSource.getConnection());
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantRegistryDataDeletionUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantRegistryDataDeletionUtil.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantRegistryDataDeletionUtil.java
new file mode 100644
index 0000000..f640c65
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantRegistryDataDeletionUtil.java
@@ -0,0 +1,119 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.stratos.tenant.mgt.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+
+public class TenantRegistryDataDeletionUtil {
+    public static final Log log = LogFactory.getLog(TenantRegistryDataDeletionUtil.class);
+    
+    /**
+     * Delete all tenant information related to tenant stored in REG tables
+     * @param tenantId id of tenant whose data should be deleted
+     * @param conn database connection object
+     * @throws SQLException thrown if an error occurs while executing the queries 
+     */
+    public static void deleteTenantRegistryData(int tenantId, Connection conn) throws Exception {
+        try {
+            conn.setAutoCommit(false);
+            String deleteClusterLockSql = "DELETE FROM REG_CLUSTER_LOCK WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteClusterLockSql, tenantId);
+
+            String deleteLogSql = "DELETE FROM REG_LOG WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteLogSql, tenantId);
+
+            String deleteAssociationSql = "DELETE FROM REG_ASSOCIATION WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteAssociationSql, tenantId);
+
+            String deleteSnapshotSql = "DELETE FROM REG_SNAPSHOT WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteSnapshotSql, tenantId);
+
+            String deleteResourceCommentSql = "DELETE FROM REG_RESOURCE_COMMENT WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteResourceCommentSql, tenantId);
+
+            String deleteCommentSql = "DELETE FROM REG_COMMENT WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteCommentSql, tenantId);
+
+            String deleteResourceRatingSql = "DELETE FROM REG_RESOURCE_RATING WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteResourceRatingSql, tenantId);
+
+            String deleteRatingSql = "DELETE FROM REG_RATING WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteRatingSql, tenantId);
+
+            String deleteResourceTagSql = "DELETE FROM REG_RESOURCE_TAG WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteResourceTagSql, tenantId);
+
+            String deleteTagSql = "DELETE FROM REG_TAG WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteTagSql, tenantId);
+
+            String deleteResourcePropertySql = "DELETE FROM REG_RESOURCE_PROPERTY WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteResourcePropertySql, tenantId);
+
+            String deletePropertySql = "DELETE FROM REG_PROPERTY WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deletePropertySql, tenantId);
+
+            String deleteResourceHistorySql = "DELETE FROM REG_RESOURCE_HISTORY WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteResourceHistorySql, tenantId);
+
+            String deleteContentHistorySql = "DELETE FROM REG_CONTENT_HISTORY WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteContentHistorySql, tenantId);
+
+            String deleteResourceSql = "DELETE FROM REG_RESOURCE WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteResourceSql, tenantId);
+
+            String deleteContentSql = "DELETE FROM REG_CONTENT WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteContentSql, tenantId);
+
+            String deletePathSql = "DELETE FROM REG_PATH WHERE REG_TENANT_ID = ?";
+            executeDeleteQuery(conn, deletePathSql, tenantId);
+
+            conn.commit();
+        } catch (SQLException e) {
+            conn.rollback();
+            String errorMsg = "An error occurred while deleting registry data for tenant: " + tenantId;
+            log.error(errorMsg, e);
+            throw new Exception(errorMsg, e);
+        } finally {
+            conn.close();
+        }
+    }
+
+    private static void executeDeleteQuery(Connection conn, String query, int tenantId)
+            throws Exception {
+        PreparedStatement ps = null;
+        try {
+            ps = conn.prepareStatement(query);
+            ps.setInt(1, tenantId);
+            ps.executeUpdate();
+        } catch (SQLException e) {
+            String errMsg = "Error executing query " + query + " for tenant: " + tenantId;
+            log.error(errMsg, e);
+            throw new Exception(errMsg, e);
+        } finally {
+            if (ps != null) {
+                ps.close();
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantUMDataDeletionUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantUMDataDeletionUtil.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantUMDataDeletionUtil.java
new file mode 100644
index 0000000..d857e38
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/util/TenantUMDataDeletionUtil.java
@@ -0,0 +1,112 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.tenant.mgt.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+
+public class TenantUMDataDeletionUtil {
+    public static final Log log = LogFactory.getLog(TenantUMDataDeletionUtil.class);
+
+    /**
+     * Delete all tenant information related to tenant stored in UM tables
+     * @param tenantId id of tenant whose data should be deleted
+     * @param conn database connection object
+     * @throws SQLException thrown if an error occurs while executing the queries
+     */
+    public static void deleteTenantUMData(int tenantId, Connection conn) throws Exception {
+        try {
+            conn.setAutoCommit(false);
+            String deleteUserPermissionSql = "DELETE FROM UM_USER_PERMISSION WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteUserPermissionSql, tenantId);
+
+            String deleteRolePermissionSql = "DELETE FROM UM_ROLE_PERMISSION WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteRolePermissionSql, tenantId);
+
+            String deletePermissionSql = "DELETE FROM UM_PERMISSION WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deletePermissionSql, tenantId);
+
+            String deleteClaimBehaviourSql = "DELETE FROM UM_CLAIM_BEHAVIOR WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteClaimBehaviourSql, tenantId);
+
+            String deleteProfileConfigSql = "DELETE FROM UM_PROFILE_CONFIG WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteProfileConfigSql, tenantId);
+
+            String deleteClaimSql = "DELETE FROM UM_CLAIM WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteClaimSql, tenantId);
+
+            String deleteDialectSql = "DELETE FROM UM_DIALECT WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteDialectSql, tenantId);
+
+            String deleteUserAttributeSql = "DELETE FROM UM_USER_ATTRIBUTE WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteUserAttributeSql, tenantId);
+
+            String deleteHybridUserRoleSql = "DELETE FROM UM_HYBRID_USER_ROLE WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteHybridUserRoleSql, tenantId);
+
+            String deleteHybridRoleSql = "DELETE FROM UM_HYBRID_ROLE WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteHybridRoleSql, tenantId);
+
+            String deleteHybridRememberMeSql = "DELETE FROM UM_HYBRID_REMEMBER_ME WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteHybridRememberMeSql, tenantId);
+
+            String deleteUserRoleSql = "DELETE FROM UM_USER_ROLE WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteUserRoleSql, tenantId);
+
+            String deleteRoleSql = "DELETE FROM UM_ROLE WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteRoleSql, tenantId);
+
+            String deleteUserSql = "DELETE FROM UM_USER WHERE UM_TENANT_ID = ?";
+            executeDeleteQuery(conn, deleteUserSql, tenantId);
+
+            String deleteTenantSql = "DELETE FROM UM_TENANT WHERE UM_ID = ?";
+            executeDeleteQuery(conn, deleteTenantSql, tenantId);
+
+            conn.commit();
+        } catch (Exception e) {
+            conn.rollback();
+            String errorMsg = "An error occurred while deleting registry data for tenant: " + tenantId;
+            log.error(errorMsg, e);
+            throw new Exception(errorMsg, e);
+        } finally {
+            conn.close();
+        }
+    }
+
+    private static void executeDeleteQuery(Connection conn, String query, int tenantId)
+            throws Exception {
+        PreparedStatement ps = null;
+        try {
+            ps = conn.prepareStatement(query);
+            ps.setInt(1, tenantId);
+            ps.executeUpdate();
+        } catch (SQLException e) {
+            String errMsg = "Error executing query " + query + " for tenant: " + tenantId;
+            log.error(errMsg, e);
+            throw new Exception(errMsg, e);
+        } finally {
+            if (ps != null) {
+                ps.close();
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/resources/META-INF/component.xml b/components/org.apache.stratos.tenant.mgt/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..883930f
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/resources/META-INF/component.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+  ~
+  ~  Licensed under the Apache License, Version 2.0 (the "License");
+  ~  you may not use this file except in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~       http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing, software
+  ~  distributed under the License is distributed on an "AS IS" BASIS,
+  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~  See the License for the specific language governing permissions and
+  ~  limitations under the License.
+  -->
+
+<component xmlns="http://products.wso2.org/carbon">
+    <ManagementPermissions>
+        <ManagementPermission>
+            <DisplayName>Manage</DisplayName>
+            <ResourceId>/permission/protected/manage</ResourceId>
+        </ManagementPermission>
+        <ManagementPermission>
+            <DisplayName>Monitor</DisplayName>
+            <ResourceId>/permission/protected/manage/monitor</ResourceId>
+        </ManagementPermission>
+        <ManagementPermission>
+            <DisplayName>Tenants</DisplayName>
+            <ResourceId>/permission/protected/manage/monitor/tenants</ResourceId>
+        </ManagementPermission>
+        <ManagementPermission>
+            <DisplayName>Modify</DisplayName>
+            <ResourceId>/permission/protected/manage/modify</ResourceId>
+        </ManagementPermission>
+        <ManagementPermission>
+            <DisplayName>Tenants</DisplayName>
+            <ResourceId>/permission/protected/manage/modify/tenants</ResourceId>
+        </ManagementPermission>
+   </ManagementPermissions>
+</component>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.tenant.mgt/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..7e87c44
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/resources/META-INF/services.xml
@@ -0,0 +1,155 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ !
+ ! Copyright 2006 The Apache Software Foundation.
+ !
+ ! Licensed under the Apache License, Version 2.0 (the "License");
+ ! you may not use this file except in compliance with the License.
+ ! You may obtain a copy of the License at
+ !
+ !      http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing, software
+ ! distributed under the License is distributed on an "AS IS" BASIS,
+ ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ! See the License for the specific language governing permissions and
+ ! limitations under the License.
+ !-->
+<serviceGroup>
+
+    <service name="TenantMgtService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.apache.stratos.tenant.mgt.services.TenantSelfRegistrationService
+        </parameter>
+        <operation name="registerTenant">
+        </operation>
+        <operation name="checkDomainAvailability">
+        </operation>
+        <operation name="validateOrSuggestDomain">
+        </operation>
+        <operation name="generateRandomCaptcha">
+        </operation>
+    </service>
+
+    <service name="TenantMgtAdminService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.apache.stratos.tenant.mgt.services.TenantMgtAdminService
+        </parameter>
+        <operation name="addTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
+        </operation>
+        <operation name="retrieveTenants">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
+        </operation>
+        <operation name="retrievePaginatedTenants">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
+        </operation>
+         <operation name="retrievePartialSearchTenants">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
+        </operation>
+        <operation name="retrievePaginatedPartialSearchTenants">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
+        </operation>
+        <operation name="getTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
+        </operation>
+        <operation name="updateTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/modify/tenants</parameter>
+        </operation>
+        <operation name="activateTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/modify/tenants</parameter>
+        </operation>
+        <operation name="deactivateTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/modify/tenants</parameter>
+        </operation>
+        <operation name="deleteTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/modify/tenants</parameter>
+        </operation>
+        <parameter name="adminService" locked="true">true</parameter>
+    </service>
+    
+    <service name="GAppTenantRegistrationService">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <schema schemaNamespace="http://org.apache.axis2/xsd" elementFormDefaultQualified="true"/>
+        <description>Rampart protected service that is used to setup Google Apps domain</description>
+        <parameter name="ServiceClass">org.apache.stratos.tenant.mgt.services.GAppTenantRegistrationService</parameter>
+        <parameter name="adminService" locked="true">false</parameter>
+
+        <module ref="rampart"/>
+
+        <wsp:Policy wsu:Id="SigOnly"
+                    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
+                    xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
+            <wsp:ExactlyOne>
+                <wsp:All>
+                    <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
+                        <wsp:Policy>
+                            <sp:InitiatorToken>
+                                <wsp:Policy>
+                                    <sp:X509Token
+                                            sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
+                                        <wsp:Policy>
+                                            <sp:RequireThumbprintReference/>
+                                            <sp:WssX509V3Token10/>
+                                        </wsp:Policy>
+                                    </sp:X509Token>
+                                </wsp:Policy>
+                            </sp:InitiatorToken>
+                            <sp:RecipientToken>
+                                <wsp:Policy>
+                                    <sp:X509Token
+                                            sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
+                                        <wsp:Policy>
+                                            <sp:RequireThumbprintReference/>
+                                            <sp:WssX509V3Token10/>
+                                        </wsp:Policy>
+                                    </sp:X509Token>
+                                </wsp:Policy>
+                            </sp:RecipientToken>
+                            <sp:AlgorithmSuite>
+                                <wsp:Policy>
+                                    <sp:Basic256/>
+                                </wsp:Policy>
+                            </sp:AlgorithmSuite>
+                            <sp:Layout>
+                                <wsp:Policy>
+                                    <sp:Strict/>
+                                </wsp:Policy>
+                            </sp:Layout>
+                            <sp:IncludeTimestamp/>
+                            <sp:OnlySignEntireHeadersAndBody/>
+                        </wsp:Policy>
+                    </sp:AsymmetricBinding>
+                    <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
+                        <wsp:Policy>
+                            <sp:MustSupportRefKeyIdentifier/>
+                            <sp:MustSupportRefIssuerSerial/>
+                        </wsp:Policy>
+                    </sp:Wss10>
+                    <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
+                        <sp:Body/>
+                    </sp:SignedParts>
+                </wsp:All>
+            </wsp:ExactlyOne>
+        </wsp:Policy>
+    </service>
+    <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/pom.xml
----------------------------------------------------------------------
diff --git a/components/pom.xml b/components/pom.xml
index 61f3b53..26031c3 100644
--- a/components/pom.xml
+++ b/components/pom.xml
@@ -43,28 +43,34 @@
 	</licenses>
 
             <modules>
+                <!-- COMMON -->
+                <module>org.apache.stratos.common</module>
 		<!-- CC -->
 		<module>org.apache.stratos.cloud.controller</module>
-		<module>org.apache.stratos.cartridge.messages/2.1.1</module>
-		<module>org.apache.stratos.cartridge.agent/2.1.3</module>
+		<module>org.apache.stratos.cartridge.messages</module>
+		<module>org.apache.stratos.cartridge.agent</module>
 		<!-- ADC -->
-		<module>org.apache.stratos.adc.topology.mgt/2.1.3</module>
-		<module>org.apache.stratos.adc.mgt/2.1.3</module>
-		<module>org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1</module>
-		<module>org.apache.stratos.adc.mgt.cli/2.1.3</module>
-		<module>org.apache.stratos.deployment/2.1.0</module>
+		<module>org.apache.stratos.adc.topology.mgt</module>
+		<module>org.apache.stratos.adc.mgt</module>
+		<module>org.apache.stratos.adc.mgt.repository.synchronizer</module>
+		<module>org.apache.stratos.adc.mgt.cli</module>
+		<module>org.apache.stratos.deployment</module>
 		<!-- ELB -->
-		<module>lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3</module>
-		<module>org.apache.stratos.lb.common/4.1.3</module>
-		<module>org.apache.stratos.load.balance.agent/2.1.0</module>
-		<module>autoscaler/org.apache.stratos.mediator.autoscale/4.1.3</module>
-           	<module>autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0</module>
-		<!-- COMMON -->
-		<module>org.apache.stratos.common/2.1.2</module>
-		<module>org.apache.stratos.tenant.dispatcher/2.1.0</module>
-		<module>org.apache.stratos.keystore.mgt/2.1.0</module>
-		<module>org.apache.stratos.tenant.mgt.email.sender/2.1.0</module>
-                <module>tenant-activity</module>
+		<module>org.apache.stratos.lb.common</module>
+		<module>org.apache.stratos.lb.endpoint</module>
+		<module>org.apache.stratos.load.balance.agent</module>
+		<module>org.apache.stratos.mediator.autoscale</module>
+           	<module>org.apache.stratos.autoscaler.service</module>
+		<!-- Tenant Mgt -->
+		<module>org.apache.stratos.tenant.mgt.core</module>
+		<module>org.apache.stratos.tenant.mgt</module>
+		<module>org.apache.stratos.tenant.mgt.email.sender</module>	
+
+		<module>org.apache.stratos.tenant.dispatcher</module>
+		<module>org.apache.stratos.keystore.mgt</module>
+		<module>org.apache.stratos.activation</module>
+		<module>org.apache.stratos.tenant.activity</module>
+                <module>org.apache.stratos.tenant.activity.ui</module>
 	    </modules>
 	    
 	    <build>
@@ -250,8 +256,12 @@
         <google.guice.wso2.version>3.0.wso2v1</google.guice.wso2.version>
 	<commons-httpclient.version>3.0.1</commons-httpclient.version>
 	<json.wso2.version>2.0.0.wso2v1</json.wso2.version>
+	<axiom.wso2.version>1.2.11.wso2v4</axiom.wso2.version>
 	<orbit.version.axis2>1.6.1.wso2v5</orbit.version.axis2>
 	<orbit.version.axiom>1.2.11.wso2v3</orbit.version.axiom>
+	<neethi.wso2.version>2.0.4.wso2v4</neethi.wso2.version>
+	<imp.pkg.version.javax.servlet>[2.6.0, 3.0.0)</imp.pkg.version.javax.servlet>
+	<rampart.wso2.version>1.6.1.wso2v9</rampart.wso2.version>
         <!--eclipse.osgi.version>3.5.0.v20090520</eclipse.osgi.version>
         <eclipse.osgi.services.version>3.2.0.v20090520-1800</eclipse.osgi.services.version>
         <equinox.commons.logging.version>1.0.4.v200706111724</equinox.commons.logging.version>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/pom.xml
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/pom.xml b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/pom.xml
deleted file mode 100644
index f8b1b47..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/pom.xml
+++ /dev/null
@@ -1,142 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-  -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>tenant.activity.parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-	<relativePath>../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.tenant.activity.ui</artifactId>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Tenant Activity - User Interface</name>
-
-    <build>
-
-        <plugins>
-
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-compiler-plugin</artifactId>
-                <configuration>
-                    <source>1.5</source>
-                    <target>1.5</target>
-                </configuration>
-            </plugin>
-
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                <version>1.4.0</version>
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Private-Package>
-                            org.wso2.carbon.tenant.activity.ui.internal.*,
-                        </Private-Package>
-                        <Export-Package>
-                            org.wso2.carbon.tenant.activity.ui.*,
-                        </Export-Package>
-                        <Import-Package>
-			                org.wso2.carbon.tenant.activity.stub.*; version="${carbon.platform.package.import.version.range}",
-                            org.apache.stratos.common.*,
-                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
-                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
-                            !javax.xml.namespace,
-                            javax.xml.namespace; version=0.0.0,                            
-                            org.apache.lucene.*,
-                            *;resolution:=optional
-                        </Import-Package>
-                        <Carbon-Component>UIBundle</Carbon-Component>
-                    </instructions>
-                </configuration>
-            </plugin>
-
-        </plugins>
-    </build>
-
-    <dependencies>
-
-        <dependency>
-            <groupId>log4j</groupId>
-            <artifactId>log4j</artifactId>
-        </dependency>
-	    <dependency>
-            <groupId>commons-codec.wso2</groupId>
-            <artifactId>commons-codec</artifactId>
-	    <version>${version.commons.codec}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.registry.common.ui</artifactId>
-	    <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.registry.core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>commons-logging</groupId>
-            <artifactId>commons-logging</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.eclipse.equinox</groupId>
-            <artifactId>javax.servlet</artifactId>
-	    <version>3.0.0.v201112011016</version>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.ws.commons.axiom.wso2</groupId>
-            <artifactId>axiom</artifactId>
-	    <version>${orbit.version.axiom}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.ui</artifactId>
-	    <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.stratos</groupId>
-            <artifactId>org.apache.stratos.common</artifactId>
-	    <version>2.1.2</version>
-        </dependency>
-	    <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.tenant.activity.stub</artifactId>
-            <version>4.1.0</version>
-        </dependency>
-    </dependencies>
-    
-    <properties>
-	<version.commons.codec>1.4.0.wso2v1</version.commons.codec>
-    </properties>
-    
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/clients/TenantActivityServiceClient.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/clients/TenantActivityServiceClient.java b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/clients/TenantActivityServiceClient.java
deleted file mode 100644
index a7f3674..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/clients/TenantActivityServiceClient.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.tenant.activity.ui.clients;
-
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.client.Options;
-import org.apache.axis2.client.ServiceClient;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.CarbonConstants;
-import org.wso2.carbon.authenticator.proxy.AuthenticationAdminClient;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.tenant.activity.stub.TenantActivityServiceExceptionException;
-import org.wso2.carbon.tenant.activity.stub.beans.xsd.*;
-import org.apache.stratos.tenant.activity.ui.internal.TenantActivityUIServiceComponent;
-import org.wso2.carbon.ui.CarbonUIUtil;
-import org.wso2.carbon.user.core.UserStoreException;
-import org.wso2.carbon.utils.ServerConstants;
-import org.wso2.carbon.tenant.activity.stub.TenantActivityServiceStub;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.http.HttpSession;
-import java.rmi.RemoteException;
-
-public class TenantActivityServiceClient {
-    private static final Log log = LogFactory.getLog(TenantActivityServiceClient.class);
-
-    private TenantActivityServiceStub stub;
-    private String epr;
-
-
-    public TenantActivityServiceClient(
-            String cookie, String backendServerURL, ConfigurationContext configContext)
-            throws RegistryException {
-
-        epr = backendServerURL + "TenantMonitorService";
-
-        try {
-            stub = new TenantActivityServiceStub(configContext, epr);
-            ServiceClient client = stub._getServiceClient();
-            Options option = client.getOptions();
-            option.setManageSession(true);
-            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
-
-        } catch (AxisFault axisFault) {
-            String msg = "Failed to initiate TenantMonitorService service client. " + axisFault.getMessage();
-            log.error(msg, axisFault);
-            throw new RegistryException(msg, axisFault);
-        }
-    }
-
-    public TenantActivityServiceClient(ServletConfig config, HttpSession session)
-            throws RegistryException {
-        String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
-        String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
-        ConfigurationContext configContext = (ConfigurationContext) config.
-                getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
-        epr = backendServerURL + "TenantActivityService";
-
-        try {
-            stub = new TenantActivityServiceStub(configContext, epr);
-
-            ServiceClient client = stub._getServiceClient();
-            Options option = client.getOptions();
-            option.setManageSession(true);
-            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
-
-        } catch (AxisFault axisFault) {
-            String msg = "Failed to initiate TenantMonitorService service client. " + axisFault.getMessage();
-            log.error(msg, axisFault);
-            throw new RegistryException(msg, axisFault);
-        }
-    }
-
-    public TenantActivityServiceClient(String url, ServletConfig config, HttpSession session)
-            throws Exception {
-        //String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
-        ConfigurationContext configContext = (ConfigurationContext) config.
-                getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
-        try {
-            String cookie = login(url + "/services/", 
-                    TenantActivityUIServiceComponent.stratosConfiguration.getAdminUserName(),
-                    TenantActivityUIServiceComponent.stratosConfiguration.getAdminPassword(), 
-                    configContext);
-            epr = url + "/services/TenantActivityService";
-            stub = new TenantActivityServiceStub(configContext, epr);
-            ServiceClient client = stub._getServiceClient();
-            Options option = client.getOptions();
-            option.setManageSession(true);
-            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
-
-        } catch (AxisFault axisFault) {
-            String msg = "Failed to initiate TenantMonitorService service client. ";
-            log.error(msg, axisFault);
-            throw new RegistryException(msg, axisFault);
-        }
-    }
-
-
-    public int getActiveTenantCount() throws TenantActivityServiceExceptionException, RemoteException {
-        int count = stub.getActiveTenantCount();
-        return count;
-    }
-
-    /*public String[] getActiveTenantList() throws TenantActivityServiceExceptionException, RemoteException {
-        return stub.getActiveTenantList();
-    } */
-
-    public PaginatedTenantDataBean getPaginatedActiveTenantList(int pageNumber) throws TenantActivityServiceExceptionException, RemoteException {
-        return stub.retrievePaginatedActiveTenants(pageNumber);
-    }
-
-    /*  public TenantDataBean[] getAllActiveTenantList() throws TenantActivityServiceExceptionException, RemoteException {
-        return stub.getAllActiveTenantList();
-    }*/
-
-    public boolean isTenantActiveInService(String domainName) throws TenantActivityServiceExceptionException, RemoteException {
-        return stub.isActiveTenantOnService(domainName);
-    }
-    
-    private String login(String serverUrl, String userName, 
-                               String password, ConfigurationContext confContext) throws UserStoreException {
-        String sessionCookie = null;
-        try {
-            AuthenticationAdminClient client =
-                    new AuthenticationAdminClient(confContext, serverUrl, null, null, false);
-            //TODO : get the correct IP
-            boolean isLogin = client.login(userName, password, "127.0.0.1");
-            if (isLogin) {
-                sessionCookie = client.getAdminCookie();
-            }
-        } catch (Exception e) {
-            throw new UserStoreException("Error in login to the server server: " + serverUrl +
-                                         "username: " + userName + ".", e);
-        }
-        return sessionCookie;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/internal/TenantActivityUIServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/internal/TenantActivityUIServiceComponent.java b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/internal/TenantActivityUIServiceComponent.java
deleted file mode 100644
index d8c8eea..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/internal/TenantActivityUIServiceComponent.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package org.apache.stratos.tenant.activity.ui.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.service.component.ComponentContext;
-import org.apache.stratos.common.util.StratosConfiguration;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-/**
- * @scr.component name="org.wso2.stratos.tenant.activity.ui" immediate="true"
- * @scr.reference name="config.context.service"
- * interface="org.wso2.stratos.utils.ConfigurationContextService"
- * cardinality="1..1" policy="dynamic"  bind="setConfigurationContextService"
- * unbind="unsetConfigurationContextService"
- * @scr.reference name="stratos.config.service"
- * interface="org.wso2.stratos.stratos.common.util.StratosConfiguration" cardinality="1..1"
- * policy="dynamic" bind="setStratosConfigurationService" unbind="unsetStratosConfigurationService"
- */
-public class TenantActivityUIServiceComponent {
-    private static Log log = LogFactory.getLog(TenantActivityUIServiceComponent.class);
-    public static ConfigurationContextService contextService;
-    public static StratosConfiguration stratosConfiguration;
-
-    protected void activate(ComponentContext context) {
-        try {
-            if (log.isDebugEnabled()) {
-                log.error("******* Tenant Activity UI bundle is activated ******* ");
-            }
-        } catch (Throwable e) {
-            log.error("******* Error in activating Tenant Activity UI bundle ******* ", e);
-        }
-    }
-
-    protected void deactivate(ComponentContext context) {
-        if (log.isDebugEnabled()) {
-            log.debug("******* Tenant Activity UI bundle is deactivated ******* ");
-        }
-    }
-
-    protected void setStratosConfigurationService(StratosConfiguration stratosConfigService) {
-        TenantActivityUIServiceComponent.stratosConfiguration = stratosConfigService;
-    }
-
-    protected void unsetStratosConfigurationService(StratosConfiguration ccService) {
-        TenantActivityUIServiceComponent.stratosConfiguration = null;
-    }
-
-    protected void setConfigurationContextService(ConfigurationContextService contextService) {
-        TenantActivityUIServiceComponent.contextService = contextService;
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
-        TenantActivityUIServiceComponent.contextService = null;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/ManagerConfigurations.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/ManagerConfigurations.java b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/ManagerConfigurations.java
deleted file mode 100644
index 294cb15..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/ManagerConfigurations.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.tenant.activity.ui.utils;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.common.constants.StratosConstants;
-import org.apache.stratos.common.util.CommonUtil;
-import org.wso2.carbon.utils.CarbonUtils;
-
-import javax.xml.namespace.QName;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-
-public class ManagerConfigurations {
-
-    private static final String CONFIG_FILE = "throttling-agent-config.xml";
-
-    private static final String MANAGER_SERVICE_URL_PARAM_NAME = "managerServiceUrl";
-    private static final String USERNAME_PARAM_NAME = "userName";
-    private static final String PASSWORD_PARAM_NAME = "password";
-
-
-    private String managerServerUrl;
-    private String userName;
-    private String password;
-
-    private final static Log log = LogFactory.getLog(ManagerConfigurations.class);
-
-    private static final String CONFIG_NS =
-            "http://wso2.com/stratos/multitenancy/throttling/agent/config";
-    private static final String PARAMTERS_ELEMENT_NAME = "parameters";
-    private static final String PARAMTER_ELEMENT_NAME = "parameter";
-    private static final String PARAMTER_NAME_ATTR_NAME = "name";
-    private Map<String, String> parameters = new HashMap<String, String>();
-
-
-
-
-    public String getConfigFileName() throws Exception {
-
-        String configFileName = CarbonUtils.getCarbonConfigDirPath() +
-                File.separator + StratosConstants.MULTITENANCY_CONFIG_FOLDER +
-                File.separator + CONFIG_FILE;
-
-        return configFileName;
-
-    }
-
-
-    public ManagerConfigurations() throws Exception {
-
-        String throttlingAgentConfigFile = this.getConfigFileName();
-        try {
-            OMElement meteringConfig =
-                    CommonUtil.buildOMElement(new FileInputStream(throttlingAgentConfigFile));
-            deSerialize(meteringConfig);
-            Map<String, String> throttlingAgentParams = getParameters();
-            this.setUserName(throttlingAgentParams.get(USERNAME_PARAM_NAME));
-            this.setPassword(throttlingAgentParams.get(PASSWORD_PARAM_NAME));
-            this.setManagerServerUrl(throttlingAgentParams.get(MANAGER_SERVICE_URL_PARAM_NAME));
-        } catch (FileNotFoundException e) {
-            String msg = "Unable to find the file: " + throttlingAgentConfigFile + ".";
-            log.error(msg, e);
-        }
-    }
-
-    public void deSerialize(OMElement throttlingConfigEle) throws Exception {
-        Iterator meteringConfigChildIt = throttlingConfigEle.getChildElements();
-        while (meteringConfigChildIt.hasNext()) {
-            Object meteringConfigChild = meteringConfigChildIt.next();
-            if (!(meteringConfigChild instanceof OMElement)) {
-                continue;
-            }
-            OMElement meteringConfigChildEle = (OMElement) meteringConfigChild;
-            if (new QName(CONFIG_NS, PARAMTERS_ELEMENT_NAME, "").equals(meteringConfigChildEle
-                    .getQName())) {
-                Iterator parametersChildIt = meteringConfigChildEle.getChildElements();
-                while (parametersChildIt.hasNext()) {
-                    Object taskConfigChild = parametersChildIt.next();
-                    if (!(taskConfigChild instanceof OMElement)) {
-                        continue;
-                    }
-                    OMElement parameterChildEle = (OMElement) taskConfigChild;
-                    if (!new QName(CONFIG_NS, PARAMTER_ELEMENT_NAME, "").equals(parameterChildEle
-                            .getQName())) {
-                        continue;
-                    }
-                    String parameterName =
-                            parameterChildEle.getAttributeValue(new QName(PARAMTER_NAME_ATTR_NAME));
-                    String parameterValue = parameterChildEle.getText();
-                    parameters.put(parameterName, parameterValue);
-                }
-            }
-        }
-    }
-
-    public Map<String, String> getParameters() {
-        return parameters;
-    }
-
-
-    public String getUserName() {
-        return userName;
-    }
-
-    public void setUserName(String userName) {
-        this.userName = userName;
-    }
-
-    public String getPassword() {
-        return password;
-    }
-
-    public void setPassword(String password) {
-        this.password = password;
-    }
-
-    public String getManagerServerUrl() {
-        return managerServerUrl;
-    }
-
-    public void setManagerServerUrl(String managerServerUrl) {
-        this.managerServerUrl = managerServerUrl;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/TenantMonitorUtil.java
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/TenantMonitorUtil.java b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/TenantMonitorUtil.java
deleted file mode 100644
index 54d9c83..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/java/org/apache/stratos/tenant/activity/ui/utils/TenantMonitorUtil.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.tenant.activity.ui.utils;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.common.config.CloudServiceConfig;
-import org.apache.stratos.common.config.CloudServiceConfigParser;
-import org.apache.stratos.common.config.CloudServicesDescConfig;
-
-import java.util.*;
-
-import org.wso2.carbon.tenant.activity.stub.beans.xsd.PaginatedTenantDataBean;
-import org.wso2.carbon.tenant.activity.stub.beans.xsd.TenantDataBean;
-
-public class TenantMonitorUtil {
-    private static final Log log = LogFactory.getLog(TenantMonitorUtil.class);
-
-    public static Map<String, String[]> tenantList = new HashMap<String, String[]>();
-    public static Map<String, TenantDataBean[]> tenantDataList = new HashMap<String, TenantDataBean[]>();
-
-
-    private static ManagerConfigurations managerConfig = null;
-
-
-    public static ManagerConfigurations getManagerConfig() {
-        return managerConfig;
-    }
-
-    public static void setManagerConfig(ManagerConfigurations managerConfig) {
-        TenantMonitorUtil.managerConfig = managerConfig;
-    }
-
-  /*  public static Map<String, Integer> getActiveTenantCount(ServletConfig config, HttpSession session) throws Exception {
-        Map<String, Integer> map = new HashMap<String, Integer>();
-        try {
-            CloudServicesDescConfig cloudServicesDescConfig = CloudServiceConfigParser.loadCloudServicesConfiguration();
-
-            Map<String, CloudServiceConfig> cloudServicesConfigs = cloudServicesDescConfig.getCloudServiceConfigs();
-            for (String serviceName : cloudServicesConfigs.keySet()) {
-                String backEndURL = cloudServicesConfigs.get(serviceName).getLink();
-                System.out.println(backEndURL);
-                if (backEndURL == null) {
-                    try {
-                        TenantActivityServiceClient client = new TenantActivityServiceClient(config, session);
-                        map.put(serviceName, client.getActiveTenantCount());
-                        for (String nn : client.getActiveTenantList()) {
-                            System.out.println(nn);
-                        }
-                    } catch (Exception e) {
-                        log.error("Failed to get active tenants for manager service");
-                    }
-
-                } else {
-                    try {
-                        TenantActivityServiceClient client = new TenantActivityServiceClient(backEndURL, config, session);
-                        map.put(serviceName, client.getActiveTenantCount());
-                    } catch (Exception e) {
-                        log.error("failed to get Active tenants for" + serviceName + e.toString());
-                    }
-                }
-
-            }
-        } catch (Exception e) {
-            log.error("Error while retrieving cloud desc configuration");
-
-        }
-        return map;
-    }*/
-
-    public static Map<String, CloudServiceConfig> getCloudServiceConfigMap() {
-        try {
-            CloudServicesDescConfig cloudServicesDescConfig = CloudServiceConfigParser.loadCloudServicesConfiguration();
-            return cloudServicesDescConfig.getCloudServiceConfigs();
-        } catch (Exception e) {
-            log.error("Error while getting service names " + e.toString());
-        }
-        return null;
-    }
-
-    public static PaginatedTenantDataBean getPaginatedTenantData(int pageNumber, String serviceName) {
-        int entriesPerPage = 15;
-        List<TenantDataBean> tenantListOnService = Arrays.asList(tenantDataList.get(serviceName));
-        List<TenantDataBean> tenantUsages = new ArrayList<TenantDataBean>();
-        int i = 0;
-        int numberOfPages = 0;
-        for (TenantDataBean tenant : tenantListOnService) {
-            if (i % entriesPerPage == 0) {
-                numberOfPages++;
-            }
-            if (numberOfPages == pageNumber) {
-                tenantUsages.add(tenant);
-            }
-            i++;
-
-        }
-        PaginatedTenantDataBean paginatedTenantInfo = new PaginatedTenantDataBean();
-        paginatedTenantInfo.setTenantInfoBeans(
-                tenantUsages.toArray(new TenantDataBean[tenantUsages.size()]));
-        paginatedTenantInfo.setNumberOfPages(numberOfPages);
-        return paginatedTenantInfo;
-    }
-
-    public static boolean isTenantActiveOnService(String serviceName, String domain) {
-        boolean status = false;
-        for (TenantDataBean tenantBean : tenantDataList.get(serviceName)) {
-            if (tenantBean.getDomain().equalsIgnoreCase(domain)) {
-                status = true;
-            }
-        }
-        return status;
-    }
-
-    public static Map<String, String> getAdminParameters() {
-        Map<String, String> adminParameters = new HashMap<String, String>();
-        if (managerConfig == null) {
-            try {
-                managerConfig = new ManagerConfigurations();
-            } catch (Exception e) {
-                log.error("Failed to get administrator credentials" + e.toString());
-            }
-        }
-        adminParameters.put("userName", managerConfig.getUserName());
-        adminParameters.put("password", managerConfig.getPassword());
-        return adminParameters;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/META-INF/component.xml b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/META-INF/component.xml
deleted file mode 100644
index a163b36..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/META-INF/component.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<!--
- ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- ~
- ~ WSO2 Inc. licenses this file to you under the Apache License,
- ~ Version 2.0 (the "License"); you may not use this file except
- ~ in compliance with the License.
- ~ You may obtain a copy of the License at
- ~
- ~    http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing,
- ~ software distributed under the License is distributed on an
- ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- ~ KIND, either express or implied.  See the License for the
- ~ specific language governing permissions and limitations
- ~ under the License.
- -->
-<component xmlns="http://products.wso2.org/carbon">
-    <!-- sample menu configuration -->
-    <menus>
-        <menu>
-            <id>all_tenant_monitor_menu</id>
-            <i18n-key>Tenant Activity Monitor</i18n-key>
-            <i18n-bundle>org.wso2.carbon.tenant.activity.ui.i18n.Resources</i18n-bundle>
-            <parent-menu>monitor_menu</parent-menu>
-            <link>../tenant-activity/tenant-activity.jsp</link>
-            <region>region4</region>
-            <order>50</order>
-            <style-class>manage</style-class>
-            <icon>../tenant-activity/images/tenant-usage-report.gif</icon>
-            <require-permission>/permission/protected/monitor/userUsage</require-permission>
-            <require-super-tenant>true</require-super-tenant>
-        </menu>
-    </menus>
-</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/JSResources.properties
----------------------------------------------------------------------
diff --git a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/JSResources.properties b/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/JSResources.properties
deleted file mode 100644
index f038b96..0000000
--- a/components/tenant-activity/org.apache.stratos.tenant.activity.ui/src/main/resources/org/apache/stratos/tenant/activity/ui/i18n/JSResources.properties
+++ /dev/null
@@ -1 +0,0 @@
-session.timed.out=Session timed out. Please login again
\ No newline at end of file


[41/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
deleted file mode 100644
index 209a830..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.clients;
-
-import org.apache.axis2.AxisFault;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.stratos.cloud.controller.stub.CloudControllerServiceStub;
-
-/**
- * This is the client class this calls Autoscaler service.
- */
-public class CloudControllerStubClient extends CloudControllerClient {
-
-    private CloudControllerServiceStub stub;
-    private static final String CLOUD_CONTROLLER_EPR = AutoscalerTaskDSHolder.getInstance().getLoadBalancerConfig().getAutoscalerServiceEpr();
-
-    private static final Log log = LogFactory.getLog(CloudControllerStubClient.class);
-
-    // public CloudControllerStubClient(String epr) throws AxisFault {
-    //
-    // try {
-    //
-    // stub = new CloudControllerServiceStub(epr);
-    // stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(90000);
-    //
-    // } catch (AxisFault axisFault) {
-    // String msg =
-    // "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
-    // log.error(msg, axisFault);
-    // throw new AxisFault(msg, axisFault);
-    // }
-    // }
-
-    // public boolean init(boolean isSpi) throws Exception {
-    //
-    // return stub.initAutoscaler(isSpi);
-    // }
-
-    public String startInstance(String domainName, String subDomainName) throws Exception {
-
-        return stub.startInstance(domainName, subDomainName);
-    }
-
-    public boolean terminateInstance(String domainName, String subDomainName) throws Exception {
-
-        return stub.terminateInstance(domainName, subDomainName);
-    }
-
-    public boolean
-        terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception {
-
-        return stub.terminateLastlySpawnedInstance(domainName, subDomainName);
-    }
-
-    public int getPendingInstanceCount(String domainName, String subDomainName) throws Exception {
-
-        return stub.getPendingInstanceCount(domainName, subDomainName);
-    }
-
-    @Override
-    public void init() {
-
-        try {
-
-            stub = new CloudControllerServiceStub(CLOUD_CONTROLLER_EPR);
-            stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);
-
-        } catch (AxisFault axisFault) {
-            String msg = "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
-            log.error(msg, axisFault);
-            throw new RuntimeException(msg, axisFault);
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/AppDomainContext.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/AppDomainContext.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/AppDomainContext.java
deleted file mode 100644
index f8155a7..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/AppDomainContext.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.context;
-
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-
-
-/**
- * Contextual information related to autoscaling for a particular clustering domain
- */
-public class AppDomainContext extends LoadBalancerContext{
-
-    private static final long serialVersionUID = 6582721801663800609L;
-
-    private static final Log log = LogFactory.getLog(AppDomainContext.class);
-
-    /**
-     * Request tokens of requests in flight
-     * <p/>
-     * Key - request token ID, Value - message received time
-     */
-    private Map<String, Long> requestTokens = new ConcurrentHashMap<String, Long>();
-    private List<Integer> requestTokenListLengths;
-    private LoadBalancerConfiguration.ServiceConfiguration serviceConfig;
-
-    public AppDomainContext(LoadBalancerConfiguration.ServiceConfiguration serviceConfig) {
-        this.serviceConfig = serviceConfig;
-        requestTokenListLengths = new Vector<Integer>(serviceConfig.getRoundsToAverage());
-    }
-
-    public LoadBalancerConfiguration.ServiceConfiguration getServiceConfig() {
-        return serviceConfig;
-    }
-
-    /**
-     * If there is insufficient number of messages we cannot make a scaling decision.
-     *
-     * @return true - if a scaling decision can be made
-     */
-    public boolean canMakeScalingDecision() {
-        return requestTokenListLengths.size() >= serviceConfig.getRoundsToAverage();
-    }
-
-    public void addRequestToken(String tokenId) {
-        requestTokens.put(tokenId, System.currentTimeMillis());
-        if (log.isDebugEnabled()) {
-            log.debug("Request Tokens Added : "+requestTokens.size());
-        }
-    }
-
-    public void removeRequestToken(String tokenId) {
-        requestTokens.remove(tokenId);
-    }
-
-//    public int getRunningInstanceCount() {
-//        return super.getRunningInstanceCount();
-//    }
-
-    /**
-     * This will set the running instance count for this app domain
-     * and also will return the difference of current running instance count and previous count.
-     * @param runningInstanceCount current running instance count
-     * @return difference of current running instance count and previous count.
-     */
-//    public int setRunningInstanceCount(int runningInstanceCount) {
-//        int diff = 0;
-//        
-//        if(this.runningInstanceCount < runningInstanceCount){
-//            diff = runningInstanceCount - this.runningInstanceCount;
-//        }
-//        
-//        this.runningInstanceCount = runningInstanceCount;
-//        
-//        return diff;
-//    }
-
-    public void expireRequestTokens() {
-        for (Map.Entry<String, Long> entry : requestTokens.entrySet()) {
-            if (System.currentTimeMillis() - entry.getValue() >= serviceConfig.getMessageExpiryTime()) {
-                requestTokens.remove(entry.getKey());
-                if (log.isDebugEnabled()) {
-                    log.debug("Request Tokens Expired : " + requestTokens.get(entry.getKey()));
-                }
-            }
-        }
-    }
-
-    public void recordRequestTokenListLength() {
-        if (requestTokenListLengths.size() >= serviceConfig.getRoundsToAverage()) {
-            int count = requestTokenListLengths.remove(0);
-            if (log.isDebugEnabled()) {
-                log.debug("Request Tokens Removed : " + count);
-            }
-        }
-        if (log.isDebugEnabled()) {
-            log.debug("Request Tokens Added : " + requestTokens.size());
-        }
-        requestTokenListLengths.add(requestTokens.size());
-    }
-
-
-//    public synchronized int getPendingInstances() {
-//        return pendingInstances;
-//    }
-
-//    public synchronized void incrementPendingInstances() {
-//        this.pendingInstances++;
-//    }
-
-//    public synchronized void decrementPendingInstancesIfNotZero(int diff) {
-//        
-//        while (diff > 0 && this.pendingInstances > 0 ){
-//            this.pendingInstances--;
-//            diff--;
-//        }
-//        
-//    }
-    
-//    public synchronized int getInstances() {
-//        return runningInstanceCount + pendingInstances;
-//    }
-
-    /**
-     * Get the average requests in flight, averaged over the number of  of observations rounds
-     *
-     * @return number of average requests in flight. -1 if there no requests were received
-     */
-    public long getAverageRequestsInFlight() {
-        long total = 0;
-        for (Integer messageQueueLength : requestTokenListLengths) {
-            total += messageQueueLength;
-        }
-        int size = requestTokenListLengths.size();
-        if (size == 0) {
-            return -1; // -1 means that no requests have been received
-        }
-        
-        if (log.isDebugEnabled()) {
-            log.debug("Total Tokens : "+total+ " : Size: "+size);
-        }
-        return (long) total / size;
-    }
-
-
-//    public synchronized void resetRunningPendingInstances() {
-//        pendingInstances = 0;
-//        runningInstanceCount = 0;
-//    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
deleted file mode 100644
index b6a6d9b..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.context;
-
-import java.io.Serializable;
-
-/**
- * Contextual information related to autoscaling for a particular domain
- */
-public class LoadBalancerContext implements Serializable{
-
-    private static final long serialVersionUID = -2022110665957598060L;
-    private int runningInstances;
-    private int pendingInstances;
-    private int terminatingInstances;
-    
-    public synchronized int getTerminatingInstanceCount() {
-        return terminatingInstances;
-    }
-    
-    public synchronized int getRunningInstanceCount() {
-        return runningInstances;
-    }
-    
-    public synchronized int getPendingInstanceCount() {
-        return pendingInstances;
-    }
-
-    /**
-     * This will set the running instance count for a domain
-     * and also will return the difference of current running instance count and previous count.
-     * @param runningInstanceCount current running instance count
-     * @return difference of current running instance count and previous count.
-     */
-    public synchronized int setRunningInstanceCount(int count) {
-        int diff = 0;
-
-        if (this.runningInstances < count) {
-            diff = count - this.runningInstances;
-        }
-
-        this.runningInstances = count;
-
-        return diff;
-    }
-
-    public synchronized int getInstances() {
-        return runningInstances + pendingInstances;
-    }
-    
-    public synchronized void setPendingInstanceCount(int count) {
-        
-        this.pendingInstances = count;
-    }
-    
-    public synchronized void setTerminatingInstanceCount(int count) {
-        
-        this.terminatingInstances = count;
-    }
-
-    public synchronized void incrementPendingInstances(int diff) {
-
-        this.pendingInstances += diff;
-    }
-    
-    public synchronized void incrementTerminatingInstances(int diff) {
-
-        this.terminatingInstances += diff;
-    }
-    
-    public synchronized void decrementPendingInstancesIfNotZero(int diff) {
-
-        while (diff > 0 && this.pendingInstances > 0) {
-            this.pendingInstances--;
-            diff--;
-        }
-
-    }
-    
-    public synchronized void decrementTerminatingInstancesIfNotZero(int diff) {
-
-        while (diff > 0 && this.terminatingInstances > 0) {
-            this.terminatingInstances--;
-            diff--;
-        }
-
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
deleted file mode 100644
index 06a8f5e..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.internal;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.description.Parameter;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
-import org.apache.stratos.mediator.autoscale.lbautoscale.mediators.AutoscaleInMediator;
-import org.apache.stratos.mediator.autoscale.lbautoscale.mediators.AutoscaleOutMediator;
-import org.apache.stratos.mediator.autoscale.lbautoscale.task.*;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.apache.synapse.ManagedLifecycle;
-import org.apache.synapse.Mediator;
-import org.apache.synapse.SynapseConstants;
-import org.apache.synapse.SynapseException;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.mediators.base.SequenceMediator;
-import org.apache.synapse.mediators.filters.InMediator;
-import org.apache.synapse.mediators.filters.OutMediator;
-import org.apache.synapse.task.Task;
-import org.apache.synapse.task.TaskConstants;
-import org.apache.synapse.task.TaskDescription;
-import org.apache.synapse.task.TaskScheduler;
-import org.apache.synapse.task.service.TaskManagementService;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.component.ComponentContext;
-import org.quartz.JobBuilder;
-import org.quartz.JobDetail;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-import java.util.Date;
-import java.util.Map;
-
-/**
- * @scr.component name="autoscaler.task.component" immediate="true"
- * @scr.reference name="carbon.core.configurationContextService"
- * interface="org.wso2.carbon.utils.ConfigurationContextService"
- * cardinality="1..1" policy="dynamic"
- * bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
- * @scr.reference name="user.realmservice.default"
- * interface="org.wso2.carbon.user.core.service.RealmService"
- * cardinality="1..1" policy="dynamic" bind="setRealmService"
- * unbind="unsetRealmService"
- * @scr.reference name="org.apache.stratos.lb.common"
- * interface="org.apache.stratos.lb.common.service.LoadBalancerConfigurationService"
- * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
- * unbind="unsetLoadBalancerConfigurationService"
- * @scr.reference name="registry.service"
- * interface="org.wso2.carbon.registry.core.service.RegistryService"
- * cardinality="1..1" policy="dynamic"
- * bind="setRegistryService" unbind="unsetRegistryService"
- * @scr.reference name="org.wso2.carbon.stratos.cloud.controller"
- * interface="org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService"
- * cardinality="1..1" policy="dynamic" bind="setCloudControllerService"
- * unbind="unsetCloudControllerService"
- */
-public class AutoscalerTaskServiceComponent {
-
-    private static final Log log = LogFactory.getLog(AutoscalerTaskServiceComponent.class);
-    private ConfigurationContext configurationContext = null;
-
-    protected void activate(ComponentContext context) {
-    	
-    	try{
-
-        // read config file
-//        String configURL = System.getProperty(AutoscaleConstants.LOAD_BALANCER_CONFIG);
-//        LoadBalancerConfiguration lbConfig = new LoadBalancerConfiguration();
-//        lbConfig.init(configURL);
-        
-        if(configurationContext == null){
-            String msg = "Configuration context is null. Autoscaler task activation failed.";
-            log.fatal(msg);
-            throw new RuntimeException(msg);
-        }
-
-        // load synapse environment
-        Parameter synEnv =
-                configurationContext.getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_ENV);
-
-        if (synEnv == null || synEnv.getValue() == null ||
-                !(synEnv.getValue() instanceof SynapseEnvironment)) {
-
-            String message = "Unable to initialize the Synapse Configuration : Can not find the ";
-            log.fatal(message + "Synapse Environment");
-            throw new SynapseException(message + "Synapse Environment");
-        }
-
-        SynapseEnvironment synapseEnv = (SynapseEnvironment) synEnv.getValue();
-
-        /** Initializing autoscaleIn and autoscaleOut Mediators.**/
-
-        LoadBalancerConfiguration lbConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
-        // check whether autoscaling is enabled
-        if (lbConfig.getLoadBalancerConfig().isAutoscaleEnabled()) {
-
-            // get the main sequence mediator
-            SequenceMediator mainSequence =
-                    (SequenceMediator) synapseEnv.getSynapseConfiguration().getSequence("main");
-
-            // iterate through its child mediators
-            for (Mediator child : mainSequence.getList()) {
-
-                // find the InMediator
-                if (child instanceof InMediator) {
-                    InMediator inSequence = (InMediator) child;
-
-                    // if the first child of InMediator isn't an AutoscaleInMediator
-                    if (!(inSequence.getList().get(0) instanceof AutoscaleInMediator)) {
-
-                        // we gonna add it!
-                        inSequence.getList().add(0, new AutoscaleInMediator());
-                        if (log.isDebugEnabled()) {
-                            log.debug("Added Mediator: " + inSequence.getChild(0) + "" +
-                                    " to InMediator. Number of child mediators in InMediator" + " is " +
-                                    inSequence.getList().size() + ".");
-                        }
-                    }
-
-                }
-
-                // find the OutMediator
-                if (child instanceof OutMediator) {
-
-                    OutMediator outSequence = (OutMediator) child;
-
-                    // if the first child of OutMediator isn't an AutoscaleOutMediator
-                    if (!(outSequence.getList().get(0) instanceof AutoscaleOutMediator)) {
-
-                        // we gonna add it!
-                        outSequence.getList().add(0, new AutoscaleOutMediator());
-
-                        if (log.isDebugEnabled()) {
-                            log.debug("Added Mediator: " + outSequence.getChild(0) + "" +
-                                    " to OutMediator. Number of child mediators in OutMediator" +
-                                    " is " + outSequence.getList().size() + ".");
-                        }
-
-                    }
-                }
-            }
-
-            /** Initializing Autoscaler Task **/
-
-            BundleContext bundleContext = context.getBundleContext();
-            if (log.isDebugEnabled()) {
-                log.debug("Initiating Autoscaler task service component");
-            }
-
-            if (bundleContext.getServiceReference(TaskManagementService.class.getName()) != null) {
-                bundleContext.registerService(TaskManagementService.class.getName(),
-                        new AutoscalerTaskMgmtAdminService(), null);
-            }
-
-
-            AutoscalerTaskInitializer listener = new AutoscalerTaskInitializer();
-
-            if (bundleContext.getServiceReference(Axis2ConfigurationContextObserver.class.getName()) != null) {
-                bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(),
-                        listener, null);
-            }
-
-            if (configurationContext != null) {
-                TaskScheduler scheduler =
-                        (TaskScheduler) configurationContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER);
-                if (scheduler == null) {
-                    scheduler = new TaskScheduler(TaskConstants.TASK_SCHEDULER);
-                    scheduler.init(null);
-                    configurationContext.setProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER,
-                            scheduler);
-                } else if (!scheduler.isInitialized()) {
-                    scheduler.init(null);
-                }
-            }
-            
-            String autoscalerClass = lbConfig.getLoadBalancerConfig().getAutoscalerTaskClass();
-            Task task;
-            if (autoscalerClass != null) {
-                try {
-                    task = (Task) Class.forName(autoscalerClass).newInstance();
-                } catch (Exception e) {
-                    String msg = "Cannot instantiate Autoscaling Task. Class: " + autoscalerClass
-                    		+". It should implement 'org.apache.synapse.task.Task' and "
-                    		+"'org.apache.synapse.ManagedLifecycle' interfaces.";
-                    log.error(msg, e);
-                    throw new RuntimeException(msg, e);
-                }
-            } else {
-                task = new ServiceRequestsInFlightAutoscaler();
-            }
-
-//            ServiceRequestsInFlightAutoscaler autoscalerTask =
-//                    new ServiceRequestsInFlightAutoscaler();
-
-            ((ManagedLifecycle) task).init(synapseEnv);
-
-            // specify scheduler task details
-            JobBuilder jobBuilder = JobBuilder.newJob(AutoscalingJob.class)
-                .withIdentity("autoscalerJob");
-            JobDetail job = jobBuilder.build();
-
-            Map<String, Object> dataMap = job.getJobDataMap();
-            dataMap.put(AutoscalingJob.AUTOSCALER_TASK, task);
-            dataMap.put(AutoscalingJob.SYNAPSE_ENVI, synapseEnv);
-
-            final TaskDescription taskDescription = new TaskDescription();
-            taskDescription.setTaskClass(ServiceRequestsInFlightAutoscaler.class.getName());
-            taskDescription.setName("autoscaler");
-            //taskDescription.setCount(SimpleTrigger.REPEAT_INDEFINITELY);
-
-            int interval = AutoscalerTaskDSHolder.getInstance().getLoadBalancerConfig().getAutoscalerTaskInterval();
-            taskDescription.setInterval(interval);
-            taskDescription.setStartTime(new Date(System.currentTimeMillis() + (interval*2)));
-
-            TaskSchedulingManager scheduler = new TaskSchedulingManager();
-            scheduler.scheduleTask(taskDescription, dataMap, configurationContext);
-
-
-        } else {
-
-            log.info("Autoscaling is disabled.");
-        }
-    	} catch (Throwable e) {
-            log.error("Failed to activate Autoscaler Task Service Component. ", e);
-        }
-    }
-
-
-    protected void deactivate(ComponentContext ctx) {
-        AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(null);
-        if (log.isDebugEnabled()) {
-            log.debug("Autoscaler task bundle is deactivated");
-        }
-    }
-
-	protected void setCloudControllerService(CloudControllerService cc) {
-        AutoscalerTaskDSHolder.getInstance().setCloudControllerService(cc);
-    }
-    
-    protected void unsetCloudControllerService(CloudControllerService cc) {
-        AutoscalerTaskDSHolder.getInstance().setCloudControllerService(null);
-    }
-
-    protected void setConfigurationContextService(ConfigurationContextService context) {
-        if (log.isDebugEnabled()) {
-            log.debug("ConfigurationContextService bound to the Autoscaler task initialization process");
-        }
-        this.configurationContext = context.getServerConfigContext();
-        AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(context);
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
-        if (log.isDebugEnabled()) {
-            log.debug("ConfigurationContextService unbound from the Autoscaler task");
-        }
-        this.configurationContext = null;
-        AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(null);
-    }
-
-    protected void setRealmService(RealmService realmService) {
-        if (log.isDebugEnabled()) {
-            log.debug("Bound realm service from the Autoscaler task");
-        }
-        AutoscalerTaskDSHolder.getInstance().setRealmService(realmService);
-    }
-
-    protected void unsetRealmService(RealmService realmService) {
-        if (log.isDebugEnabled()) {
-            log.debug("Unbound realm service from the Autoscaler task");
-        }
-        AutoscalerTaskDSHolder.getInstance().setRealmService(null);
-    }
-    
-    protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
-        AutoscalerTaskDSHolder.getInstance().setLbConfigService(lbConfigSer);
-    }
-    
-    protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
-        AutoscalerTaskDSHolder.getInstance().setLbConfigService(null);
-    }
-    
-    protected void setRegistryService(RegistryService regService) {
-        if (log.isDebugEnabled()) {
-            log.debug("RegistryService bound to the endpoint component");
-        }
-        try {
-            AutoscalerTaskDSHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
-            AutoscalerTaskDSHolder.getInstance().setGovernanceRegistry(regService.getGovernanceSystemRegistry());
-        } catch (RegistryException e) {
-            log.error("Couldn't retrieve the registry from the registry service");
-        }
-    }
-
-    protected void unsetRegistryService(RegistryService regService) {
-        if (log.isDebugEnabled()) {
-            log.debug("RegistryService unbound from the endpoint component");
-        }
-        AutoscalerTaskDSHolder.getInstance().setConfigRegistry(null);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/RegistryManager.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/RegistryManager.java
deleted file mode 100644
index 0f5a03d..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/RegistryManager.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.internal;
-
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.common.util.DomainMapping;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-
-public class RegistryManager {
-    UserRegistry governanceRegistry = AutoscalerTaskDSHolder.getInstance().getGovernanceRegistry();
-    private static final Log log = LogFactory.getLog(RegistryManager.class);
-    /**
-     *
-     */
-    private Resource resource = null;
-    public static final String HOST_INFO = "hostinfo/";
-    public static final String ACTUAL_HOST = "actual.host";
-
-    public DomainMapping getMapping(String hostName) {
-        DomainMapping domainMapping;
-        try {
-            if (governanceRegistry.resourceExists(HOST_INFO + hostName)) {
-                resource = governanceRegistry.get(HOST_INFO + hostName);
-                domainMapping = new DomainMapping(hostName);
-                domainMapping.setActualHost(resource.getProperty(ACTUAL_HOST));
-                return domainMapping;
-            }
-        } catch (RegistryException e) {
-            log.info("Error while getting registry resource");
-            throw new RuntimeException(e);
-        }
-        return null;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
deleted file mode 100644
index 6ec1da3..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.mediators;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.internal.RegistryManager;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.apache.http.protocol.HTTP;
-import org.apache.synapse.ManagedLifecycle;
-import org.apache.synapse.MessageContext;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.core.axis2.Axis2MessageContext;
-import org.apache.synapse.mediators.AbstractMediator;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.util.HostContext;
-import org.apache.stratos.lb.common.cache.URLMappingCache;
-import org.apache.stratos.lb.common.util.DomainMapping;
-
-import java.util.Map;
-
-/**
- * This Synapse mediator generates a token per request received. These tokens are used for tracking
- * the number of requests in flight. Once a response is received, the relevant token will be removed
- * by the {@link AutoscaleOutMediator}
- *
- * @see AutoscaleOutMediator
- */
-public class AutoscaleInMediator extends AbstractMediator implements ManagedLifecycle {
-
-    private LoadBalancerConfiguration lbConfig;
-    private Map<String, HostContext> hostCtxts;
-    /**
-     * keep the size of cache which used to keep hostNames of url mapping.
-     */
-    private URLMappingCache mappingCache;
-    private RegistryManager registryManager;
-    private int sizeOfCache;
-
-    public AutoscaleInMediator() {
-
-        this.lbConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
-        hostCtxts = lbConfig.getHostContextMap();
-        sizeOfCache = lbConfig.getLoadBalancerConfig().getSizeOfCache();
-        mappingCache = URLMappingCache.getInstance(sizeOfCache);
-    }
-
-    public boolean mediate(MessageContext synCtx) {
-
-        if (log.isDebugEnabled()) {
-            log.debug("Mediation started .......... " + AutoscaleInMediator.class.getName());
-
-        }
-
-        ConfigurationContext configCtx =
-                                         ((Axis2MessageContext) synCtx).getAxis2MessageContext()
-                                                                       .getConfigurationContext();
-        String uuid = org.apache.axiom.util.UIDGenerator.generateUID();
-        synCtx.setProperty(AutoscaleConstants.REQUEST_ID, uuid);
-
-        Map<String, Map<String, ?>> appDomainContexts =
-                                                                       AutoscaleUtil.getAppDomainContexts(configCtx,
-                                                                               lbConfig);
-        org.apache.axis2.context.MessageContext axis2MessageContext =
-                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
-        Map<String, String> transportHeaders = (Map<String, String>) axis2MessageContext.
-                getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
-        String targetHost = transportHeaders.get(HTTP.TARGET_HOST);
-        
-        String toAddress = synCtx.getTo().getAddress();
-        if (targetHost.contains(":")) {
-            targetHost = targetHost.substring(0, targetHost.indexOf(':'));
-        }
-
-        int tenantId = AutoscaleUtil.getTenantId(synCtx.getTo().toString());
-
-        String domain = null, subDomain = null;
-        
-        log.debug("************ Target Host: "+targetHost + " -- Tenant id : "+tenantId);
-
-        HostContext ctxt = hostCtxts.get(targetHost);
-        
-        if (ctxt == null) {
-
-            DomainMapping domainMapping = mappingCache.getMapping(targetHost);
-            if (domainMapping == null) {
-                registryManager = new RegistryManager();
-                domainMapping = registryManager.getMapping(targetHost);
-                mappingCache.addValidMapping(targetHost, domainMapping);
-            }
-            if (domainMapping != null) {
-
-                String actualHost = domainMapping.getActualHost();
-
-                // get the HostContext from the actual host name in the case of domain 
-                // mapping.
-                ctxt = hostCtxts.get(actualHost);
-
-            }
-        }
-
-        if (ctxt == null) {
-            log.debug("Host Context is null.");
-        	// we don't need to do anything 
-        	return true;
-        }
-
-
-        // gets the corresponding domain
-        domain = ctxt.getDomainFromTenantId(tenantId);
-        synCtx.setProperty(AutoscaleConstants.TARGET_DOMAIN, domain);
-
-        // gets the corresponding sub domain
-        subDomain = ctxt.getSubDomainFromTenantId(tenantId);
-        synCtx.setProperty(AutoscaleConstants.TARGET_SUB_DOMAIN, subDomain);
-
-        if (appDomainContexts.get(domain) == null) {
-            // if we do not find a correct context, we just ignore
-            log.debug("AppDomainContext not found for domain " + domain);
-
-        } else {
-            AppDomainContext appDomainContext = (AppDomainContext) appDomainContexts.get(domain).get(subDomain);
-
-            if (appDomainContext != null) {
-                appDomainContext.addRequestToken(uuid);
-                System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");
-
-            } else {
-                // if we do not find a correct context, we just ignore
-                log.debug("AppDomainContext not found for sub domain: " + subDomain +
-                          " of domain: " + domain);
-            }
-        }
-
-        return true;
-    }
-
-    @Override
-    public void destroy() {
-
-        log.info("Mediator destroyed! " + AutoscaleInMediator.class.getName());
-    }
-
-    @Override
-    public void init(SynapseEnvironment arg0) {
-
-        if (log.isDebugEnabled()) {
-            log.debug("Mediator initialized! " + AutoscaleInMediator.class.getName());
-        }
-    }
-    
-    private void throwException(String msg){
-        log.error(msg);
-        throw new RuntimeException(msg);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
deleted file mode 100644
index 3640c08..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.mediators;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-import org.apache.synapse.ManagedLifecycle;
-import org.apache.synapse.MessageContext;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.core.axis2.Axis2MessageContext;
-import org.apache.synapse.mediators.AbstractMediator;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
-
-import java.util.Map;
-
-/**
- * This Synapse mediator removes the request token generated by the {@link AutoscaleInMediator}
- * 
- * @see AutoscaleInMediator
- */
-public class AutoscaleOutMediator extends AbstractMediator implements ManagedLifecycle {
-
-    public boolean mediate(MessageContext synCtx) {
-
-        log.debug("Mediation started ....... " + AutoscaleOutMediator.class.getName());
-
-        ConfigurationContext configCtx =
-            ((Axis2MessageContext) synCtx).getAxis2MessageContext().getConfigurationContext();
-
-        String domain = (String) synCtx.getProperty(AutoscaleConstants.TARGET_DOMAIN);
-        // gets the corresponding sub domain
-        String subDomain = (String) synCtx.getProperty(AutoscaleConstants.TARGET_SUB_DOMAIN);
-        
-        String tokenId = (String) synCtx.getProperty(AutoscaleConstants.REQUEST_ID);
-        @SuppressWarnings("unchecked")
-        Map<String, Map<String, AppDomainContext>> appDomainContexts =
-            (Map<String, Map<String, AppDomainContext>>) configCtx.getPropertyNonReplicable(AutoscaleConstants.APP_DOMAIN_CONTEXTS);
-        AppDomainContext appDomainContext = null ;
-        
-        if(appDomainContexts.get(domain) != null){
-        	appDomainContext = appDomainContexts.get(domain).get(subDomain);
-        }
-        
-        if (appDomainContext != null) {
-            appDomainContext.removeRequestToken(tokenId);
-            System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");
-        } else {
-            log.debug("AppDomainContext not found for domain " + domain+" and sub domain : "+subDomain);
-        }
-        return true;
-    }
-
-    @Override
-    public void destroy() {
-        log.debug("Autoscale out mediator destroyed...");
-    }
-
-    @Override
-    public void init(SynapseEnvironment arg0) {
-        log.debug("Autoscale out mediator started...");
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
deleted file mode 100644
index 3cf1c85..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.state.check;
-
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class PendingInstancesStateChecker implements Runnable {
-    
-    private static final Log log = LogFactory.getLog(PendingInstancesStateChecker.class);
-    private LoadBalancerContext groupCtxt = null;
-    private String domain;
-    private String subDomain;
-    private int expectedIncrementOfinstanceCount, originalRunningInstanceCount;
-    private CloudControllerClient ccClient;
-    
-    public PendingInstancesStateChecker(LoadBalancerContext ctxt, String aDomain, String aSubDomain,
-            int anexpectedInstanceCount, int currentCount, CloudControllerClient client) {
-        groupCtxt = ctxt;
-        domain = aDomain;
-        subDomain = aSubDomain;
-        expectedIncrementOfinstanceCount = anexpectedInstanceCount;
-        originalRunningInstanceCount = currentCount;
-        ccClient = client;
-    }
-
-    @Override
-    public void run() {
-
-        if (groupCtxt != null) {
-
-            int totalWaitedTime = 0;
-            int serverStartupDelay = AutoscalerTaskDSHolder
-                .getInstance()
-                .getWholeLoadBalancerConfig()
-                .getLoadBalancerConfig()
-                .getServerStartupDelay();
-
-            log.debug("Pending Instances State Checker has started for: " +
-                AutoscaleUtil.domainSubDomainString(domain, subDomain) + ". Check expiry time : " + serverStartupDelay);
-
-            // for each sub domain, get the clustering group management agent
-            GroupManagementAgent agent =
-                AutoscalerTaskDSHolder.getInstance().getAgent()
-                    .getGroupManagementAgent(domain,
-                        subDomain);
-            int startingRunningInstanceCount = agent.getMembers().size();
-
-            // we give some time for the server to get joined, we'll check time to time
-            // whether the instance has actually joined the ELB.
-            while ((agent.getMembers().size() < (originalRunningInstanceCount + expectedIncrementOfinstanceCount)) &&
-                totalWaitedTime < serverStartupDelay) {
-                int upToDateRunningInstanceCount = agent.getMembers().size();
-
-                log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
-                    " - Number of current running instances " +
-                        upToDateRunningInstanceCount);
-
-                if (upToDateRunningInstanceCount > startingRunningInstanceCount) {
-                    int newlyJoinedInstanceCount = upToDateRunningInstanceCount - startingRunningInstanceCount;
-                    // set new running instance count
-                    groupCtxt.setRunningInstanceCount(upToDateRunningInstanceCount);
-                    // decrement the pending instance count
-                    groupCtxt.decrementPendingInstancesIfNotZero(newlyJoinedInstanceCount);
-                    // update the starting running instance count
-                    startingRunningInstanceCount = upToDateRunningInstanceCount;
-
-                    log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
-                        " - Instances newly joined: " +
-                            newlyJoinedInstanceCount);
-                }
-
-                try {
-                    Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
-                } catch (InterruptedException ignore) {
-                }
-
-                totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
-            }
-
-            log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) + "- Waited for : " +
-                totalWaitedTime +
-                " (milliseconds) till pending members get joined.");
-
-            if (agent.getMembers().size() < (originalRunningInstanceCount + expectedIncrementOfinstanceCount)) {
-
-                int instanceCountFailedToJoin =
-                    originalRunningInstanceCount + expectedIncrementOfinstanceCount - agent.getMembers().size();
-                log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
-                    "Instances that are failed to join: " +
-                        instanceCountFailedToJoin);
-
-                // to avoid an infinite loop
-                int retries = instanceCountFailedToJoin + 2;
-
-                while (instanceCountFailedToJoin > 0 && retries > 0) {
-                    // instances spawned haven't joined ELB, so we assume that instance is
-                    // corrupted.
-                    // hence, we ask CC to terminate it.
-                    try {
-                        log.debug("Terminating lastly spwaned instance of " +
-                            AutoscaleUtil.domainSubDomainString(domain, subDomain));
-                        ccClient.terminateLastlySpawnedInstance(domain, subDomain);
-                        instanceCountFailedToJoin--;
-                        // decrement pending count
-                        groupCtxt.decrementPendingInstancesIfNotZero(1);
-                    } catch (Exception e) {
-                        log
-                            .error(
-                                "Instance termination failed for " +
-                                    AutoscaleUtil.domainSubDomainString(domain, subDomain),
-                                e);
-                    } finally {
-                        retries--;
-                    }
-                }
-
-                // decrement pending count
-                groupCtxt.decrementPendingInstancesIfNotZero(instanceCountFailedToJoin);
-            }
-
-        }
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
deleted file mode 100644
index d135d22..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.state.check;
-
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class TerminatingInstancesStateChecker implements Runnable {
-    
-    private static final Log log = LogFactory.getLog(TerminatingInstancesStateChecker.class);
-    private LoadBalancerContext groupCtxt = null;
-    private String domain;
-    private String subDomain;
-    
-    public TerminatingInstancesStateChecker(LoadBalancerContext ctxt, String aDomain, String aSubDomain) {
-        groupCtxt = ctxt;
-        domain = aDomain;
-        subDomain = aSubDomain;
-    }
-
-    @Override
-    public void run() {
-
-        if (groupCtxt != null) {
-
-            groupCtxt.incrementTerminatingInstances(1);
-            
-            int totalWaitedTime = 0;
-            int serverStartupDelay = AutoscalerTaskDSHolder
-                .getInstance()
-                .getWholeLoadBalancerConfig()
-                .getLoadBalancerConfig()
-                .getServerStartupDelay();
-            log.info("Terminating Instances State Checker has started for: " +
-                AutoscaleUtil.domainSubDomainString(domain, subDomain) + ". Check expiry time : " + serverStartupDelay);
-
-            // for each sub domain, get the clustering group management agent
-            GroupManagementAgent agent =
-                AutoscalerTaskDSHolder.getInstance().getAgent()
-                    .getGroupManagementAgent(domain,
-                        subDomain);
-
-            int startingRunningInstanceCount = agent.getMembers().size();
-
-            // we give some time for the server to be terminated, we'll check time to time
-            // whether the instance has actually left the cluster.
-            while (agent.getMembers().size() == startingRunningInstanceCount &&
-                totalWaitedTime < serverStartupDelay) {
-
-                try {
-                    Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
-                } catch (InterruptedException ignore) {
-                }
-
-                totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
-            }
-
-            log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) + "- Waited for : " +
-                totalWaitedTime +
-                " (milliseconds) till terminating member left the cluster.");
-
-            // we recalculate number of alive instances
-            groupCtxt.decrementTerminatingInstancesIfNotZero(1);
-        }
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
deleted file mode 100644
index a38fecd..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.mediator.autoscale.lbautoscale.task;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.synapse.task.TaskConstants;
-import org.apache.synapse.task.TaskDescriptionRepository;
-import org.apache.synapse.task.TaskScheduler;
-import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver;
-
-public class AutoscalerTaskInitializer extends AbstractAxis2ConfigurationContextObserver {
-
-    public static final java.lang.String CARBON_TASK_SCHEDULER = "CARBON_TASK_SCHEDULER";
-    public static final java.lang.String CARBON_TASK_REPOSITORY = "CARBON_TASK_REPOSITORY";
-
-    public void createdConfigurationContext(ConfigurationContext configContext) {
-        TaskScheduler scheduler = (TaskScheduler)configContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER);
-        if (scheduler == null) {
-            scheduler = new TaskScheduler(TaskConstants.TASK_SCHEDULER);
-            scheduler.init(null);
-            configContext.setProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER, scheduler);
-        } else if(!scheduler.isInitialized()) {
-            scheduler.init(null);
-        }
-
-        if (configContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_REPOSITORY) == null) {
-            TaskDescriptionRepository repository = new TaskDescriptionRepository();
-            configContext.setProperty(
-                    AutoscalerTaskInitializer.CARBON_TASK_REPOSITORY, repository);
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
deleted file mode 100644
index 5f83f7e..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
+++ /dev/null
@@ -1,348 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.task;
-
-import org.apache.axiom.om.OMAbstractFactory;
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.OMFactory;
-import org.apache.axiom.om.OMNamespace;
-import org.apache.axiom.om.util.AXIOMUtil;
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.task.TaskDescription;
-import org.apache.synapse.task.TaskDescriptionFactory;
-import org.apache.synapse.task.TaskDescriptionSerializer;
-import org.apache.synapse.task.service.TaskManagementService;
-import org.wso2.carbon.core.AbstractAdmin;
-import org.wso2.carbon.task.TaskManagementException;
-import org.wso2.carbon.task.TaskManager;
-
-import javax.xml.namespace.QName;
-import javax.xml.stream.XMLStreamException;
-import java.util.*;
-
-public class AutoscalerTaskMgmtAdminService extends AbstractAdmin implements TaskManagementService{
-
-    private static final Log log = LogFactory.getLog(AutoscalerTaskMgmtAdminService.class);
-
-    private TaskSchedulingManager schedulingManager;
-
-
-    private static final String TASK_EXTENSION_NS =
-            "http://www.wso2.org/tasks";
-
-    private static final OMFactory FACTORY = OMAbstractFactory.getOMFactory();
-
-    private static final OMNamespace TASK_OM_NAMESPACE = FACTORY.createOMNamespace(
-            TASK_EXTENSION_NS, "task");
-
-    public AutoscalerTaskMgmtAdminService(){}
-    
-    public AutoscalerTaskMgmtAdminService(ConfigurationContext configurationContext) {
-        this.schedulingManager = TaskSchedulingManager.getInstance();
-        this.configurationContext = configurationContext;
-    }
-
-    public void shutdown() {
-        schedulingManager.shutDown(getConfigContext());
-    }
-
-    public void addTaskDescription(TaskDescription taskDescription, Map<String, Object> resources)
-            throws Exception {
-        if (log.isDebugEnabled()) {
-            log.debug("Adding the Task " + taskDescription.getName());
-        }
-        try {
-            schedulingManager.scheduleTask(taskDescription, resources, getConfigContext());
-        } catch (Exception e) {
-            String msg = "Cannot add the task " + taskDescription.getName() + "..";
-            log.error(msg, e);  
-            throw e;
-        }
-    }
-
-    /**
-     * Passing the Task Description to scheduling manager to actually add it to the Task
-     * Description Repository.
-     *
-     * @param taskDescription TaskDescription
-     */
-    public void addTaskDescription(TaskDescription taskDescription) {
-        if (log.isDebugEnabled()) {
-            log.debug("Adding the Task " + taskDescription.getName());
-        }
-        try {
-            Map<String, Object> resources = new HashMap<String, Object>();
-            schedulingManager.scheduleTask(taskDescription, resources, getConfigContext());
-        } catch (Exception e) {
-            String msg = "Cannot add the task";
-            log.error(msg, e);
-        }
-    }
-
-    public void addTaskDescriptionInAnOmElement(String taskElementString) throws
-                                                                          TaskManagementException,
-                                                                          XMLStreamException {
-        OMElement taskElement = AXIOMUtil.stringToOM(taskElementString);
-        if (log.isDebugEnabled()) {
-            log.debug("Add TaskDescription - Get a Task configuration  :" + taskElement);
-        }
-        TaskDescription taskDescription = validateAndCreate(taskElement);
-
-        try {
-            addTaskDescription(taskDescription);
-        } catch (Exception e) {
-            try {
-                getTaskManager().deleteTaskDescription(taskDescription.getName(),
-                        taskDescription.getGroup());
-            } catch (Exception ignored) {
-            }
-            handleException("Error creating a task : " + e.getMessage(), e);
-        }
-    }
-
-
-
-    public void deleteTaskDescription(TaskDescription taskDescription) {
-        String taskName = taskDescription.getName();
-        if (log.isDebugEnabled()) {
-            log.debug("Deleting the task " + taskName);
-        }
-        try {
-            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
-        } catch (Exception e) {
-            log.error("Cannot delete the task " + taskName, e);
-        }
-    }
-
-    /**
-     * Indicating Task Scheduling manager to delete the task with the given task Name.
-     *
-     * @param taskName taskName
-     */
-    public void deleteTaskDescription(String taskName) {
-        if (log.isDebugEnabled()) {
-            log.debug("Deleting the task " + taskName);
-        }
-        try {
-            TaskDescription taskDescription = new TaskDescription();
-            taskDescription.setName(taskName);
-            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
-        } catch (Exception e) {
-            log.error("Cannot delete the task " + taskName, e);
-        }
-    }
-
-    /**
-     * Notifying the Task Scheduling Manager to delete the previous Task Description from the
-     * Task Description Repository and add the edited task.
-     *
-     * @param taskDescription TaskDescription
-     */
-    public void editTaskDescription(TaskDescription taskDescription) {
-        if (log.isDebugEnabled()) {
-            log.debug("Editing the task " + taskDescription.getName());
-        }
-        if (schedulingManager.isContains(taskDescription.getName(), getConfigContext())) {
-            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
-            schedulingManager.scheduleTask(taskDescription, null, getConfigContext());
-        } else {
-            log.error("Task " + taskDescription.getName() + "does not exist");
-        }
-    }
-
-    public void editTaskDescriptionInOmElement(
-            String taskElementString) throws TaskManagementException, XMLStreamException {
-        OMElement taskElement = AXIOMUtil.stringToOM(taskElementString);
-        if (log.isDebugEnabled()) {
-            log.debug("Edit TaskDescription - Get a Task configuration  :" + taskElement);
-        }
-        try {
-            editTaskDescription(validateAndCreate(taskElement));
-        } catch (Exception e) {
-            String msg = "Error editing Task";
-            throw new TaskManagementException(msg, e);
-        }
-    }
-
-    /**
-     * Returns the list of Task Descriptions that have been already added to the Task Description
-     * Repository.
-     *
-     * @return A list of Task Descriptions
-     */
-    public List<TaskDescription> getAllTaskDescriptions() {
-        List<TaskDescription> taskDescriptions = new ArrayList<TaskDescription>();
-        Iterator<TaskDescription> iterator = schedulingManager.getAllTaskDescriptions(
-                getConfigContext());
-
-        while (iterator.hasNext()) {
-            TaskDescription taskDescription = iterator.next();
-            if (taskDescription != null) {
-                taskDescriptions.add(taskDescription);
-            }
-        }
-        if (log.isDebugEnabled()) {
-            log.debug("All available Task based Scheduled Functions " + taskDescriptions);
-        }
-        return taskDescriptions;
-    }
-
-    public String getAllTaskDescriptionsInAnOMElement() throws AxisFault {
-        OMElement rootElement =
-                OMAbstractFactory.getOMFactory().createOMElement(new QName(TASK_EXTENSION_NS,
-                        "taskExtension", "task"));
-        try {
-            List<TaskDescription> descriptions = getAllTaskDescriptions();
-            for (TaskDescription taskDescription : descriptions) {
-                if (taskDescription != null) {
-                    OMElement taskElement =
-                            TaskDescriptionSerializer.serializeTaskDescription(TASK_OM_NAMESPACE,
-                                                                               taskDescription);
-                    validateTaskElement(taskElement);
-                    rootElement.addChild(taskElement);
-                }
-            }
-        } catch (TaskManagementException e) {
-            String msg = "Error loading all tasks";
-            log.error(msg, e);
-            throw new AxisFault(msg, e);
-        }
-        if (log.isDebugEnabled()) {
-            log.debug("Returning all TaskDescriptions as  :" + rootElement);
-        }
-        return rootElement.toString();
-    }
-
-    /**
-     * Returns the names of job groups that are being executed.
-     *
-     * @return An array of strings
-     */
-    public String[] getAllJobGroups() {
-        List<String> strings = getTaskManager().getAllJobGroups();
-        return strings.toArray(new String[strings.size()]);
-    }
-
-    /**
-     * Returns the TaskDescription associates with a particular task name
-     *
-     * @param taskName Task Name
-     * @return TaskDescription
-     */
-    public TaskDescription getTaskDescription(String taskName) {
-        return schedulingManager.getTaskDescription(taskName, getConfigContext());
-    }
-
-    public boolean isContains(String taskName) {
-        return schedulingManager.isContains(taskName, getConfigContext());
-    }
-
-    /**
-     * @param taskClass taskClass
-     * @return list of strings containing properties of the task class
-     */
-    public List<String> getPropertyNames(String taskClass) {
-        return null;
-    }
-
-    /**
-     * Returns the TaskManager instance currently being used
-     *
-     * @return TaskManager
-     */
-    private synchronized TaskManager getTaskManager() {
-        return (TaskManager) getConfigContext().getProperty(
-                TaskManager.CARBON_TASK_MANAGER);
-    }
-
-    /**
-     * Validates the OMElement which has a particular TaskDescription
-     * serialized into it.
-     *
-     * @param taskElement taskElement
-     * @throws TaskManagementException TaskManagementException
-     */
-    private static void validateTaskElement(
-            OMElement taskElement) throws TaskManagementException {
-        if (taskElement == null) {
-            handleException("Task Description OMElement can not be found.");
-        }
-    }
-
-    /**
-     * Handles the exception thrown and logs it.
-     *
-     * @param msg message to be logged
-     * @throws TaskManagementException TaskManagementException
-     */
-    private static void handleException(String msg) throws TaskManagementException {
-        log.error(msg);
-        throw new TaskManagementException(msg);
-    }
-
-    /**
-     * Handles the exception thrown and logs it.
-     *
-     * @param msg message to be logged
-     * @param e   exception thrown
-     * @throws TaskManagementException TaskManagementException
-     */
-    private static void handleException(String msg, Exception e) throws TaskManagementException {
-        log.error(msg, e);
-        throw new TaskManagementException(msg, e);
-    }
-
-    /**
-     * Validates an OMElement which has a TaskDescription serialized into it
-     * and returns the corresponding TaskDescription
-     *
-     * @param taskElement OMElement containing the TaskDescription
-     * @return TaskDescription
-     * @throws TaskManagementException TaskManagementException
-     */
-    private static TaskDescription validateAndCreate(
-            OMElement taskElement) throws TaskManagementException {
-
-        validateTaskElement(taskElement);
-        TaskDescription taskDescription =
-                TaskDescriptionFactory.createTaskDescription(taskElement, TASK_OM_NAMESPACE);
-        validateTaskDescription(taskDescription);
-        if (log.isDebugEnabled()) {
-            log.debug("Task Description : " + taskDescription);
-        }
-        return taskDescription;
-    }
-
-    /**
-     * Validates TaskDescriptions
-     *
-     * @param description TaskDescription
-     * @throws TaskManagementException TaskManagementException
-     */
-    private static void validateTaskDescription(
-            TaskDescription description) throws TaskManagementException {
-        if (description == null) {
-            handleException("Task Description can not be found.");
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
deleted file mode 100644
index 852c6bd..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.mediator.autoscale.lbautoscale.task;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.ManagedLifecycle;
-import org.apache.synapse.task.Task;
-import org.quartz.Job;
-import org.quartz.JobDetail;
-import org.quartz.JobExecutionContext;
-import org.quartz.JobExecutionException;
-import java.util.Map;
-
-public class AutoscalingJob implements Job {
-
-    public static final String AUTOSCALER_TASK = "autoscalerTask";
-
-    public static final String SYNAPSE_ENVI = "synapseEnv";
-
-    private static final Log log = LogFactory.getLog(AutoscalingJob.class);
-
-    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
-
-        try {
-
-            Task task = null;
-
-            JobDetail jobDetail = jobExecutionContext.getJobDetail();
-
-            if (log.isDebugEnabled()) {
-                log.debug("Executing Autoscaler task : " + jobDetail.getKey().getName());
-            }
-
-            @SuppressWarnings("rawtypes")
-            Map mjdm = jobExecutionContext.getMergedJobDataMap();
-
-            task = (Task) mjdm.get(AUTOSCALER_TASK);
-
-            if (task instanceof ManagedLifecycle) {
-                // Execute Autoscaler task
-                ((ServiceRequestsInFlightAutoscaler) task).execute();
-            }
-
-        } catch (Exception e) {
-            throw new JobExecutionException(e);
-        }
-
-    }
-
-}


[31/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java
deleted file mode 100644
index a83a5c9..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java
+++ /dev/null
@@ -1,1095 +0,0 @@
-package org.apache.stratos.adc.mgt.utils;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.rmi.RemoteException;
-import java.text.DecimalFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.util.regex.Pattern;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import javax.activation.DataHandler;
-import javax.activation.FileDataSource;
-
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.Member;
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.client.CloudControllerServiceClient;
-import org.apache.stratos.adc.mgt.dao.CartridgeSubscription;
-import org.apache.stratos.adc.mgt.dao.DataCartridge;
-import org.apache.stratos.adc.mgt.dao.PortMapping;
-import org.apache.stratos.adc.mgt.dao.Repository;
-import org.apache.stratos.adc.mgt.dns.DNSManager;
-import org.apache.stratos.adc.mgt.dto.Cartridge;
-import org.apache.stratos.adc.mgt.dto.Policy;
-import org.apache.stratos.adc.mgt.dto.RepositoryInformation;
-import org.apache.stratos.adc.mgt.dto.SubscriptionInfo;
-import org.apache.stratos.adc.mgt.exception.ADCException;
-import org.apache.stratos.adc.mgt.exception.AlreadySubscribedException;
-import org.apache.stratos.adc.mgt.exception.DuplicateCartridgeAliasException;
-import org.apache.stratos.adc.mgt.exception.InvalidCartridgeAliasException;
-import org.apache.stratos.adc.mgt.exception.InvalidRepositoryException;
-import org.apache.stratos.adc.mgt.exception.NotSubscribedException;
-import org.apache.stratos.adc.mgt.exception.PolicyException;
-import org.apache.stratos.adc.mgt.exception.RepositoryCredentialsRequiredException;
-import org.apache.stratos.adc.mgt.exception.RepositoryRequiredException;
-import org.apache.stratos.adc.mgt.exception.RepositoryTransportException;
-import org.apache.stratos.adc.mgt.exception.UnregisteredCartridgeException;
-import org.apache.stratos.adc.mgt.internal.DataHolder;
-import org.apache.stratos.adc.mgt.service.RepositoryInfoBean;
-import org.eclipse.jgit.api.Git;
-import org.eclipse.jgit.api.LsRemoteCommand;
-import org.eclipse.jgit.api.errors.GitAPIException;
-import org.eclipse.jgit.api.errors.InvalidRemoteException;
-import org.eclipse.jgit.api.errors.TransportException;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.storage.file.FileRepository;
-import org.eclipse.jgit.transport.CredentialsProvider;
-import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
-import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
-import org.apache.stratos.adc.topology.mgt.serviceobjects.DomainContext;
-import org.apache.stratos.cloud.controller.stub.CloudControllerServiceUnregisteredCartridgeExceptionException;
-import org.apache.stratos.cloud.controller.util.xsd.CartridgeInfo;
-import org.apache.stratos.cloud.controller.util.xsd.Properties;
-import org.apache.stratos.cloud.controller.util.xsd.Property;
-import org.wso2.carbon.utils.CarbonUtils;
-import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
-
-import com.google.gson.Gson;
-
-/**
- * This class contains utility methods used by ApplicationManagementService.
- */
-public class ApplicationManagementUtil {
-
-    private static Log log = LogFactory.getLog(ApplicationManagementUtil.class);
-    private static volatile CloudControllerServiceClient serviceClient;
-
-    /**
-     * Method used to subscribe to cartridges.
-     */
-	public static SubscriptionInfo doSubscribe(String cartridgeType, String alias, String policy, String repoURL,
-			boolean privateRepo, String repoUsername, String repoPassword, String dataCartridgeType,
-			String dataCartridgeAlias, String username, int tenantId, String tenantDomain) throws ADCException,
-            PolicyException, UnregisteredCartridgeException, InvalidCartridgeAliasException,
-            DuplicateCartridgeAliasException, RepositoryRequiredException, AlreadySubscribedException,
-            RepositoryCredentialsRequiredException, InvalidRepositoryException, RepositoryTransportException {
-
-		String clusterDomain = "";
-        String clusterSubDomain = CartridgeConstants.DEFAULT_SUBDOMAIN;
-        String mgtClusterDomain = "";
-        String mgtClusterSubDomain = CartridgeConstants.DEFAULT_MGT_SUBDOMAIN;
-        CartridgeSubscription subscription = null;
-        String mysqlPassword = null;
-        Repository repository = null;
-        DataCartridge dataCartridge = null;
-        String cartName = (alias != null && alias.trim().length() > 0) ? alias : cartridgeType;
-        String payloadZipFileName = "/tmp/" + UUID.randomUUID().toString() + ".zip";
-
-		log.info("Subscribing tenant [" + tenantId + "] with username [" + username + "] Cartridge Alias " + alias
-				+ ", Cartridge Type: " + cartridgeType + ", Repo URL: " + repoURL + ", Policy: " + policy);
-		
-		// Assign auto scaling only when necessary.
-		// Muti-tenant cartridge may not need a policy.
-		Policy autoScalingPolicy = null;
-		
-		CartridgeInfo cartridgeInfo;
-		try {
-			cartridgeInfo = getServiceClient().getCartridgeInfo(cartridgeType);
-		} catch (UnregisteredCartridgeException e) {
-			String message = cartridgeType
-					+ " is not a valid cartridge type. Please try again with a valid cartridge type.";
-			log.error(message);
-			throw e;
-		} catch (Exception e) {
-			String message = "Error getting info for " + cartridgeType;
-			log.error(message, e);
-			throw new ADCException(message, e);
-		}
-
-		validateCartridgeAlias(cartName, cartridgeType);
-		
-
-        if (cartridgeType.equals(CartridgeConstants.MYSQL_CARTRIDGE_NAME)) {
-        	
-        	autoScalingPolicy = PolicyHolder.getInstance().getDefaultPolicy();
-        	
-        	if (autoScalingPolicy == null) {
-        		throw new PolicyException("Could not load default auto-scaling policy.");
-        	}
-        	if (log.isDebugEnabled()) {
-    			log.debug("Selected Policy: " + new Gson().toJson(autoScalingPolicy));
-    		}
-        	
-            dataCartridge = new DataCartridge();
-            mysqlPassword = generatePassword();
-            dataCartridge.setPassword(mysqlPassword);
-            dataCartridge.setDataCartridgeType(cartridgeType);
-            dataCartridge.setUserName(CartridgeConstants.MYSQL_DEFAULT_USER);
-            clusterDomain = getDynamicClusterDomain(cartridgeType, cartName, cartridgeInfo);
-
-            registerService(cartridgeType,
-                    clusterDomain,
-                    clusterSubDomain,
-                    createPayload(cartridgeInfo, cartName, autoScalingPolicy, repoURL, mysqlPassword, "localhost", payloadZipFileName, tenantId, tenantDomain),
-                    "*",
-                    cartName + "." + cartridgeInfo.getHostName(),
-                    setRegisterServiceProperties(autoScalingPolicy, tenantId,cartName));
-            deletePayloadFile(payloadZipFileName);
-        } else {
-        	
-			if (!new Boolean(System.getProperty(CartridgeConstants.FEATURE_INTERNAL_REPO_ENABLED))) {
-				if (log.isDebugEnabled()) {
-					log.debug("Internal repo feature is not enabled.");
-				}
-
-				if (repoURL == null || repoURL.trim().length() == 0) {
-					throw new RepositoryRequiredException("External repository required for subscription");
-				}
-			}
-
-			if (repoURL != null && repoURL.trim().length() > 0) {
-				if (log.isDebugEnabled()) {
-					log.debug("Repo URL entered: " + repoURL);
-				}
-				// Validate Remote Repository.
-				validateRepository(repoURL, repoUsername, repoPassword, privateRepo,
-						new Boolean(System.getProperty(CartridgeConstants.FEATURE_EXTERNAL_REPO_VAIDATION_ENABLED)));
-			}
-
-            try {
-                repository = manageRepository(repoURL, repoUsername, repoPassword, cartName, cartridgeInfo, username,
-                        tenantDomain);
-            } catch (Exception e) {
-                log.error(e.getMessage());
-                throw new ADCException(e);
-            }
-        	
-            // TODO: Check logic here
-            if (!cartridgeInfo.getMultiTenant()) {
-            	
-        		if (policy != null && policy.trim().length() > 0) {
-        			autoScalingPolicy = PolicyHolder.getInstance().getPolicy(policy);
-        		} else {
-        			autoScalingPolicy = PolicyHolder.getInstance().getDefaultPolicy();
-        		}
-        		if (autoScalingPolicy == null) {
-        			throw new PolicyException("Could not load auto-scaling policy.");
-        		}
-        		if (log.isDebugEnabled()) {
-        			log.debug("Selected Policy: " + new Gson().toJson(autoScalingPolicy));
-        		}
-
-                if (cartridgeInfo.getProvider().equalsIgnoreCase(CartridgeConstants.PROVIDER_NAME_WSO2)) { //carbon cartridge private jet mode
-
-                    clusterDomain = getDynamicClusterDomain(cartridgeType, cartName, cartridgeInfo);
-                    registerService(cartridgeType,
-                            clusterDomain,
-                            clusterSubDomain,
-                            createCarbonPayload(cartridgeInfo, cartName, alias, payloadZipFileName, tenantDomain, false),
-                            Integer.toString(tenantId),
-                            cartName + "." + cartridgeInfo.getHostName(),
-                            setRegisterServiceProperties(autoScalingPolicy,tenantId,cartName));
-                    deletePayloadFile(payloadZipFileName);
-
-                } else {
-                    clusterDomain = getDynamicClusterDomain(cartridgeType, cartName, cartridgeInfo);
-
-                    String mySQLPassword = null;
-                    String mySQLHostName = null;
-
-                    if (dataCartridgeType != null && dataCartridgeType.trim().length() > 0 && dataCartridgeAlias != null
-                            && dataCartridgeAlias.trim().length() > 0) {
-                        if (log.isInfoEnabled()) {
-                            log.info("Retrieving Data Cartridge info for connect ... Alias : " + dataCartridgeAlias
-                                    + ", Type: " + dataCartridgeType);
-                        }
-
-                        //TODO: Optimize following logic. Same logic is used in MySQLPasswordConfigurer
-                        int maxAttempts = Integer.parseInt(System.getProperty(CartridgeConstants.MAX_ATTEMPTS, "50"));
-                        int i = 0;
-
-                        while (i < maxAttempts) {
-                            i++;
-                            Cartridge c = null;
-                            try {
-                                c = getCartridgeInfo(dataCartridgeAlias, tenantDomain);
-                            } catch (NotSubscribedException e) {
-                                // This cannot happen here.
-                            }
-                            if (c != null) {
-                                if (!c.getStatus().equals("ACTIVE")) {
-                                    try {
-                                        Thread.sleep(3000);
-                                    } catch (InterruptedException ignore) {
-                                    }
-                                } else {
-                                    mySQLPassword = c.getPassword();
-                                    mySQLHostName = c.getIp();
-                                    break;
-                                }
-                            }
-                        }
-                        log.info(" MYSQL Cartridge info retrieved ");
-                    }
-
-                    registerService(cartridgeType,
-                            clusterDomain,
-                            clusterSubDomain,
-                            createPayload(cartridgeInfo, cartName, autoScalingPolicy, repoURL, mySQLPassword,
-                                    mySQLHostName, payloadZipFileName, tenantId, tenantDomain), "*",
-                            cartName + "." + cartridgeInfo.getHostName(),
-                            setRegisterServiceProperties(autoScalingPolicy,tenantId,cartName));
-                    deletePayloadFile(payloadZipFileName);
-                }
-
-            } else {
-            	
-            	boolean allowMultipleSubscription = new Boolean(
-						System.getProperty(CartridgeConstants.FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED));
-
-				if (!allowMultipleSubscription) {
-					// If the cartridge is multi-tenant. We should not let users
-					// subscribe twice.
-					boolean subscribed;
-					try {
-						subscribed = PersistenceManager.isAlreadySubscribed(cartridgeType, tenantId);
-					} catch (Exception e) {
-						String msg = "Error checking whether the cartridge type " + cartridgeType
-								+ " is already subscribed";
-						log.error(msg, e);
-						throw new ADCException(msg, e);
-					}
-					
-					if (subscribed) {
-						String msg = "Already subscribed to " + cartridgeType
-								+ ". This multi-tenant cartridge will not be available to subscribe";
-						if (log.isDebugEnabled()) {
-							log.debug(msg);
-						}
-						throw new AlreadySubscribedException(msg, cartridgeType);
-					}
-				}
-
-                TopologyManagementService topologyService = DataHolder.getTopologyMgtService();
-                DomainContext[] domainContexts = topologyService.getDomainsAndSubdomains(cartridgeType, tenantId);
-                log.info("Retrieved " + domainContexts.length + " domain and corresponding subdomain pairs");
-
-                if (domainContexts.length > 0) {
-                	                        if(domainContexts.length > 2) {
-                	                            if(log.isDebugEnabled())
-                	                                log.debug("Too many domain sub domain pairs");
-                	                       }
-                	
-                	                        for (int i = 0 ; i < domainContexts.length ; i++) {
-                	                            if(domainContexts[i].getSubDomain().equalsIgnoreCase("mgt")) {
-                	                                mgtClusterDomain = domainContexts[i].getDomain();
-                	                                mgtClusterSubDomain = domainContexts[i].getSubDomain();
-                	                            }
-                	                          else
-                	                          {
-                	                              clusterDomain = domainContexts[i].getDomain();
-                	                              clusterSubDomain = domainContexts[i].getSubDomain();
-                	                          }
-                	                      }
-                } else {
-                	String msg = "Domain contexts not found for " + cartridgeType + " and tenant id " + tenantId;
-                    log.warn(msg);
-                    throw new ADCException(msg);
-                }
-            }
-        }
-
-        subscription =
-                createCartridgeSubscription(cartridgeInfo, autoScalingPolicy,
-                        cartridgeType, cartName, tenantId, tenantDomain,
-                        repository, clusterDomain, clusterSubDomain,
-                        mgtClusterDomain, mgtClusterSubDomain, dataCartridge);
-
-        try {
-			PersistenceManager.persistSubscription(subscription);
-		} catch (Exception e) {
-			throw new ADCException("Error Saving Subscription", e);
-		}
-        addDNSEntry(alias, cartridgeType);
-        return createSubscriptionResponse(subscription, repository);
-
-    }
-    
-    private static File getPayload(CartridgeInfo cartridgeInfo, String cartridgeName, Policy policy, String repoURL,
-                                   String mySQLPassword, String mySQLHost, String payloadZipFileName,
-                                   int tenantId, String tenantDomain) throws Exception {
-        String payloadString = "";
-
-        payloadString += "TENANT_RANGE=" + "*";
-        payloadString += ",TENANT_ID=" + tenantId;
-        payloadString +=
-            ",REPO_INFO_EPR=" +
-                    System.getProperty(CartridgeConstants.REPO_INFO_EPR);
-        payloadString +=
-                ",CARTRIDGE_AGENT_EPR=" +
-                        System.getProperty(CartridgeConstants.CARTRIDGE_AGENT_EPR);
-        payloadString += createPortMappingPayloadString(cartridgeInfo);
-        payloadString += ",HOST_NAME=" + cartridgeName + "." + cartridgeInfo.getHostName();
-        payloadString += ",MIN=" + policy.getMinAppInstances();
-        payloadString += ",MAX=" + policy.getMaxAppInstances();
-        payloadString += ",SERVICE=" + cartridgeInfo.getType();
-        payloadString += ",TENANT_CONTEXT=" + tenantDomain;
-        payloadString += ",CARTRIDGE_ALIAS=" + cartridgeName;
-
-        String gitRepoURL = null;
-        if (repoURL != null) {
-            gitRepoURL = repoURL;
-        } else {
-            gitRepoURL = "git@" + System.getProperty(CartridgeConstants.GIT_HOST_IP) + ":" + tenantDomain
-                    + System.getProperty("file.separator") + cartridgeName + ".git";
-        }
-        payloadString += ",GIT_REPO=" + gitRepoURL;
-        payloadString += ",APP_PATH=" + cartridgeInfo.getBaseDir();
-        payloadString += ",BAM_IP=" + System.getProperty(CartridgeConstants.BAM_IP);
-        payloadString += ",BAM_PORT=" + System.getProperty(CartridgeConstants.BAM_PORT);
-
-        // MYSQL params
-        payloadString += ",MYSQL_HOST=" + mySQLHost;
-        payloadString += ",MYSQL_USER=" + "root";
-        payloadString += ",MYSQL_PASSWORD=" + mySQLPassword;
-        
-        DecimalFormat df = new DecimalFormat("##.##");
-        df.setParseBigDecimal(true);
-
-        // Autoscaling params
-        payloadString += ",ALARMING_LOWER_RATE=" + df.format(policy.getAlarmingLowerRate());
-        payloadString += ",ALARMING_UPPER_RATE=" + df.format(policy.getAlarmingUpperRate());
-        payloadString += ",MAX_REQUESTS_PER_SEC=" + policy.getMaxRequestsPerSecond();
-        payloadString += ",ROUNDS_TO_AVERAGE=" + policy.getRoundsToAverage();
-        payloadString += ",SCALE_DOWN_FACTOR=" + df.format(policy.getScaleDownFactor());
-
-        log.info("** Payload ** " + payloadString);
-        
-        String payloadStringTempFile = "launch-params";
-
-        FileWriter fstream = new FileWriter(payloadStringTempFile);
-        BufferedWriter out = new BufferedWriter(fstream);
-        out.write(payloadString);
-        out.close();
-
-        FileOutputStream fos = new FileOutputStream(payloadZipFileName);
-        ZipOutputStream zos = new ZipOutputStream(fos);
-
-		addToZipFile(System.getProperty("user.dir"), payloadStringTempFile, zos);
-
-		File folder = new File(CarbonUtils.getCarbonHome()+
-				File.separator + "repository"
-				+ File.separator + "resources" + File.separator + "user-data");
-		for (File fileEntry : folder.listFiles()) {
-			if (!fileEntry.isDirectory()) {
-				addToZipFile(folder.getPath(), fileEntry.getName(), zos);
-			}
-		}
-
-        zos.close();
-        fos.close();
-
-        return new File(payloadZipFileName);
-    }
-
-    private static File getCarbonPayload (CartridgeInfo cartridgeInfo, String cartridgeName, String cartridgeAlias,
-                                          String payloadZipFileName, String tenantDomain, boolean isMultitenant) throws Exception {
-
-        String payloadString = "";
-        payloadString += "DEPLOYMENT=" + "default";  //TODO: Currently hard coded but can be either manager, worker or default.
-        //payloadString += ",DOMAIN=" + "s2.wso2.com";
-        payloadString += ",SERVICE=" + cartridgeInfo.getType();
-        //payloadString += ",TENANT_ID=" + tenantId;
-        payloadString += ",SC_IP=" + System.getProperty(CartridgeConstants.SC_IP);
-        payloadString += ",CARTRIDGE_ALIAS=" + cartridgeAlias;
-        payloadString += ",MULTITENANT=" + "false";
-
-        if(isMultitenant) { //not used at the moment
-            payloadString += ",DOMAIN=" + "wso2." + cartridgeInfo.getType() + ".domain";
-            payloadString += ",HOSTNAME=" + cartridgeInfo.getType() + ".s2.wso2.com";
-
-        } else {
-            payloadString += ",DOMAIN=" + cartridgeName + "." + cartridgeInfo.getHostName() + "." + cartridgeInfo.getType() +
-                    ".domain";
-            payloadString += ",HOSTNAME=" + cartridgeName + "." + cartridgeInfo.getHostName();
-        }
-
-        log.info("** Payload ** " + payloadString);
-
-        String payloadStringTempFile = "launch-params";
-
-        FileWriter fstream = new FileWriter(payloadStringTempFile);
-        BufferedWriter out = new BufferedWriter(fstream);
-        out.write(payloadString);
-        out.close();
-
-        FileOutputStream fos = new FileOutputStream(payloadZipFileName);
-        ZipOutputStream zos = new ZipOutputStream(fos);
-
-        addToZipFile(System.getProperty("user.dir"), payloadStringTempFile, zos);
-
-        zos.close();
-        fos.close();
-
-        return new File(payloadZipFileName);
-    }
-
-    private static String createPortMappingPayloadString(CartridgeInfo cartridgeInfo) {
-        // port mappings
-        StringBuilder portMapBuilder = new StringBuilder();
-        org.apache.stratos.cloud.controller.util.xsd.PortMapping[] portMappings = cartridgeInfo.getPortMappings();
-        for (org.apache.stratos.cloud.controller.util.xsd.PortMapping portMapping : portMappings) {
-            String port = portMapping.getPort();
-            String protocol = portMapping.getProtocol();
-            String proxyPort = portMapping.getProxyPort();
-            portMapBuilder.append(protocol).append(":").append(port).append(":").append(proxyPort).append("|");
-        }
-
-        // remove last "|" character
-        String portMappingString = portMapBuilder.toString();
-        String portMappingPayloadString = null;
-        if (portMappingString.charAt(portMappingString.length() - 1) == '|') {
-            portMappingPayloadString = portMappingString.substring(0, portMappingString.length() - 1);
-        } else {
-            portMappingPayloadString = portMappingString;
-        }
-
-        return ",PORTS=" + portMappingPayloadString;
-    }
-
-    private static void addToZipFile(String dir, String fileName, ZipOutputStream zos) throws FileNotFoundException,
-            IOException {
-
-        log.info("Writing '" + fileName + "' to zip file");
-
-        File file = new File(dir+File.separator+fileName);
-        FileInputStream fis = new FileInputStream(file);
-        ZipEntry zipEntry = new ZipEntry(fileName);
-        zos.putNextEntry(zipEntry);
-
-        byte[] bytes = new byte[1024];
-        int length;
-        while ((length = fis.read(bytes)) >= 0) {
-            zos.write(bytes, 0, length);
-        }
-
-        zos.closeEntry();
-        fis.close();
-    }
-
-    private static DataHandler createPayload(CartridgeInfo cartridgeInfo, String cartridgeName, Policy policy, String repoURL, String mySQLPwd, String mySQLHost,
-                                             String payloadZipFileName, int tenantId,
-                                             String tenantDomain)
-            throws ADCException {
-
-        FileDataSource dataSource = null;
-        File payloadFile = null;
-        try {
-            payloadFile = getPayload(cartridgeInfo, cartridgeName,
-            		policy, repoURL,
-                    mySQLPwd, mySQLHost, payloadZipFileName, tenantId, tenantDomain);
-            dataSource = new FileDataSource(payloadFile);
-        } catch (Exception e) {
-            String msg = "Exception : " + e.getMessage();
-            log.error(msg, e);
-            throw new ADCException("Subscribe failed ", e);
-        }
-        return new DataHandler(dataSource);
-    }
-
-    private static DataHandler createCarbonPayload (CartridgeInfo cartridgeInfo, String cartridgeName, String cartridgeAlias, String payloadZipFileName,
-                                                    String tenantDomain, boolean isMultitenant) throws ADCException {
-
-        FileDataSource dataSource = null;
-        File payloadFile = null;
-        try {
-            payloadFile = getCarbonPayload(cartridgeInfo, cartridgeName, cartridgeAlias, payloadZipFileName,
-                    tenantDomain, isMultitenant);
-            dataSource = new FileDataSource(payloadFile);
-
-        } catch (Exception e) {
-            String msg = "Exception : " + e.getMessage();
-            log.error(msg, e);
-            throw new ADCException("Subscribe failed ", e);
-        }
-
-        return new DataHandler(dataSource);
-    }
-
-    protected static String getAppDeploymentDirPath(String cartridge, AxisConfiguration axisConfig) {
-        return axisConfig.getRepository().getPath() + File.separator + cartridge;
-    }
-
-    private static CartridgeSubscription createCartridgeSubscription(CartridgeInfo cartridgeInfo,
-                                                                     Policy policy,
-                                                                     String cartridgeType,
-                                                                     String cartridgeName,
-                                                                     int tenantId,
-                                                                     String tenantDomain,
-                                                                     Repository repository,
-                                                                     String clusterDomain,
-                                                                     String clusterSubDomain,
-                                                                     String mgtClusterDomain,
-                                                                     String mgtClusterSubDomain,
-                                                                     DataCartridge dataCartridge) {
-
-        CartridgeSubscription cartridgeSubscription = new CartridgeSubscription();
-        cartridgeSubscription.setCartridge(cartridgeType);
-        cartridgeSubscription.setAlias(cartridgeName);
-        cartridgeSubscription.setClusterDomain(clusterDomain);
-        cartridgeSubscription.setClusterSubdomain(clusterSubDomain);
-               cartridgeSubscription.setMgtClusterDomain(mgtClusterDomain);
-                cartridgeSubscription.setMgtClusterSubDomain(mgtClusterSubDomain);
-        String hostName = null;
-        if (cartridgeInfo.getMultiTenant()) {
-            hostName = cartridgeInfo.getHostName();
-        } else {
-            hostName = cartridgeName + "." + cartridgeInfo.getHostName();
-        }
-        cartridgeSubscription.setHostName(hostName);
-        if (policy != null) {
-        	// Policy can be null for multi-tenant cartridge
-        	cartridgeSubscription.setPolicy(policy.getName());
-        }
-        cartridgeSubscription.setRepository(repository);
-        cartridgeSubscription.setPortMappings(createPortMappings(cartridgeInfo));
-        cartridgeSubscription.setProvider(cartridgeInfo.getProvider());
-        cartridgeSubscription.setDataCartridge(dataCartridge);
-        cartridgeSubscription.setTenantId(tenantId);
-        cartridgeSubscription.setTenantDomain(tenantDomain);
-        cartridgeSubscription.setBaseDirectory(cartridgeInfo.getBaseDir());
-        cartridgeSubscription.setState("PENDING");
-        return cartridgeSubscription;
-    }
-
-
-    private static List<PortMapping> createPortMappings(CartridgeInfo cartridgeInfo) {
-        List<PortMapping> portMappings = new ArrayList<PortMapping>();
-
-        if (cartridgeInfo.getPortMappings() != null) {
-            for (org.apache.stratos.cloud.controller.util.xsd.PortMapping portMapping : cartridgeInfo.getPortMappings()) {
-                PortMapping portMap = new PortMapping();
-                portMap.setPrimaryPort(portMapping.getPort());
-                portMap.setProxyPort(portMapping.getProxyPort());
-                portMap.setType(portMapping.getProtocol());
-                portMappings.add(portMap);
-            }
-        }
-        return portMappings;
-    }
-
-    public static CloudControllerServiceClient getServiceClient() throws AxisFault {
-        if (serviceClient == null) {
-            synchronized (CloudControllerServiceClient.class) {
-                if (serviceClient == null) {
-                    serviceClient = new CloudControllerServiceClient(
-                            System.getProperty(CartridgeConstants.AUTOSCALER_SERVICE_URL));
-                }
-            }
-        }
-        return serviceClient;
-    }
-
-    public static int getTenantId(ConfigurationContext configurationContext) {
-        int tenantId = MultitenantUtils.getTenantId(configurationContext);
-        if(log.isDebugEnabled()) {
-            log.debug("Returning tenant ID : " + tenantId);
-        }
-        return tenantId;
-    }
-
-	private static void validateCartridgeAlias(String alias, String cartridgeType) throws InvalidCartridgeAliasException, DuplicateCartridgeAliasException, ADCException {
-		// Do not use quotes in messages, current UI JavaScript does not work if there are quotes
-		// TODO: Fix message display in UI
-		String patternString = "([a-z0-9]+([-][a-z0-9])*)+";
-        Pattern pattern = Pattern.compile(patternString);
-        
-        if (!pattern.matcher(alias).matches()) {
-        	String msg = "The alias " + alias + " can contain only alpha-numeric lowercase characters. Please enter a valid alias.";
-			log.error(msg);
-			throw new InvalidCartridgeAliasException(msg, cartridgeType, alias);
-        }
-		
-		boolean isAliasTaken = false;
-		try {			
-			isAliasTaken = PersistenceManager.isAliasAlreadyTaken(alias, cartridgeType);			
-		} catch (Exception e) {
-			String msg = "Exception : " + e.getMessage();
-			log.error(msg, e);
-			throw new ADCException("Error when checking alias is already taken", e);
-		}
-		
-		if (isAliasTaken) {
-			String msg = "The alias " + alias + " is already taken. Please try again with a different alias.";
-			log.error(msg);
-			throw new DuplicateCartridgeAliasException(msg, cartridgeType, alias);
-		}
-	}
-	
-	public static RepositoryInformation validateRepository(String repoURL, String repoUsername, String repoPassword,
-			boolean privateRepo, boolean testConnection) throws RepositoryRequiredException, ADCException,
-			RepositoryCredentialsRequiredException, InvalidRepositoryException, RepositoryTransportException {
-		RepositoryInformation repositoryInformation = new RepositoryInformation();
-		repositoryInformation.setRepoURL(repoURL);
-		if (log.isDebugEnabled()) {
-			log.debug("Validating Git Repository");
-		}
-
-		if (repoURL != null && repoURL.trim().length() > 0 && privateRepo) {
-			if (log.isDebugEnabled()) {
-				log.debug("External repo validation is a private repo: " + repoURL);
-			}
-			if (repoUsername == null || repoUsername.trim().length() == 0 || repoPassword == null
-					|| repoPassword.trim().length() == 0) {
-				throw new RepositoryCredentialsRequiredException(
-						"Username and Password are required for private repository");
-			}
-		}
-
-		if (!testConnection) {
-			if (log.isDebugEnabled()) {
-				log.debug("External repo validation is not enabled");
-			}
-			return repositoryInformation;
-		}
-
-		if (repoURL == null || repoURL.trim().length() == 0) {
-			// This means, no repo to validate.
-			return repositoryInformation;
-		}
-		
-		if (log.isDebugEnabled()) {
-			log.debug("External repo validation enabled");
-		}
-
-		// This assumes running on Linux.
-		String parentDirName = "/tmp/" + UUID.randomUUID().toString();
-		CredentialsProvider credentialsProvider = null;
-		if (repoUsername != null && repoUsername.trim().length() > 0 && repoPassword != null
-				&& repoPassword.trim().length() > 0) {
-			if (log.isDebugEnabled()) {
-				log.debug("External repo credentails are passed: " + repoUsername);
-			}
-			credentialsProvider = new UsernamePasswordCredentialsProvider(repoUsername, repoPassword.toCharArray());
-		}
-
-		// Initialize temp local file repo
-		FileRepository localRepo = null;
-		try {
-			File f = new File(parentDirName + "/.git");
-			localRepo = new FileRepository(f);
-			if (log.isDebugEnabled()) {
-				log.debug("Local File Repo: " + f.getAbsoluteFile());
-			}
-		} catch (IOException e) {
-			throw new ADCException("Error creating local file repo", e);
-		}
-
-		Git git = new Git(localRepo);
-		LsRemoteCommand cmd = git.lsRemote().setRemote(repoURL);
-		if (credentialsProvider != null) {
-			cmd.setCredentialsProvider(credentialsProvider);
-		}
-		try {
-			Collection<Ref> collection = cmd.call();
-			List<String> refNames = new ArrayList<String>();
-			if (collection != null) {
-				for (Ref ref : collection) {
-					if (log.isDebugEnabled()) {
-						log.debug(repoURL + ": " + ref.getName());
-					}
-					refNames.add(ref.getName());
-				}
-			}
-			repositoryInformation.setRefName(refNames.toArray(new String[refNames.size()]));
-		} catch (InvalidRemoteException e) {
-			throw new InvalidRepositoryException("Provided repository url is not valid", e);
-		} catch (TransportException e) {
-			throw new RepositoryTransportException("Transport error when checking remote repository", e);
-		} catch (GitAPIException e) {
-			throw new ADCException("Git API error when checking remote repository", e);
-		}
-		return repositoryInformation;
-	}
-
-    private static String generatePassword() {
-
-        final int PASSWORD_LENGTH = 8;
-        StringBuffer sb = new StringBuffer();
-        for (int x = 0; x < PASSWORD_LENGTH; x++) {
-            sb.append((char) ((int) (Math.random() * 26) + 97));
-        }
-        return sb.toString();
-
-    }
-
-    private static void deletePayloadFile(String payloadZipFileName) {
-        File payloadFile = new File(payloadZipFileName);
-        payloadFile.delete();
-        log.info(" Payload file is deleted. ");
-    }
-
-    private static Properties setRegisterServiceProperties(Policy policy, int tenantId, String alias) {
-    	
-    	DecimalFormat df = new DecimalFormat("##.##");
-        df.setParseBigDecimal(true);
-
-        Properties properties = new Properties();
-        List<Property> allProperties = new ArrayList<Property>();
-        // min_app_instances
-        Property property = new Property();
-        property.setName("min_app_instances");
-        property.setValue(df.format(policy.getMinAppInstances()));
-        allProperties.add(property);
-        
-        
-     // max_app_instances
-        property = new Property();
-        property.setName("max_app_instances");
-        property.setValue(df.format(policy.getMaxAppInstances()));
-        allProperties.add(property);
-        
-        // max_requests_per_second
-        property = new Property();
-        property.setName("max_requests_per_second");
-        property.setValue(df.format(policy.getMaxRequestsPerSecond()));
-        allProperties.add(property);
-        
-        // alarming_upper_rate
-        property = new Property();
-        property.setName("alarming_upper_rate");
-        property.setValue(df.format(policy.getAlarmingUpperRate()));
-        allProperties.add(property);
-        
-     // alarming_lower_rate
-        property = new Property();
-        property.setName("alarming_lower_rate");
-        property.setValue(df.format(policy.getAlarmingLowerRate()));
-        allProperties.add(property);
-        
-        // scale_down_factor
-        property = new Property();
-        property.setName("scale_down_factor");
-        property.setValue(df.format(policy.getScaleDownFactor()));
-        allProperties.add(property);
-        
-     // rounds_to_average
-        property = new Property();
-        property.setName("rounds_to_average");
-        property.setValue(df.format(policy.getRoundsToAverage()));
-        allProperties.add(property);
-        
-       // tenant id
-        property = new Property();
-        property.setName("tenant_id");
-        property.setValue(String.valueOf(tenantId));
-        allProperties.add(property);
-        
-        // alias
-        property = new Property();
-        property.setName("alias");
-        property.setValue(String.valueOf(alias));
-        allProperties.add(property);
-        
-        properties.setProperties(allProperties.toArray(new Property[allProperties.size()]));
-        return properties;
-    }
-
-    private static String convertRepoURL(String gitURL) {
-        String convertedHttpURL = null;
-        if (gitURL != null && gitURL.startsWith("git@")) {
-            StringBuilder httpRepoUrl = new StringBuilder();
-            httpRepoUrl.append("http://");
-            String[] urls = gitURL.split(":");
-            String[] hostNameArray = urls[0].split("@");
-            String hostName = hostNameArray[1];
-            httpRepoUrl.append(hostName).append("/").append(urls[1]);
-            convertedHttpURL = httpRepoUrl.toString();
-        } else if (gitURL != null && gitURL.startsWith("http")) {
-            convertedHttpURL = gitURL;
-        }
-        return convertedHttpURL;
-    }
-
-    private static void addDNSEntry(String alias, String cartridgeType) {
-        new DNSManager().addNewSubDomain(alias + "." + cartridgeType, System.getProperty(CartridgeConstants.ELB_IP));
-    }
-
-    private static SubscriptionInfo createSubscriptionResponse(CartridgeSubscription cartridgeSubscription, Repository repository) {
-    	SubscriptionInfo subscriptionInfo = new SubscriptionInfo();
-    	
-        if (repository != null && repository.getRepoName() != null) {
-        	subscriptionInfo.setRepositoryURL(convertRepoURL(repository.getRepoName()));
-        }
-        
-        subscriptionInfo.setHostname(cartridgeSubscription.getHostName());
-        
-        return subscriptionInfo;
-    }
-
-    private static String getDynamicClusterDomain(String cartridgeType, String cartName,
-                                                  CartridgeInfo cartridgeInfo) {
-        return cartName + "." + cartridgeInfo.getHostName() + "." + cartridgeType +
-                ".domain";
-    }
-
-    private static Repository manageRepository(String repoURL, String repoUserName, String repoUserPassword,
-                                               String cartName, CartridgeInfo cartridgeInfo, String username,
-                                               String tenantDomain)
-            throws Exception {
-
-        Repository repository = new Repository();
-        if (repoURL != null && repoURL.trim().length() > 0) {
-            log.info("External REPO URL is provided as [" + repoURL +
-                    "]. Therefore not creating a new repo.");
-            //repository.setRepoName(repoURL.substring(0, repoURL.length()-4)); // remove .git part
-            repository.setRepoName(repoURL);
-            repository.setRepoUserName(repoUserName);
-            repository.setRepoUserPassword(repoUserPassword);
-        } else {
-
-            //log.info("External REPO URL is not provided. Therefore creating a new repo. Adding to Executor");
-            log.info("External git repo url not provided for tenant "
-                    + tenantDomain + ", creating an git internal repository");
-
-            // for internal repos  internal git server username and password is used.
-            repository.setRepoUserName(System.getProperty(CartridgeConstants.INTERNAL_GIT_USERNAME));
-            repository.setRepoUserPassword(System.getProperty(CartridgeConstants.INTERNAL_GIT_PASSWORD));
-            /*repoCreationExecutor.execute(new RepositoryCreator(new RepositoryInfoBean(repoURL,
-                    cartName,
-                    tenantDomain,
-                    repository.getRepoUserName(),
-                    repository.getRepoUserPassword(),
-                    cartridgeInfo.getDeploymentDirs(),
-                    cartridgeInfo)));*/
-            new RepositoryCreator(new RepositoryInfoBean(repoURL,
-                    cartName,
-                    tenantDomain,
-                    repository.getRepoUserName(),
-                    repository.getRepoUserPassword(),
-                    cartridgeInfo.getDeploymentDirs(),
-                    cartridgeInfo)).createInternalRepository();
-            String repoName = tenantDomain + "/" + cartName;
-            repository.setRepoName("https://" + System.getProperty(CartridgeConstants.GIT_HOST_NAME) + ":8443/git/" + repoName);
-
-        }
-        return repository;
-    }
-
-    public static Cartridge getCartridgeInfo(String alias, String tenantDomain) throws ADCException, NotSubscribedException {
-        log.info("Alias: " + alias);
-        if (alias == null) {
-            String msg = "Provided alias is empty";
-            log.error(msg);
-            throw new ADCException("Alias you provided is empty.");
-        }
-
-        CartridgeSubscription sub;
-        try {
-            sub = PersistenceManager.getSubscription(tenantDomain, alias);
-        } catch (Exception e) {
-            String message = "Cannot get subscription info for " + tenantDomain + " and alias " + alias;
-            log.error(message, e);
-            throw new ADCException(message, e);
-        }
-        if (sub == null) {
-            String msg = "Info request for not subscribed cartridge";
-            log.error(msg);
-            throw new NotSubscribedException("You have not subscribed for " + alias, alias);
-        }
-
-        log.info("Cluster domain : " + sub.getClusterDomain() + " cartridge: " + sub.getCartridge());
-        
-        CartridgeInfo cartridgeInfo = null;
-        try {
-            cartridgeInfo = getServiceClient().getCartridgeInfo(sub.getCartridge());
-        } catch (Exception e) {
-            throw new ADCException("Cannot get cartridge info: " + sub.getCartridge(), e);
-        }
-
-        TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
-
-        String[] ips =
-                topologyMgtService.getActiveIPs(sub.getCartridge(),
-                        sub.getClusterDomain(),
-                        sub.getClusterSubdomain());
-        return populateCartridgeInfo(cartridgeInfo, sub, ips, tenantDomain);
-    }
-
-    private static void registerService(String cartridgeType, String domain, String subDomain,
-                                        DataHandler payload, String tenantRange, String hostName, Properties properties)
-            throws ADCException, UnregisteredCartridgeException {
-        log.info("Register service..");
-        try {
-            getServiceClient().register(domain, subDomain, cartridgeType, payload, tenantRange,
-                    hostName, properties);
-        } catch (CloudControllerServiceUnregisteredCartridgeExceptionException e) {
-            String msg = "Exception is occurred in register service operation. Reason :" + e.getMessage();
-            log.error(msg, e);
-            throw new UnregisteredCartridgeException("Not a registered cartridge " + cartridgeType, cartridgeType, e);
-        } catch (RemoteException e) {
-        	log.error("Remote Error", e);
-        	throw new ADCException("An error occurred in subscribing process");
-        }
-    }
-
-    public static Cartridge populateCartridgeInfo(CartridgeInfo cartridgeInfo, CartridgeSubscription sub, String[] ips, String tenantDomain) throws ADCException {
-    	Cartridge cartridge = new Cartridge();
-        if (ips != null && ips.length > 0) {
-			if (log.isDebugEnabled()) {
-				log.debug("Found IPs: " + Arrays.toString(ips) + " for " + cartridgeInfo.getType() + ", "
-						+ sub.getAlias());
-			}
-			if (CartridgeConstants.DATA_CARTRIDGE_PROVIDER.equals(sub.getProvider())) {
-				// FIXME Temporary fix for SPI-301
-				cartridge.setIp(ips[ips.length - 1]);
-				if (sub.getDataCartridge() != null) {
-					if (log.isDebugEnabled()) {
-						log.debug("Data Cartridge Info: " + sub.getDataCartridge().getUserName());
-					}
-					cartridge.setPassword(sub.getDataCartridge().getPassword());
-					cartridge.setDbUserName(sub.getDataCartridge().getUserName());
-				}
-			}
-			if (cartridgeInfo.getMultiTenant()) { // TODO refactor logic for carbon cartridges.
-				cartridge.setStatus(CartridgeConstants.ACTIVE);
-				cartridge.setActiveInstances(ips.length);
-			} else {
-				Map<String, String> instanceIpMap;
-				try {
-					instanceIpMap = PersistenceManager.getCartridgeInstanceInfo(ips, sub.getClusterDomain(),
-							sub.getClusterSubdomain());
-					cartridge.setActiveInstances(Collections.frequency(instanceIpMap.values(),
-							CartridgeConstants.ACTIVE));
-					cartridge.setStatus(checkCartridgeStatus(instanceIpMap));
-				} catch (Exception e) {
-					throw new ADCException("Error checking cartridge status");
-				}
-
-                if(cartridgeInfo.getProvider().equalsIgnoreCase(CartridgeConstants.PROVIDER_NAME_WSO2)) {
-
-                    List<Member> members = getMemberInstances(sub.getClusterDomain(), sub.getClusterSubdomain());
-                    if(members != null) {
-                        int activeInstancesCount = 0;
-                        for (Member member : members) {
-                            if (member != null && member.isActive() && member.getDomain().equals(sub.getClusterDomain())) {
-                                cartridge.setStatus(CartridgeConstants.ACTIVE);
-                                activeInstancesCount ++;
-                            }
-                        }
-                        cartridge.setActiveInstances(activeInstancesCount);
-                    }
-                }
-			}
-        } else {
-            log.warn("IPs have not returned through Topology Management for " + sub.getAlias());
-            cartridge.setStatus(CartridgeConstants.SUBSCRIBED);
-        }
-        cartridge.setDisplayName(cartridgeInfo.getDisplayName());
-        cartridge.setDescription(cartridgeInfo.getDescription());
-        cartridge.setVersion(cartridgeInfo.getVersion());
-        cartridge.setMultiTenant(cartridgeInfo.getMultiTenant());
-
-        List<String> accessURLs = new ArrayList<String>();
-
-        if (cartridgeInfo.getPortMappings() != null) {
-            for (org.apache.stratos.cloud.controller.util.xsd.PortMapping portMapping : cartridgeInfo
-                    .getPortMappings()) {
-                if (portMapping != null) {
-					try {
-						int port = Integer.parseInt(portMapping.getProxyPort());
-	                	String protocol = portMapping.getProtocol();
-
-	                	if ("http".equals(protocol) && port == 80) {
-	                	    port = -1;
-	                	} else if ("https".equals(protocol) && port == 443) {
-	                	    port = -1;
-	                	}
-	                	
-	                	String file = "";
-	                	if (CartridgeConstants.PROVIDER_NAME_WSO2.equals(cartridgeInfo.getProvider()) && !cartridgeInfo.getMultiTenant()) {
-	                		// Carbon Private Jet Cartridges
-	                		file = "/t/" + tenantDomain;
-	                	}
-	                	
-	                	URL serverURL = new URL(protocol, sub.getHostName(), port, file);
-						accessURLs.add(serverURL.toExternalForm());
-					} catch (MalformedURLException e) {
-						if (log.isErrorEnabled()) {
-							log.error("Error getting access URL for " + cartridgeInfo.getType(), e);
-						}
-					} catch (NumberFormatException e) {
-						if (log.isErrorEnabled()) {
-							log.error("Error getting port of access URL for " + cartridgeInfo.getType(), e);
-						}
-					}
-                }
-            }
-        }
-
-        cartridge.setAccessURLs(accessURLs.toArray(new String[accessURLs.size()]));
-
-        cartridge.setCartridgeAlias(sub.getAlias());
-        cartridge.setCartridgeType(sub.getCartridge());
-        cartridge.setHostName(sub.getHostName());
-        cartridge.setPolicy(sub.getPolicy());
-        Policy policy = PolicyHolder.getInstance().getPolicy(sub.getPolicy());
-        if (policy != null) {
-        	cartridge.setPolicyDescription(policy.getDescription());
-        }
-        cartridge.setProvider(sub.getProvider());
-        cartridge.setMappedDomain(sub.getMappedDomain());
-
-        if (sub.getRepository() != null) {
-            cartridge.setRepoURL(convertRepoURL(sub.getRepository().getRepoName()));
-        }
-        return cartridge;
-    }
-
-    private static List<Member> getMemberInstances(String domain, String subDomain) {
-
-        ClusteringAgent clusteringAgent = DataHolder.getServerConfigContext()
-                .getAxisConfiguration().getClusteringAgent();
-        GroupManagementAgent groupMgtAgent = clusteringAgent.getGroupManagementAgent(domain, subDomain);
-
-        if (groupMgtAgent == null) {
-            log.warn("Group Management Agent not found for domain : " + domain +
-                    ", sub domain : " + subDomain);
-            return null;
-        }
-
-        List<Member> members = groupMgtAgent.getMembers();
-        if (members == null || members.isEmpty()) {
-            return null;
-        }
-
-        return members;
-    }
-
-    private static String checkCartridgeStatus(Map<String, String> instanceIpMap) {
-        if (instanceIpMap.values().contains(CartridgeConstants.ACTIVE)) {
-            return CartridgeConstants.ACTIVE;
-        } else
-            return CartridgeConstants.NOT_READY;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeAppType.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeAppType.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeAppType.java
deleted file mode 100644
index 1c23c08..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeAppType.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.utils;
-
-/**
- *
- */
-public class CartridgeAppType {
-	private String appType;
-	private boolean appSpecificMapping;
-
-	public String getAppType() {
-		return appType;
-	}
-
-	public void setAppType(String appType) {
-		this.appType = appType;
-	}
-
-	public boolean isAppSpecificMapping() {
-		return appSpecificMapping;
-	}
-
-	public void setAppSpecificMapping(boolean appSpecificMapping) {
-		this.appSpecificMapping = appSpecificMapping;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConfigFileReader.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConfigFileReader.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConfigFileReader.java
deleted file mode 100644
index 9d28d4a..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConfigFileReader.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.utils;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.utils.CarbonUtils;
-
-public class CartridgeConfigFileReader {
-
-	private static String carbonHome = CarbonUtils.getCarbonHome();
-
-	private static final Log log = LogFactory.getLog(CartridgeConfigFileReader.class);
-
-	/**
-	 * 
-	 * Reads cartridge-config.properties file and assign properties to system
-	 * properties
-	 * 
-	 */
-	public static void readProperties() {
-
-		Properties properties = new Properties();
-		try {
-			properties.load(new FileInputStream(carbonHome + File.separator + "repository" +
-			                                    File.separator + "conf" + File.separator +
-			                                    "cartridge-config.properties"));
-		} catch (Exception e) {
-			log.error("Exception is occurred in reading properties file. Reason:" + e.getMessage());
-		}
-		if (log.isInfoEnabled()) {
-			log.info("Setting config properties into System properties");
-		}
-
-		for (String name : properties.stringPropertyNames()) {
-			String value = properties.getProperty(name);
-			System.setProperty(name, value);
-		}
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConstants.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConstants.java
deleted file mode 100644
index 0340e61..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConstants.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.utils;
-
-public class CartridgeConstants {
-    public static final String SC_IP = "sc.ip";
-	public static final String AUTOSCALER_SERVICE_URL = "autoscalerService.url";
-    public static final String ALIAS_NAMESPACE ="http://org.wso2.securevault/configuration";
-    public static final String ALIAS_LOCALPART ="secretAlias";
-    public static final String ALIAS_PREFIX ="svns";
-	public static final String CARTRIDGE_AGENT_EPR = "cartridge.agent.epr";
-	public static final String GIT_HOST_NAME = "git.host.name";
-	public static final String GIT_HOST_IP = "git.host.ip";
-	public static final String SUBSCRIPTION_ACTIVE = "SUBSCRIPTION_ACTIVE";
-	public static final String SUBSCRIPTION_INACTIVE = "SUBSCRIPTION_INACTIVE";
-	public static final String REPO_NOTIFICATION_URL = "git.repo.notification.url";
-	public static final String ACTIVE = "ACTIVE";
-	public static final String NOT_READY = "NOT-READY";
-	public static final String SUBSCRIBED = "SUBSCRIBED";
-
-	public static final String DB_DATASOURCE = "adc.datasource";
-	public static final String DB_URL = "adc.jdbc.url";
-	public static final String DB_DRIVER = "adc.jdbc.driver";
-	public static final String DB_USERNAME = "adc.jdbc.username";
-	public static final String DB_PASSWORD = "adc.jdbc.password";
-	public static final String BAM_IP = "bam.ip";
-	public static final String BAM_PORT = "bam.port";
-	public static final String SUDO_SH = "sudo sh";
-	public static final String APPEND_SCRIPT = "append.script";
-	public static final String REMOVE_SCRIPT = "remove.script";
-	public static final String BIND_FILE_PATH = "bind.file.path";
-	public static final String ELB_IP = "elb.ip";
-	public static final String REPO_KEY_PATH = "repo.key.path";
-	public static final String REPO_KEY = "repo.key";
-	public static final String MAX_ATTEMPTS = "max.attempts";
-	public static final String CARTRIDGE_KEY = "cartridge.key";
-	
-	public static final String FEATURE_EXTERNAL_REPO_VAIDATION_ENABLED = "feature.externalrepo.validation.enabled";
-	public static final String FEATURE_INTERNAL_REPO_ENABLED = "feature.internalrepo.enabled";
-	public static final String FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED = "feature.multitenant.multiplesubscription.enabled";
-	
-	public static final String MYSQL_CARTRIDGE_NAME = "mysql";
-	public static final String DEFAULT_SUBDOMAIN = "__$default";
-	public static final String DEFAULT_MGT_SUBDOMAIN = "mgt";
-	public static final String MYSQL_DEFAULT_USER = "root";
-	public static final String PROVIDER_NAME_WSO2 = "wso2";
-	public static final String NOT_SUBSCRIBED = "NOT-SUBSCRIBED";
-    public static final String SECURITY_KEY_FILE = "gitRepoKey.xml";
-    public static final String SECURITY_KEY = "securityKey";
-    public static final String DEFAULT_SECURITY_KEY = "tvnw63ufg9gh5111";
-    public static final String DATA_CARTRIDGE_PROVIDER = "data";
-	public static final String REPO_INFO_EPR = "repository.info.epr";
-	public static final String INTERNAL_GIT_USERNAME = "internal.repo.username";
-	public static final String INTERNAL_GIT_PASSWORD = "internal.repo.password";
-
-    public static final class DomainMappingInfo {
-		public static final String ACTUAL_HOST = "actual.host";
-		public static final String HOSTINFO = "hostinfo/";
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeDomain.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeDomain.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeDomain.java
deleted file mode 100644
index 2207b43..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeDomain.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.utils;
-
-/**
- *
- */
-public class CartridgeDomain {
-
-	private String primaryPort;
-	private String proxyPort;
-	private String type;
-	private String tenantId;
-	private int min;
-	private int max;
-	private String cartridgeType;
-	private boolean volume;
-	private String tenantDomain;
-	private String clusterDomain;
-	private String clusterSubDomain;
-
-	private String hostName;
-	private boolean started;
-
-	public String getPrimaryPort() {
-		return primaryPort;
-	}
-
-	public String getProxyPort() {
-		return proxyPort;
-	}
-
-	public String getType() {
-		return type;
-	}
-
-	public String getTenantId() {
-		return tenantId;
-	}
-
-	public int getMin() {
-		return min;
-	}
-
-	public int getMax() {
-		return max;
-	}
-
-	public String getCartridgeType() {
-		return cartridgeType;
-	}
-
-	public boolean getVolume() {
-		return volume;
-	}
-
-	public String getTenantDomain() {
-		return tenantDomain;
-	}
-
-	public void setPrimaryPort(String primaryPort) {
-		this.primaryPort = primaryPort;
-	}
-
-	public void setProxyPort(String proxyPort) {
-		this.proxyPort = proxyPort;
-	}
-
-	public void setType(String type) {
-		this.type = type;
-	}
-
-	public void setTenantId(String tenantId) {
-		this.tenantId = tenantId;
-	}
-
-	public void setMin(int min) {
-		this.min = min;
-	}
-
-	public void setMax(int max) {
-		this.max = max;
-	}
-
-	public void setCartridgeType(String cartridgeType) {
-		this.cartridgeType = cartridgeType;
-	}
-
-	public void setVolume(boolean volume) {
-		this.volume = volume;
-	}
-
-	public void setTenantDomain(String tenantDomain) {
-		this.tenantDomain = tenantDomain;
-	}
-
-	public void setStarted(boolean started) {
-		this.started = started;
-	}
-
-	public boolean isStarted() {
-		return started;
-	}
-
-	public String getHostName() {
-		return hostName;
-	}
-
-	public void setHostName(String hostName) {
-		this.hostName = hostName;
-	}
-
-	public String getClusterDomain() {
-		return clusterDomain;
-	}
-
-	public void setClusterDomain(String clusterDomain) {
-		this.clusterDomain = clusterDomain;
-	}
-
-	public String getClusterSubDomain() {
-		return clusterSubDomain;
-	}
-
-	public void setClusterSubDomain(String clusterSubDomain) {
-		this.clusterSubDomain = clusterSubDomain;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/DomainInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/DomainInfo.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/DomainInfo.java
deleted file mode 100644
index 53fed09..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/DomainInfo.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.utils;
-
-public class DomainInfo {
-
-	String domain;
-	String subDomain;
-
-	public String getDomain() {
-		return domain;
-	}
-
-	public void setDomain(String domain) {
-		this.domain = domain;
-	}
-
-	public String getSubDomain() {
-		return subDomain;
-	}
-
-	public void setSubDomain(String subDomain) {
-		this.subDomain = subDomain;
-	}
-
-}


[34/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SyncCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SyncCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SyncCommand.java
new file mode 100644
index 0000000..6e21a4d
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SyncCommand.java
@@ -0,0 +1,76 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.CommandLineService;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class SyncCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(SyncCommand.class);
+
+	public SyncCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.SYNC_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Synchronize GIT repository for the subscribed cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge alias]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length == 1) {
+			String alias = args[0];
+			if (logger.isDebugEnabled()) {
+				logger.debug("Synchronizing repository for alias {}", alias);
+			}
+
+			CommandLineService.getInstance().sync(alias);
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/UnsubscribeCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/UnsubscribeCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/UnsubscribeCommand.java
new file mode 100644
index 0000000..9b178e4
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/UnsubscribeCommand.java
@@ -0,0 +1,130 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.CommandLineService;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class UnsubscribeCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(UnsubscribeCommand.class);
+	
+	private final Options options;;
+
+	public UnsubscribeCommand() {
+		options = constructOptions();
+	}
+	
+	/**
+	 * Construct Options.
+	 * 
+	 * @return Options expected from command-line.
+	 */
+	private Options constructOptions() {
+		final Options options = new Options();
+		Option forceOption = new Option(CliConstants.FORCE_OPTION, CliConstants.FORCE_LONG_OPTION, false,
+				"Never prompt for confirmation");
+		options.addOption(forceOption);
+		return options;
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.UNSUBSCRIBE_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Unsubscribe from a subscribed cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge alias]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length > 0) {
+			String[] remainingArgs = null;
+			String alias = null;
+			boolean force = false;
+			final CommandLineParser parser = new GnuParser();
+			CommandLine commandLine;
+			try {
+				commandLine = parser.parse(options, args);
+				remainingArgs = commandLine.getArgs();
+				if (remainingArgs != null && remainingArgs.length == 1) {
+					// Get alias
+					alias = remainingArgs[0];
+				} else {
+					if (logger.isDebugEnabled()) {
+						logger.debug("Unsubscribe: not enough arguments");
+					}
+					context.getStratosApplication().printUsage(getName());
+					return CliConstants.BAD_ARGS_CODE;
+				}
+
+				if (commandLine.hasOption(CliConstants.FORCE_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Force option is passed");
+					}
+					force = true;
+				}
+				if (logger.isDebugEnabled()) {
+					logger.debug("Unsubscribing {}, Force Option: {}", alias, force);
+				}
+				if (force || context.getApplication().getConfirmation("Are you sure you want to unsubscribe?")) {
+					System.out.format("Unsubscribing the cartridge %s%n", alias);
+					CommandLineService.getInstance().unsubscribe(alias);
+				}
+				return CliConstants.SUCCESSFUL_CODE;
+			} catch (ParseException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error parsing arguments", e);
+				}
+				System.out.println(e.getMessage());
+				return CliConstants.BAD_ARGS_CODE;
+			}
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return options;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/completer/CommandCompleter.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/completer/CommandCompleter.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/completer/CommandCompleter.java
new file mode 100644
index 0000000..3405762
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/completer/CommandCompleter.java
@@ -0,0 +1,133 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.completer;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import jline.console.completer.ArgumentCompleter;
+import jline.console.completer.Completer;
+import jline.console.completer.StringsCompleter;
+
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.text.StrTokenizer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.StratosApplication;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class CommandCompleter implements Completer {
+
+	private static final Logger logger = LoggerFactory.getLogger(StratosApplication.class);
+
+	/**
+	 * Keep arguments for each command
+	 */
+	private final Map<String, Collection<String>> argumentMap;
+	
+	private final Completer helpCommandCompleter;
+
+	private final Completer defaultCommandCompleter;
+
+	public CommandCompleter(Map<String, Command<StratosCommandContext>> commands) {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Creating auto complete for {} commands", commands.size());
+		}
+		argumentMap = new HashMap<String, Collection<String>>();
+		defaultCommandCompleter = new StringsCompleter(commands.keySet());
+		helpCommandCompleter = new ArgumentCompleter(new StringsCompleter(CliConstants.HELP_ACTION),
+				defaultCommandCompleter);
+		for (String action : commands.keySet()) {
+			Command<StratosCommandContext> command = commands.get(action);
+			Options commandOptions = command.getOptions();
+			if (commandOptions != null) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("Creating argument completer for command: {}", action);
+				}
+				List<String> arguments = new ArrayList<String>();
+				Collection<?> allOptions = commandOptions.getOptions();
+				for (Object o : allOptions) {
+					Option option = (Option) o;
+					String longOpt = option.getLongOpt();
+					String opt = option.getOpt();
+					if (StringUtils.isNotBlank(longOpt)) {
+						arguments.add("--" + longOpt);
+					} else if (StringUtils.isNotBlank(opt)) {
+						arguments.add("-" + opt);
+					}
+				}
+
+				argumentMap.put(action, arguments);
+			}
+		}
+	}
+
+	@Override
+	public int complete(String buffer, int cursor, List<CharSequence> candidates) {
+		if (logger.isTraceEnabled()) {
+			logger.trace("Buffer: {}, cursor: {}", buffer, cursor);
+			logger.trace("Candidates {}", candidates);
+		}
+		if (StringUtils.isNotBlank(buffer)) {
+			// User is typing a command
+			StrTokenizer strTokenizer = new StrTokenizer(buffer);
+			String action = strTokenizer.next();
+			Collection<String> arguments = argumentMap.get(action);
+			if (arguments != null) {
+				if (logger.isTraceEnabled()) {
+					logger.trace("Arguments found for {}, Tokens: {}", action, strTokenizer.getTokenList());
+					logger.trace("Arguments for {}: {}", action, arguments);
+				}
+				List<String> args = new ArrayList<String>(arguments);
+				List<Completer> completers = new ArrayList<Completer>();
+				for (String token : strTokenizer.getTokenList()) {
+					boolean argContains = arguments.contains(token);
+					if (token.startsWith("-") && !argContains) {
+						continue;
+					}
+					if (argContains) {
+						if (logger.isTraceEnabled()) {
+							logger.trace("Removing argument {}", token);
+						}
+						args.remove(token);
+					}
+					completers.add(new StringsCompleter(token));
+				}
+				completers.add(new StringsCompleter(args));
+				Completer completer = new ArgumentCompleter(completers);
+				return completer.complete(buffer, cursor, candidates);
+			} else if (CliConstants.HELP_ACTION.equals(action)) {
+				// For help action, we need to display available commands as arguments
+				return helpCommandCompleter.complete(buffer, cursor, candidates);
+			}
+		}
+		if (logger.isTraceEnabled()) {
+			logger.trace("Using Default Completer...");
+		}
+		return defaultCommandCompleter.complete(buffer, cursor, candidates);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/exception/CommandException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/exception/CommandException.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/exception/CommandException.java
new file mode 100644
index 0000000..a462500
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/exception/CommandException.java
@@ -0,0 +1,39 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.exception;
+
+public class CommandException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	public CommandException() {
+	}
+
+	public CommandException(String message) {
+		super(message);
+	}
+
+	public CommandException(Throwable cause) {
+		super(cause);
+	}
+
+	public CommandException(String message, Throwable cause) {
+		super(message, cause);
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CliConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CliConstants.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CliConstants.java
new file mode 100644
index 0000000..986bb72
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CliConstants.java
@@ -0,0 +1,130 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.adc.mgt.cli.utils;
+
+/**
+ * Constants for CLI Tool
+ */
+public class CliConstants {
+
+	public static final String STRATOS_APPLICATION_NAME = "stratos";
+
+	public static final String STRATOS_URL_ENV_PROPERTY = "STRATOS_URL";
+
+	public static final String STRATOS_USERNAME_ENV_PROPERTY = "STRATOS_USERNAME";
+
+	public static final String STRATOS_PASSWORD_ENV_PROPERTY = "STRATOS_PASSWORD";
+
+	public static final String STRATOS_SHELL_PROMPT = "stratos> ";
+	
+	public static final int SUCCESSFUL_CODE = 0;
+	public static final int BAD_ARGS_CODE = 1;
+	public static final int ERROR_CODE = 2;
+
+
+	/**
+	 * The Directory for storing configuration
+	 */
+	public static final String STRATOS_DIR = ".stratos";
+	public static final String STRATOS_HISTORY_DIR = ".history";
+
+	public static final String HELP_ACTION = "help";
+
+	/**
+	 * Subscribe to a cartridge.
+	 */
+	public static final String SUBSCRIBE_ACTION = "subscribe";
+
+	public static final String UNSUBSCRIBE_ACTION = "unsubscribe";
+
+	/**
+	 * List the subscribed cartridges
+	 */
+	public static final String LIST_ACTION = "list";
+
+	/**
+	 * List the available cartridges
+	 */
+	public static final String CARTRIDGES_ACTION = "cartridges";
+
+	/**
+	 * Give information of a cartridge.
+	 */
+	public static final String INFO_ACTION = "info";
+
+	/**
+	 * Synchronize repository
+	 */
+	public static final String SYNC_ACTION = "sync";
+
+	/**
+	 * Domain mapping
+	 */
+	public static final String ADD_DOMAIN_MAPPING_ACTION = "add-domain-mapping";
+	/**
+	 * Remove Domain mapping
+	 */
+	public static final String REMOVE_DOMAIN_MAPPING_ACTION = "remove-domain-mapping";
+	
+	/**
+	 * List the available policies
+	 */
+	public static final String POLICIES_ACTION = "policies";
+
+	/**
+	 * Exit action
+	 */
+	public static final String EXIT_ACTION = "exit";
+
+	public static final String REPO_URL_OPTION = "r";
+	public static final String REPO_URL_LONG_OPTION = "repoURL";
+	
+	public static final String PRIVATE_REPO_OPTION = "i";
+	public static final String PRIVATE_REPO_LONG_OPTION = "privateRepo";
+
+	public static final String USERNAME_OPTION = "u";
+	public static final String USERNAME_LONG_OPTION = "username";
+
+	public static final String PASSWORD_OPTION = "p";
+	public static final String PASSWORD_LONG_OPTION = "password";
+
+	public static final String HELP_OPTION = "h";
+	public static final String HELP_LONG_OPTION = "help";
+	
+	public static final String POLICY_OPTION = "o";
+	public static final String POLICY_LONG_OPTION = "policy";
+	
+	public static final String CONNECT_OPTION = "c";
+	public static final String CONNECT_LONG_OPTION = "connect";
+	
+	public static final String DATA_ALIAS_OPTION = "d";
+	public static final String DATA_ALIAS_LONG_OPTION = "data-alias";
+	
+	public static final String FULL_OPTION = "f";
+	public static final String FULL_LONG_OPTION = "full";
+	
+	public static final String FORCE_OPTION = "f";
+	public static final String FORCE_LONG_OPTION = "force";
+	
+	public static final String TRACE_OPTION = "trace";
+	
+	public static final String DEBUG_OPTION = "debug";
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CommandLineUtils.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CommandLineUtils.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CommandLineUtils.java
new file mode 100644
index 0000000..c6167f2
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CommandLineUtils.java
@@ -0,0 +1,94 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.utils;
+
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+
+public class CommandLineUtils {
+	
+	private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("Resources");
+
+	public static <T> void printTable(T[] data, RowMapper<T> mapper, String... headers) {
+		if (data == null) {
+			return;
+		}
+		// The maximum number of columns
+		// All data String[] length must be equal to this
+		int columns = headers.length;
+		int rows = data.length + 1;
+
+		String[][] table = new String[rows][columns];
+		table[0] = headers;
+
+		for (int i = 0; i < data.length; i++) {
+			T t = data[i];
+			table[i + 1] = mapper.getData(t);
+		}
+
+		// Find the maximum length of a string in each column
+		int[] lengths = new int[columns];
+		for (int i = 0; i < table.length; i++) {
+			for (int j = 0; j < table[i].length; j++) {
+				lengths[j] = Math.max(table[i][j].length(), lengths[j]);
+			}
+		}
+
+		// The border rows
+		String borders[] = new String[lengths.length];
+		// Generate a format string for each column
+		String[] formats = new String[lengths.length];
+		for (int i = 0; i < lengths.length; i++) {
+			StringBuilder stringBuilder = new StringBuilder();
+			stringBuilder.append("+");
+			for (int j = 0; j < lengths[i] + 2; j++) {
+				stringBuilder.append("-");
+			}
+			boolean finalColumn = (i + 1 == lengths.length);
+			if (finalColumn) {
+				stringBuilder.append("+\n");
+			}
+			borders[i] = stringBuilder.toString();
+			formats[i] = "| %1$-" + lengths[i] + "s " + (finalColumn ? "|\n" : "");
+		}
+
+		// Print the table
+		for (int i = 0; i < table.length; i++) {
+			for (int j = 0; j < table[i].length; j++) {
+				System.out.print(borders[j]);
+			}
+			for (int j = 0; j < table[i].length; j++) {
+				System.out.format(formats[j], table[i][j]);
+			}
+			if (i + 1 == table.length) {
+				for (int j = 0; j < table[i].length; j++) {
+					System.out.print(borders[j]);
+				}
+			}
+		}
+	}
+	
+	public static String getMessage(String key, Object... args) {
+		String message = BUNDLE.getString(key);
+		if (args != null && args.length > 0) {
+			message = MessageFormat.format(message, args);
+		}
+		return message;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/RowMapper.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/RowMapper.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/RowMapper.java
new file mode 100644
index 0000000..0a61ad7
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/utils/RowMapper.java
@@ -0,0 +1,23 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.utils;
+
+public interface RowMapper<T> {
+	String[] getData(T t);
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/resources/Resources.properties
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/resources/Resources.properties b/components/org.apache.stratos.adc.mgt.cli/src/main/resources/Resources.properties
new file mode 100644
index 0000000..fcec66f
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/resources/Resources.properties
@@ -0,0 +1,25 @@
+
+
+cannot.list.available.cartridges=An error occurred when getting available cartridges.
+cannot.list.subscribed.cartridges=An error occurred when getting subscribed cartridges.
+cannot.get.cartridge.info=An error occurred when getting cartridge information.
+cannot.syncrepo=Synchronization failed
+cannot.subscribe=Subscribe failed
+cannot.unsubscribe=Unsubscribe failed
+cannot.mapdomain=Map Domain failed
+cannot.removedomain=Mapped Domain removal failed
+
+notsubscribed.error=You have not subscribed to {0}
+domainmapping.exists.error=The domain mapping {0} already exists for {1}
+
+cartridge.notregistered=Cartridge {0} is not registered
+cartridge.invalid.alias=The provided cartridge alias is not valid. The alias can contain only lowercase characters and numbers.
+cartridge.already.subscribed=You have already subscribed for cartridge type {0}
+cartridge.alias.duplicate=Duplicate cartridge alias {0}
+
+policy.error=Could not load policy.
+repository.required=An external repository required
+repository.credentials.required=Username and Password are required for the repository: {0}
+repository.transport.error=Error connecting to the repository: {0}
+repository.invalid.error=Invalid repository: {0}
+remote.error=Error connecting to back-end service.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/resources/log4j.properties b/components/org.apache.stratos.adc.mgt.cli/src/main/resources/log4j.properties
new file mode 100755
index 0000000..958eb9c
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/resources/log4j.properties
@@ -0,0 +1,15 @@
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.Target=System.out
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} [%t] %n%m%n
+
+log4j.appender.file=org.apache.log4j.RollingFileAppender
+log4j.appender.file.File=${user.home}/.stratos/.stratos-cli.log
+log4j.appender.file.MaxFileSize=10MB
+log4j.appender.file.MaxBackupIndex=100
+log4j.appender.file.layout=org.apache.log4j.PatternLayout
+log4j.appender.file.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} [%t] %n%m%n
+
+#Loggers
+log4j.rootLogger=info, file
+log4j.logger.org.wso2.carbon.adc.mgt.cli=info
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/resources/wso2carbon.jks
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/resources/wso2carbon.jks b/components/org.apache.stratos.adc.mgt.cli/src/main/resources/wso2carbon.jks
new file mode 100644
index 0000000..7942c53
Binary files /dev/null and b/components/org.apache.stratos.adc.mgt.cli/src/main/resources/wso2carbon.jks differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/pom.xml b/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/pom.xml
deleted file mode 100644
index ccf706b..0000000
--- a/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/pom.xml
+++ /dev/null
@@ -1,87 +0,0 @@
-<!--
-  ~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
-  ~
-  ~ Licensed under the Apache License, Version 2.0 (the "License");
-  ~ you may not use this file except in compliance with the License.
-  ~ You may obtain a copy of the License at
-  ~
-  ~ http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing, software
-  ~ distributed under the License is distributed on an "AS IS" BASIS,
-  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~ See the License for the specific language governing permissions and
-  ~ limitations under the License.
-  -->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.adc.mgt.repository.synchronizer</artifactId>
-    <version>2.1.1</version>
-    <name>Apache Stratos - Repository Synchronizer</name>
-    <description>Repository Synchronizer</description>
-    <packaging>war</packaging>
-
-    <build>
-        <plugins>
-            <plugin>
-                <artifactId>maven-compiler-plugin</artifactId>
-                <configuration>
-                    <source>1.5</source>
-                    <target>1.5</target>
-                </configuration>
-                <version>2.3.2</version>
-            </plugin>
-            <plugin>
-                <artifactId>maven-war-plugin</artifactId>
-                <version>2.2</version>
-                <configuration>                     
-                    <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
-                    <warName>${project.artifactId}</warName>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-
-    <dependencies>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-transports-http</artifactId>
-            <version>2.6.2</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
-            <version>2.6.2</version>
-        </dependency>
-        <dependency>
-            <groupId>commons-httpclient</groupId>
-            <artifactId>commons-httpclient</artifactId>
-            <version>3.1</version>
-        </dependency>
-        <dependency>
-            <groupId>javax.ws.rs</groupId>
-            <artifactId>jsr311-api</artifactId>
-            <version>1.1.1</version>
-        </dependency>
-        <dependency>
-        <groupId>net.sf.json-lib</groupId>
-        <artifactId>json-lib</artifactId>
-        <version>2.4</version>
-        <classifier>jdk15</classifier>
-    </dependency>
-            
-    </dependencies>
-
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/java/org/apache/stratos/adc/mgt/reposync/service/RepositorySynchronizer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/java/org/apache/stratos/adc/mgt/reposync/service/RepositorySynchronizer.java b/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/java/org/apache/stratos/adc/mgt/reposync/service/RepositorySynchronizer.java
deleted file mode 100644
index 937baab..0000000
--- a/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/java/org/apache/stratos/adc/mgt/reposync/service/RepositorySynchronizer.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 
- */
-package org.apache.stratos.adc.mgt.reposync.service;
-
-import java.util.Map;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.FormParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.core.MediaType;
-
-import net.sf.json.JSONObject;
-
-/**
- * @author wso2
- * 
- */
-@Path("/reposyncservice/")
-public class RepositorySynchronizer {
-
-	@POST
-	@Path("/notify/")
-	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
-	public void execute(@FormParam("payload") String payload) {
-		Map jsonObject = JSONObject.fromObject(payload);
-		System.out.println("Printing......");
-		Map repoMap = (Map) jsonObject.get("repository");
-		System.out.println("-------------");
-		System.out.println("Repo URL : " + repoMap.get("url"));
-		System.out.println("-------------");
-		System.out.println("-------------");
-		System.out.println("-------------");
-		System.out.println("---JSON customer : " + payload);
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/cxf-servlet.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/cxf-servlet.xml
deleted file mode 100644
index 9454028..0000000
--- a/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/cxf-servlet.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<!--
-  ~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
-  ~
-  ~ Licensed under the Apache License, Version 2.0 (the "License");
-  ~ you may not use this file except in compliance with the License.
-  ~ You may obtain a copy of the License at
-  ~
-  ~ http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing, software
-  ~ distributed under the License is distributed on an "AS IS" BASIS,
-  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~ See the License for the specific language governing permissions and
-  ~ limitations under the License.
-  -->
-
-<beans xmlns="http://www.springframework.org/schema/beans"
-       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xmlns:jaxrs="http://cxf.apache.org/jaxrs"
-       xsi:schemaLocation="
-         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
-         http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
-
-    <jaxrs:server id="repoSynchronizer" address="/notify">
-        <jaxrs:serviceBeans>
-            <ref bean="serviceBean"/>
-        </jaxrs:serviceBeans>
-    </jaxrs:server>
-
-    <bean id="serviceBean" class="org.apache.stratos.adc.mgt.reposync.service.RepositorySynchronizer"/>
-</beans>
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/web.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/web.xml b/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 696d5cc..0000000
--- a/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,49 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  ~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
-  ~
-  ~ Licensed under the Apache License, Version 2.0 (the "License");
-  ~ you may not use this file except in compliance with the License.
-  ~ You may obtain a copy of the License at
-  ~
-  ~ http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing, software
-  ~ distributed under the License is distributed on an "AS IS" BASIS,
-  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~ See the License for the specific language governing permissions and
-  ~ limitations under the License.
-  -->
-
-<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
-         http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
-
-    <display-name>JAX-WS/JAX-RS Webapp</display-name>
-
-    <servlet>
-        <servlet-name>JAXServlet</servlet-name>
-        <display-name>JAX-WS/JAX-RS Servlet</display-name>
-        <description>JAX-WS/JAX-RS Endpoint</description>
-        <servlet-class>
-            org.apache.cxf.transport.servlet.CXFServlet
-        </servlet-class>
-        <init-param>
-            <param-name>service-list-stylesheet</param-name>
-            <param-value>servicelist.css</param-value>
-        </init-param>
-        <load-on-startup>1</load-on-startup>
-    </servlet>
-
-    <servlet-mapping>
-        <servlet-name>JAXServlet</servlet-name>
-        <url-pattern>/services/*</url-pattern>
-    </servlet-mapping>
-
-    <session-config>
-        <session-timeout>60</session-timeout>
-    </session-config>
-
-</web-app>
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/servicelist.css
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/servicelist.css b/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/servicelist.css
deleted file mode 100644
index bbc4987..0000000
--- a/components/org.apache.stratos.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/servicelist.css
+++ /dev/null
@@ -1,117 +0,0 @@
-@CHARSET "ISO-8859-1";
-
-/* http://meyerweb.com/eric/tools/css/reset/ 
-   v2.0 | 20110126
-   License: none (public domain)
-*/
-
-html, body, div, span, applet, object, iframe,
-h1, h2, h3, h4, h5, h6, p, blockquote, pre,
-a, abbr, acronym, address, big, cite, code,
-del, dfn, em, img, ins, kbd, q, s, samp,
-small, strike, strong, sub, sup, tt, var,
-b, u, i, center,
-dl, dt, dd, ol, ul, li,
-fieldset, form, label, legend,
-table, caption, tbody, tfoot, thead, tr, th, td,
-article, aside, canvas, details, embed, 
-figure, figcaption, footer, header, hgroup, 
-menu, nav, output, ruby, section, summary,
-time, mark, audio, video {
-	margin: 0;
-	padding: 0;
-	border: 0;
-	font-size: 100%;
-	font: inherit;
-	vertical-align: baseline;
-}
-/* HTML5 display-role reset for older browsers */
-article, aside, details, figcaption, figure, 
-footer, header, hgroup, menu, nav, section {
-	display: block;
-}
-
-html {
-	background: #efefef;
-}
-
-body {
-	line-height: 1;
-	width:960px;
-	margin:auto;
-	background:white;
-	padding:10px;
-	box-shadow:0px 0px 5px #CCC;
-	font-family:"Lucida Grande","Lucida Sans","Microsoft Sans Serif", "Lucida Sans Unicode","Verdana","Sans-serif","trebuchet ms" !important;
-	
-}
-ol, ul {
-	list-style: none;
-}
-blockquote, q {
-	quotes: none;
-}
-blockquote:before, blockquote:after,
-q:before, q:after {
-	content: '';
-	content: none;
-}
-table {
-	border-collapse: collapse;
-	border-spacing: 0;
-	width:960px;
-	border:solid 1px #ccc;
-}
-
-table a {
-	font-size:12px;
-	color:#1e90ff;
-	padding:7px;
-float:left;	
-;
-}
-
-.heading {
-	font-size: 18px;
-	margin-top: 20px;
-	float:left;
-	color:#0067B1;
-	margin-bottom:20px;
-	padding-top:20px;
-}
-
-.field {
-	font-weight: normal;
-	width:120px;
-	font-size:12px;
-	float:left;
-	padding:7px;
-	clear:left;
-}
-.value {
-	font-weight: bold;
-	font-size:12px;
-	float:left;
-	padding:7px;
-	clear:right;
-}
-.porttypename {
-	font-weight: bold;
-	font-size:14px;
-}
-UL {
-	margin-top: 0;
-}
-LI {
-	font-weight: normal;
-	font-size:12px;
-	margin-top:10px;
-}
-
-TD {
-	border:1px solid #ccc;
-	vertical-align: text-top;
-	padding: 5px;
-}
-
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.repository.synchronizer/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.repository.synchronizer/pom.xml b/components/org.apache.stratos.adc.mgt.repository.synchronizer/pom.xml
new file mode 100644
index 0000000..ce21fae
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.repository.synchronizer/pom.xml
@@ -0,0 +1,85 @@
+<!--
+  ~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.adc.mgt.repository.synchronizer</artifactId>
+    <name>Apache Stratos - Repository Synchronizer</name>
+    <description>Repository Synchronizer</description>
+    <packaging>war</packaging>
+
+    <build>
+        <plugins>
+            <plugin>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>1.5</source>
+                    <target>1.5</target>
+                </configuration>
+                <version>2.3.2</version>
+            </plugin>
+            <plugin>
+                <artifactId>maven-war-plugin</artifactId>
+                <version>2.2</version>
+                <configuration>                     
+                    <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
+                    <warName>${project.artifactId}</warName>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-transports-http</artifactId>
+            <version>2.6.2</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
+            <version>2.6.2</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-httpclient</groupId>
+            <artifactId>commons-httpclient</artifactId>
+            <version>3.1</version>
+        </dependency>
+        <dependency>
+            <groupId>javax.ws.rs</groupId>
+            <artifactId>jsr311-api</artifactId>
+            <version>1.1.1</version>
+        </dependency>
+        <dependency>
+        <groupId>net.sf.json-lib</groupId>
+        <artifactId>json-lib</artifactId>
+        <version>2.4</version>
+        <classifier>jdk15</classifier>
+    </dependency>
+            
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/java/org/apache/stratos/adc/mgt/reposync/service/RepositorySynchronizer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/java/org/apache/stratos/adc/mgt/reposync/service/RepositorySynchronizer.java b/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/java/org/apache/stratos/adc/mgt/reposync/service/RepositorySynchronizer.java
new file mode 100644
index 0000000..937baab
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/java/org/apache/stratos/adc/mgt/reposync/service/RepositorySynchronizer.java
@@ -0,0 +1,37 @@
+/**
+ * 
+ */
+package org.apache.stratos.adc.mgt.reposync.service;
+
+import java.util.Map;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.FormParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.core.MediaType;
+
+import net.sf.json.JSONObject;
+
+/**
+ * @author wso2
+ * 
+ */
+@Path("/reposyncservice/")
+public class RepositorySynchronizer {
+
+	@POST
+	@Path("/notify/")
+	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
+	public void execute(@FormParam("payload") String payload) {
+		Map jsonObject = JSONObject.fromObject(payload);
+		System.out.println("Printing......");
+		Map repoMap = (Map) jsonObject.get("repository");
+		System.out.println("-------------");
+		System.out.println("Repo URL : " + repoMap.get("url"));
+		System.out.println("-------------");
+		System.out.println("-------------");
+		System.out.println("-------------");
+		System.out.println("---JSON customer : " + payload);
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/WEB-INF/cxf-servlet.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/WEB-INF/cxf-servlet.xml
new file mode 100644
index 0000000..9454028
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/WEB-INF/cxf-servlet.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  ~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:jaxrs="http://cxf.apache.org/jaxrs"
+       xsi:schemaLocation="
+         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
+         http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
+
+    <jaxrs:server id="repoSynchronizer" address="/notify">
+        <jaxrs:serviceBeans>
+            <ref bean="serviceBean"/>
+        </jaxrs:serviceBeans>
+    </jaxrs:server>
+
+    <bean id="serviceBean" class="org.apache.stratos.adc.mgt.reposync.service.RepositorySynchronizer"/>
+</beans>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/WEB-INF/web.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/WEB-INF/web.xml b/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000..696d5cc
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
+         http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
+
+    <display-name>JAX-WS/JAX-RS Webapp</display-name>
+
+    <servlet>
+        <servlet-name>JAXServlet</servlet-name>
+        <display-name>JAX-WS/JAX-RS Servlet</display-name>
+        <description>JAX-WS/JAX-RS Endpoint</description>
+        <servlet-class>
+            org.apache.cxf.transport.servlet.CXFServlet
+        </servlet-class>
+        <init-param>
+            <param-name>service-list-stylesheet</param-name>
+            <param-value>servicelist.css</param-value>
+        </init-param>
+        <load-on-startup>1</load-on-startup>
+    </servlet>
+
+    <servlet-mapping>
+        <servlet-name>JAXServlet</servlet-name>
+        <url-pattern>/services/*</url-pattern>
+    </servlet-mapping>
+
+    <session-config>
+        <session-timeout>60</session-timeout>
+    </session-config>
+
+</web-app>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/servicelist.css
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/servicelist.css b/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/servicelist.css
new file mode 100644
index 0000000..bbc4987
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.repository.synchronizer/src/main/webapp/servicelist.css
@@ -0,0 +1,117 @@
+@CHARSET "ISO-8859-1";
+
+/* http://meyerweb.com/eric/tools/css/reset/ 
+   v2.0 | 20110126
+   License: none (public domain)
+*/
+
+html, body, div, span, applet, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, big, cite, code,
+del, dfn, em, img, ins, kbd, q, s, samp,
+small, strike, strong, sub, sup, tt, var,
+b, u, i, center,
+dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend,
+table, caption, tbody, tfoot, thead, tr, th, td,
+article, aside, canvas, details, embed, 
+figure, figcaption, footer, header, hgroup, 
+menu, nav, output, ruby, section, summary,
+time, mark, audio, video {
+	margin: 0;
+	padding: 0;
+	border: 0;
+	font-size: 100%;
+	font: inherit;
+	vertical-align: baseline;
+}
+/* HTML5 display-role reset for older browsers */
+article, aside, details, figcaption, figure, 
+footer, header, hgroup, menu, nav, section {
+	display: block;
+}
+
+html {
+	background: #efefef;
+}
+
+body {
+	line-height: 1;
+	width:960px;
+	margin:auto;
+	background:white;
+	padding:10px;
+	box-shadow:0px 0px 5px #CCC;
+	font-family:"Lucida Grande","Lucida Sans","Microsoft Sans Serif", "Lucida Sans Unicode","Verdana","Sans-serif","trebuchet ms" !important;
+	
+}
+ol, ul {
+	list-style: none;
+}
+blockquote, q {
+	quotes: none;
+}
+blockquote:before, blockquote:after,
+q:before, q:after {
+	content: '';
+	content: none;
+}
+table {
+	border-collapse: collapse;
+	border-spacing: 0;
+	width:960px;
+	border:solid 1px #ccc;
+}
+
+table a {
+	font-size:12px;
+	color:#1e90ff;
+	padding:7px;
+float:left;	
+;
+}
+
+.heading {
+	font-size: 18px;
+	margin-top: 20px;
+	float:left;
+	color:#0067B1;
+	margin-bottom:20px;
+	padding-top:20px;
+}
+
+.field {
+	font-weight: normal;
+	width:120px;
+	font-size:12px;
+	float:left;
+	padding:7px;
+	clear:left;
+}
+.value {
+	font-weight: bold;
+	font-size:12px;
+	float:left;
+	padding:7px;
+	clear:right;
+}
+.porttypename {
+	font-weight: bold;
+	font-size:14px;
+}
+UL {
+	margin-top: 0;
+}
+LI {
+	font-weight: normal;
+	font-size:12px;
+	margin-top:10px;
+}
+
+TD {
+	border:1px solid #ccc;
+	vertical-align: text-top;
+	padding: 5px;
+}
+
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/pom.xml b/components/org.apache.stratos.adc.mgt/2.1.3/pom.xml
deleted file mode 100644
index ab2759a..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/pom.xml
+++ /dev/null
@@ -1,144 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
-       Licensed to the Apache Software Foundation (ASF) under one
-       or more contributor license agreements.  See the NOTICE file
-       distributed with this work for additional information
-       regarding copyright ownership.  The ASF licenses this file
-       to you under the Apache License, Version 2.0 (the
-       "License"); you may not use this file except in compliance
-       with the License.  You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing,
-       software distributed under the License is distributed on an
-       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-       KIND, either express or implied.  See the License for the
-       specific language governing permissions and limitations
-       under the License.
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-	<parent>
-		<groupId>org.apache.stratos</groupId>
-		<artifactId>stratos-components-parent</artifactId>
-		<version>3.0.0-SNAPSHOT</version>
-	        <relativePath>../../pom.xml</relativePath>
-	</parent>
-
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>org.apache.stratos.adc.mgt</artifactId>
-	<version>2.1.3</version>
-	<packaging>bundle</packaging>
-	<name>Apache Stratos - ADC BE</name>
-	<description>BE functionalities of ADC</description>
-	<url>http://apache.org</url>
-
-	<dependencies>
-		<dependency>
-			<groupId>org.wso2.carbon</groupId>
-			<artifactId>org.wso2.carbon.registry.ws.client</artifactId>
-		</dependency>
-		<!--<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> 
-			</dependency> -->
-		<dependency>
-			<groupId>org.apache.stratos</groupId>
-			<artifactId>org.apache.stratos.load.balance.cartridge.autoscaler.service.stub</artifactId>
-			<version>4.1.3</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.apache.stratos</groupId>
-			<artifactId>org.apache.stratos.adc.topology.mgt</artifactId>
-			<version>2.1.3</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.wso2.carbon</groupId>
-			<artifactId>org.wso2.carbon.utils</artifactId>
-			<version>${wso2carbon.version}</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.wso2.carbon</groupId>
-			<artifactId>org.wso2.carbon.cartridge.agent.stub</artifactId>
-			<version>4.1.1</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.apache.tomcat.wso2</groupId>
-			<artifactId>jdbc-pool</artifactId>
-			<version>${version.tomcat}.wso2v1</version>
-		</dependency>
-
-		<dependency>
-			<groupId>com.gitblit</groupId>
-			<artifactId>gitblit</artifactId>
-			<version>1.2.0.wso2v1</version>
-		</dependency>
-		<dependency>
-			<groupId>com.google.code.gson</groupId>
-			<artifactId>gson</artifactId>
-			<version>2.1</version>
-        </dependency>
-        <dependency>
-            <groupId>org.eclipse.jgit</groupId>
-            <artifactId>org.eclipse.jgit</artifactId>
-            <version>2.1.0.wso2v1</version>
-        </dependency>
-        <dependency>
-            <groupId>com.jcraft</groupId>
-            <artifactId>jsch</artifactId>
-            <version>0.1.49.wso2v1</version>
-        </dependency>
-		<dependency>
-			<groupId>junit</groupId>
-			<artifactId>junit</artifactId>
-			<scope>test</scope>
-		</dependency>
-	</dependencies>
-
-	<build>
-		<plugins>
-			<plugin>
-				<groupId>org.apache.felix</groupId>
-				<artifactId>maven-scr-plugin</artifactId>
-			</plugin>
-			<plugin>
-				<groupId>org.apache.felix</groupId>
-				<artifactId>maven-bundle-plugin</artifactId>
-
-				<extensions>true</extensions>
-				<configuration>
-					<instructions>
-						<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-						<Bundle-Name>${project.artifactId}</Bundle-Name>
-						<Bundle-Activator>
-							org.apache.stratos.adc.mgt.internal.HostingManagementActivator
-                                                </Bundle-Activator>
-						<Private-Package>org.apache.stratos.adc.mgt.internal.*</Private-Package>
-						<Export-Package>
-							org.apache.stratos.adc.mgt.utils*,
-							org.apache.stratos.adc.mgt.service.*,
-							org.apache.stratos.adc.mgt.*
-                        			</Export-Package>
-						<Import-Package>
-							org.apache.axis2.*; version="1.6.1.wso2v6",
-							org.apache.axiom.*;
-							version="1.2.11.wso2v2",
-							org.apache.neethi.*;
-							version="2.0.4.wso2v4",
-							javax.xml.stream.*; version="1.0.1",
-							javax.wsdl.*; version="1.6.2",
-							org.osgi.framework.*,
-							*;resolution:=optional
-                        			</Import-Package>
-						<DynamicImport-Package>*</DynamicImport-Package>
-					</instructions>
-				</configuration>
-			</plugin>
-		</plugins>
-	</build>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/conf/cartridge-config.properties
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/conf/cartridge-config.properties b/components/org.apache.stratos.adc.mgt/2.1.3/src/conf/cartridge-config.properties
deleted file mode 100644
index b495014..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/conf/cartridge-config.properties
+++ /dev/null
@@ -1,38 +0,0 @@
-# Configuration properties
-
-sc.ip=s2_ip
-autoscalerService.url=https://cc.wso2.com:9444/services/CloudControllerService/
-autoscaler.time.out=190000
-cartridge.agent.epr=https://s2_ip:9447/services/CartridgeAgentService
-git.host.name=s2_hostname
-git.host.ip=s2_ip
-git.repo.notification.url=https://sc.wso2.com:9445/services/RepoNotificationService/
-identity.server.url=https://sc.wso2.com:9447/services/RepoNotificationService/
-
-adc.jdbc.url=jdbc:h2:repository/database/WSO2S2_DB
-adc.jdbc.username=wso2carbon
-adc.jdbc.password=wso2carbon
-adc.jdbc.driver=org.h2.Driver
-
-mb.server.ip=cc.wso2.com:5673
-
-feature.externalrepo.validation.enabled=true
-feature.internalrepo.enabled=false
-feature.multitenant.multiplesubscription.enabled=false
-
-internal.repo.username=admin
-internal.repo.password=admin
-
-append.script=SCRIPT_PATH/add_entry_zone_file.sh
-remove.script=SCRIPT_PATH/remove_entry_zone_file.sh
-bind.file.path=/etc/bind/db.STRATOS_DOMAIN
-elb.ip=s2_ip
-
-bam.ip=s2_ip
-bam.port=7714
-
-max.attempts=1000
-
-cartridge.key=KEYPATH
-
-repository.info.epr=https://s2_ip:9445/services/RepositoryInformationService

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/conf/tenant-resource-policy.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/conf/tenant-resource-policy.xml b/components/org.apache.stratos.adc.mgt/2.1.3/src/conf/tenant-resource-policy.xml
deleted file mode 100644
index 12bbf74..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/conf/tenant-resource-policy.xml
+++ /dev/null
@@ -1 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/CartridgeAgentClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/CartridgeAgentClient.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/CartridgeAgentClient.java
deleted file mode 100644
index 3731107..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/CartridgeAgentClient.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.client;
-
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.internal.DataHolder;
-import org.wso2.carbon.cartridge.agent.stub.CartridgeAgentServiceStub;
-
-public class CartridgeAgentClient {
-
-	private static final Log log = LogFactory.getLog(CartridgeAgentClient.class);
-	CartridgeAgentServiceStub stub = null;
-	public CartridgeAgentClient(String epr) throws AxisFault {
-	  ConfigurationContext clientConfigContext = DataHolder.getClientConfigContext();
-	  stub = new CartridgeAgentServiceStub(clientConfigContext, epr);
-    }
-	
-	public void unregister(String domain, String subDomain, String hostName) throws Exception {
-		log.info(" ** Unregistering -- ");
-		stub.unregister(domain, subDomain, hostName);
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java
deleted file mode 100644
index 6dbba78..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.client;
-
-import java.rmi.RemoteException;
-
-import javax.activation.DataHandler;
-
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.exception.UnregisteredCartridgeException;
-import org.apache.stratos.adc.mgt.internal.DataHolder;
-import org.apache.stratos.cloud.controller.stub.CloudControllerServiceStub;
-import org.apache.stratos.cloud.controller.stub.CloudControllerServiceUnregisteredCartridgeExceptionException;
-import org.apache.stratos.cloud.controller.util.xsd.CartridgeInfo;
-import org.apache.stratos.cloud.controller.util.xsd.Properties;
-
-public class CloudControllerServiceClient {
-
-	private CloudControllerServiceStub stub;
-
-	private static final Log log = LogFactory.getLog(CloudControllerServiceClient.class);
-
-	public CloudControllerServiceClient(String epr) throws AxisFault {
-
-		ConfigurationContext clientConfigContext = DataHolder.getClientConfigContext();
-		try {
-			stub = new CloudControllerServiceStub(clientConfigContext, epr);
-			stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);
-
-		} catch (AxisFault axisFault) {
-			String msg = "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
-			log.error(msg, axisFault);
-			throw new AxisFault(msg, axisFault);
-		}
-
-	}
-
-	public boolean register(String domainName, String subDomain, String cartridgeType,
-	                        DataHandler payload, String tenantRange, String hostName, Properties properties) throws RemoteException, CloudControllerServiceUnregisteredCartridgeExceptionException
-	                                                                                  {		
-		return stub.registerService(domainName, subDomain, tenantRange, cartridgeType, hostName,
-		                            properties, payload);
-
-	}
-
-	public String startInstance(String domain, String subDomain) throws Exception {
-		return stub.startInstance(domain, subDomain);
-	}
-
-	public boolean terminateAllInstances(String domain, String subDomain) throws Exception {
-		return stub.terminateAllInstances(domain, subDomain);
-	}
-
-	public String[] getRegisteredCartridges() throws Exception {
-		return stub.getRegisteredCartridges();
-	}
-
-	public boolean createKeyPair(String cartridge, String keyPairName, String publicKey)
-	                                                                                    throws Exception {
-		return stub.createKeyPairFromPublicKey(cartridge, keyPairName, publicKey);
-	}
-
-	public CartridgeInfo getCartridgeInfo(String cartridgeType) throws UnregisteredCartridgeException, Exception {
-		try {
-			return stub.getCartridgeInfo(cartridgeType);
-		} catch (RemoteException e) {
-			throw e;
-		} catch (CloudControllerServiceUnregisteredCartridgeExceptionException e) {
-			throw new UnregisteredCartridgeException("Not a registered cartridge " + cartridgeType, cartridgeType, e);
-		}
-	}
-	
-	public boolean unregisterService(String domain, String subDomain) throws Exception {
-	    return stub.unregisterService(domain, subDomain);
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/RegistryClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/RegistryClient.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/RegistryClient.java
deleted file mode 100644
index c1d6cd3..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/client/RegistryClient.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.client;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-import java.util.UUID;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.context.ConfigurationContextFactory;
-import org.apache.commons.io.IOUtils;
-import org.wso2.carbon.registry.core.Association;
-import org.wso2.carbon.registry.core.Collection;
-import org.wso2.carbon.registry.core.Registry;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
-
-public class RegistryClient {
-
-	// url where the repository is running its services interface
-	private static String backendURL = "http://localhost:9763/services/";
-	private static ConfigurationContext configContext = null;
-
-	// configuration locations used to bootstrap axis2
-	private static String axis2Repo =
-	                                  "/home/wso2/Desktop/HP-demo-packs-with-video/cartridge/wso2stratos-cartridge-1.0.0-SNAPSHOT/repository/conf/axis2";
-	private static String axis2Conf =
-	                                  "/home/wso2/Desktop/HP-demo-packs-with-video/cartridge/wso2stratos-cartridge-1.0.0-SNAPSHOT/repository/conf/axis2/axis2_client.xml";
-	private static String serverURL = "https://localhost:9443/services/";
-
-	public RegistryClient() {
-		// TODO Auto-generated constructor stub
-	}
-
-	private static WSRegistryServiceClient initialize() throws Exception {
-		// set these properties, this is used for authentication over https to
-		// the registry
-		// if you have a newer version, you can update the keystore by copying
-		// it from
-		// the security directory of the repository
-		System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
-		System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
-		System.setProperty("javax.net.ssl.trustStoreType", "JKS");
-
-		configContext =
-		                ConfigurationContextFactory.createConfigurationContextFromFileSystem(axis2Repo,
-		                                                                                     axis2Conf);
-		return new WSRegistryServiceClient(serverURL, "admin", "admin", backendURL, configContext);
-	}
-
-	public static void addKey(String keyName, String content) throws Exception {
-		Registry registry = initialize();
-
-		// get the governance folder
-		Resource governanceFolder = registry.get("/_system/governance");
-		System.out.println("Folder description: " + governanceFolder.getDescription());
-		Resource r1 = registry.newResource();
-		String path = "/_system/governance/" + keyName;
-		r1.setContent(content);
-		registry.put(path, r1);
-
-		/*
-		 * List<Resource> paths = getServicePath(registry,
-		 * "/_system/governance/trunk/services");
-		 * 
-		 * for (Resource service : paths) { // we've got all the services here
-		 * 
-		 * Properties props = service.getProperties(); for (Object prop :
-		 * props.keySet()) { System.out.println(prop + " - " + props.get(prop));
-		 * }
-		 * 
-		 * Association[] associations =
-		 * registry.getAssociations(service.getPath(), "Documentation"); for
-		 * (Association association : associations) {
-		 * System.out.println(association.getAssociationType()); } }
-		 */
-	}
-
-	private static List<Resource> getServicePath(Registry registry, String servicesResource)
-	                                                                                        throws RegistryException {
-		List<Resource> result = new ArrayList<Resource>();
-		Resource resource = registry.get(servicesResource);
-
-		if (resource instanceof Collection) {
-			Object content = resource.getContent();
-			for (Object path : (Object[]) content) {
-				result.addAll(getServicePath(registry, (String) path));
-			}
-		} else if (resource instanceof Resource) {
-			result.add(resource);
-		}
-		return result;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/custom/domain/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/custom/domain/RegistryManager.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/custom/domain/RegistryManager.java
deleted file mode 100644
index d53fcc0..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/custom/domain/RegistryManager.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.custom.domain;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.exception.ADCException;
-import org.apache.stratos.adc.mgt.exception.DomainMappingExistsException;
-import org.apache.stratos.adc.mgt.internal.DataHolder;
-import org.apache.stratos.adc.mgt.utils.CartridgeConstants;
-import org.wso2.carbon.registry.core.Collection;
-import org.wso2.carbon.registry.core.Registry;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-
-public class RegistryManager {
-	private static Log log = LogFactory.getLog(RegistryManager.class);
-	private static Registry registry = DataHolder.getRegistry();
-
-	public RegistryManager() {
-		try {
-			if (!registry.resourceExists(CartridgeConstants.DomainMappingInfo.HOSTINFO)) {
-				registry.put(CartridgeConstants.DomainMappingInfo.HOSTINFO,
-				                    registry.newCollection());
-			}
-		} catch (RegistryException e) {
-			String msg =
-			             "Error while accessing registry or initializing domain mapping registry path\n";
-			log.error(msg + e.getMessage());
-		}
-	}
-
-	/**
-    *
-    */
-    public void addDomainMappingToRegistry(String hostName, String actualHost)
-            throws ADCException, RegistryException, DomainMappingExistsException {
-        try {
-            registry.beginTransaction();
-            Resource hostResource = registry.newResource();
-            hostResource.addProperty(CartridgeConstants.DomainMappingInfo.ACTUAL_HOST, actualHost);
-            if (!registry.resourceExists(CartridgeConstants.DomainMappingInfo.HOSTINFO +
-                                                hostName)) {
-                registry.put(CartridgeConstants.DomainMappingInfo.HOSTINFO + hostName,
-                                    hostResource);
-            } else {
-                registry.rollbackTransaction();
-                String msg = "Requested domain is already taken!";
-                log.error(msg);
-                throw new DomainMappingExistsException(msg, hostName);
-            }
-            registry.commitTransaction();
-        } catch (RegistryException e) {
-            registry.rollbackTransaction();
-            throw e; 
-        }
-    }
-
-
-    /**
-        *
-        */
-   	public void removeDomainMappingFromRegistry(String actualHost) throws Exception {
-   		try {
-               registry.beginTransaction();
-                String hostResourcePath = CartridgeConstants.DomainMappingInfo.HOSTINFO;
-                if (registry.resourceExists(hostResourcePath)) {
-                    Resource hostResource = registry.get(hostResourcePath);
-                    Collection hostInfoCollection;
-                    if(hostResource instanceof Collection){
-                        hostInfoCollection = (Collection) hostResource;
-                    } else {
-                        throw new Exception("Resource is not a collection " + hostResourcePath );
-                    }
-                    String[] paths = hostInfoCollection.getChildren();
-                    for (String path: paths){
-                        Resource domainMapping = registry.get(path);
-                        String actualHostInRegistry = domainMapping.getProperty(CartridgeConstants.DomainMappingInfo.ACTUAL_HOST);
-                        if(actualHostInRegistry != null && actualHost.equalsIgnoreCase(actualHostInRegistry)){
-                            registry.delete(path);
-                        }
-                    }
-                }
-                registry.commitTransaction();
-   		} catch (RegistryException e) {
-   			registry.rollbackTransaction();
-   			log.error("Unable to remove the mapping", e);
-   			throw e;
-   		}
-   	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/CartridgeSubscription.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/CartridgeSubscription.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/CartridgeSubscription.java
deleted file mode 100644
index 9d48b0f..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/CartridgeSubscription.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.dao;
-
-import java.util.List;
-
-public class CartridgeSubscription {
-
-	private int subscriptionId;
-	private int tenantId;
-	private String cartridge;
-	private String provider;
-	private String hostName;
-	private String policy;
-	private List<PortMapping> portMappings;
-	private String clusterDomain;
-	private String clusterSubdomain;
-	private Repository repository;
-	private String state;
-	private String alias;
-	private String tenantDomain;
-	private DataCartridge dataCartridge;
-	private String baseDirectory;
-	private String mappedDomain;
-	private String mgtClusterDomain;
-	private String mgtClusterSubDomain;
-
-	public int getSubscriptionId() {
-		return subscriptionId;
-	}
-
-	public void setSubscriptionId(int subscriptionId) {
-		this.subscriptionId = subscriptionId;
-	}
-
-	public int getTenantId() {
-		return tenantId;
-	}
-
-	public void setTenantId(int tenantId) {
-		this.tenantId = tenantId;
-	}
-
-	public String getCartridge() {
-		return cartridge;
-	}
-
-	public void setCartridge(String cartridge) {
-		this.cartridge = cartridge;
-	}
-
-	public String getProvider() {
-		return provider;
-	}
-
-	public void setProvider(String provider) {
-		this.provider = provider;
-	}
-
-	public String getHostName() {
-		return hostName;
-	}
-
-	public void setHostName(String hostName) {
-		this.hostName = hostName;
-	}
-
-	public String getPolicy() {
-		return policy;
-	}
-
-	public void setPolicy(String policy) {
-		this.policy = policy;
-	}
-
-	public List<PortMapping> getPortMappings() {
-		return portMappings;
-	}
-
-	public void setPortMappings(List<PortMapping> portMappings) {
-		this.portMappings = portMappings;
-	}
-
-	public String getClusterDomain() {
-		return clusterDomain;
-	}
-
-	public void setClusterDomain(String clusterDomain) {
-		this.clusterDomain = clusterDomain;
-	}
-
-	public String getClusterSubdomain() {
-		return clusterSubdomain;
-	}
-
-	public void setClusterSubdomain(String clusterSubdomain) {
-		this.clusterSubdomain = clusterSubdomain;
-	}
-
-	public Repository getRepository() {
-		return repository;
-	}
-
-	public void setRepository(Repository repository) {
-		this.repository = repository;
-	}
-
-	public String getState() {
-		return state;
-	}
-
-	public void setState(String state) {
-		this.state = state;
-	}
-
-	public String getAlias() {
-		return alias;
-	}
-
-	public void setAlias(String alias) {
-		this.alias = alias;
-	}
-
-	public String getTenantDomain() {
-		return tenantDomain;
-	}
-
-	public void setTenantDomain(String tenantDomain) {
-		this.tenantDomain = tenantDomain;
-	}
-
-	public DataCartridge getDataCartridge() {
-		return dataCartridge;
-	}
-
-	public void setDataCartridge(DataCartridge dataCartridge) {
-		this.dataCartridge = dataCartridge;
-	}
-
-	public String getBaseDirectory() {
-		return baseDirectory;
-	}
-
-	public void setBaseDirectory(String baseDirectory) {
-		this.baseDirectory = baseDirectory;
-	}
-
-	public String getMappedDomain() {
-		return mappedDomain;
-	}
-
-	public void setMappedDomain(String mappedDomain) {
-		this.mappedDomain = mappedDomain;
-	}
-
-	public String getMgtClusterDomain() {
-		return mgtClusterDomain;
-	}
-
-	public void setMgtClusterDomain(String mgtClusterDomain) {
-		this.mgtClusterDomain = mgtClusterDomain;
-	}
-
-	public String getMgtClusterSubDomain() {
-		return mgtClusterSubDomain;
-	}
-
-	public void setMgtClusterSubDomain(String mgtClusterSubDomain) {
-		this.mgtClusterSubDomain = mgtClusterSubDomain;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/DataCartridge.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/DataCartridge.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/DataCartridge.java
deleted file mode 100644
index 8e43079..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/DataCartridge.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.dao;
-
-public class DataCartridge {
-
-	private int id;
-	private String dataCartridgeType;
-	private String userName;
-	private String password;
-	public int getId() {
-    	return id;
-    }
-	public void setId(int id) {
-    	this.id = id;
-    }
-	public String getDataCartridgeType() {
-    	return dataCartridgeType;
-    }
-	public void setDataCartridgeType(String dataCartridgeType) {
-    	this.dataCartridgeType = dataCartridgeType;
-    }
-	public String getUserName() {
-    	return userName;
-    }
-	public void setUserName(String userName) {
-    	this.userName = userName;
-    }
-	public String getPassword() {
-    	return password;
-    }
-	public void setPassword(String password) {
-    	this.password = password;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/PortMapping.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/PortMapping.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/PortMapping.java
deleted file mode 100644
index 5916847..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/PortMapping.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.dao;
-
-public class PortMapping {
-	private int id;
-	private String type;
-	private String primaryPort;
-	private String proxyPort;
-
-	public int getId() {
-		return id;
-	}
-
-	public void setId(int id) {
-		this.id = id;
-	}
-
-	public String getType() {
-		return type;
-	}
-
-	public void setType(String type) {
-		this.type = type;
-	}
-
-	public String getPrimaryPort() {
-		return primaryPort;
-	}
-
-	public void setPrimaryPort(String primaryPort) {
-		this.primaryPort = primaryPort;
-	}
-
-	public String getProxyPort() {
-		return proxyPort;
-	}
-
-	public void setProxyPort(String proxyPort) {
-		this.proxyPort = proxyPort;
-	}
-}


[42/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java
deleted file mode 100644
index fc1569b..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.util;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.stratos.lb.common.conf.util.Constants;
-
-/**
- * We keep details under a service element of jcoluds configuration file,
- * in this object.
- */
-public class ServiceTemplate implements Cloneable {
-
-    private String domainName;
-    private String subDomainName = Constants.DEFAULT_SUB_DOMAIN;
-    private Map<String, String> properties = new HashMap<String, String>();
-    
-    public String getDomainName() {
-        return domainName;
-    }
-    
-    public boolean setDomainName(String domainName) {
-        if (!"".equals(domainName)) {
-            this.domainName = domainName;
-            return true;
-        }
-        
-        return false;
-    }
-    
-    public void setProperty(String key, String value) {
-        properties.put(key, value);
-    }
-    
-    public String getProperty(String key) {
-        
-        if(properties.containsKey(key)){
-            return properties.get(key);
-        }
-        
-        return "";
-    }
-
-    public Map<String, String> getProperties() {
-        return properties;
-    }
-
-    public void setProperties(Map<String, String> properties) {
-        this.properties = properties;
-    }
-    
-    public String getSubDomainName() {
-        return subDomainName;
-    }
-
-    public void setSubDomainName(String subDomainName) {
-        if(subDomainName == null || "".equals(subDomainName)){
-            return;
-        }
-        this.subDomainName = subDomainName;
-    }
-    
-    public Object clone() throws CloneNotSupportedException {
-        return super.clone();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java
deleted file mode 100644
index a40cf41..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java
+++ /dev/null
@@ -1,557 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.xml;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.apache.stratos.autoscaler.service.exception.MalformedConfigurationFileException;
-import org.apache.stratos.autoscaler.service.util.AutoscalerConstant;
-import org.apache.stratos.autoscaler.service.util.IaasProvider;
-import org.apache.stratos.autoscaler.service.util.ServiceTemplate;
-import org.wso2.carbon.utils.CarbonUtils;
-import org.wso2.securevault.SecretResolver;
-import org.wso2.securevault.SecretResolverFactory;
-
-/**
- * Responsible for reading the Elastic scaler configuration file.
- * Following is a sample XML.
- *
- * &lt;elasticScalerConfig&gt;
- *      &lt;iaasProviders&gt;
- *          &lt;iaasProvider name="ec2"&gt;
- *              &lt;provider&gt;aws-ec2&lt;/provider&gt;
- *              &lt;identity&gt;aaa&lt;/identity&gt;
- *              &lt;credential&gt;aaaa&lt;/credential&gt;
- *              &lt;scaleUpOrder&gt;1&lt;/scaleUpOrder&gt;
- *              &lt;scaleDownOrder&gt;2&lt;/scaleDownOrder&gt;
- *              &lt;property name="A" value="a"/&gt;
- *              &lt;property name="B" value="b"/&gt;
- *              &lt;template&gt;temp1&lt;/template&gt;
- *          &lt;/iaasProvider&gt;
- *          
- *          &lt;iaasProvider name="lxc"&gt;
- *              &lt;provider&gt;aws-ec2&lt;/provider&gt;
- *              &lt;identity&gt;aaa&lt;/identity&gt;
- *              &lt;credential&gt;aaaa&lt;/credential&gt;
- *              &lt;scaleUpOrder&gt;2&lt;/scaleUpOrder&gt;
- *              &lt;scaleDownOrder&gt;1&lt;/scaleDownOrder&gt;
- *              &lt;property name="X" value="x"/&gt;
- *              &lt;property name="Y" value="y"/&gt;
- *              &lt;template&gt;temp2&lt;/template&gt;
- *          &lt;/iaasProvider&gt;
- *      &lt;/iaasProviders&gt;
- *      $lt;services&gt;
- *          $lt;default&gt;
- *              $lt;property name="availabilityZone" value="us-east-1c"/&gt;
- *              $lt;property name="securityGroups" value="manager,cep,mb,default"/&gt;
- *              $lt;property name="instanceType" value="m1.large"/&gt;
- *              $lt;property name="keyPair" value="aa"/&gt;
- *          $lt;/default&gt;
- *          $lt;service domain="wso2.as.domain"&gt;
- *              $lt;property name="securityGroups" value="manager,default"/&gt;
- *              $lt;property name="payload" value="resources/as.zip"/&gt;
- *          $lt;/service&gt;
- *      $lt;/services&gt;
- *  &lt;/elasticScalerConfig&gt;
- */
-public class ElasticScalerConfigFileReader {
-	
-	private static final Log log = LogFactory.getLog(ElasticScalerConfigFileReader.class);
-
-	//get the factory
-	private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-	private Document dom;
-	private Element docEle;
-
-	/**
-	 * Path to elastic-scaler-config XML file, which specifies the Iaas specific details and 
-	 * services related details.
-	 */
-	private String elasticScalerConfigFile;
-	
-	
-	public ElasticScalerConfigFileReader(){
-	    
-	    elasticScalerConfigFile = CarbonUtils.getCarbonConfigDirPath() +
-	            File.separator + "elastic-scaler-config.xml";
-	    
-		/**
-		 * Parse the configuration file.
-		 */
-		try {
-			//Using factory, get an instance of document builder
-			DocumentBuilder db = dbf.newDocumentBuilder();
-
-			//parse using builder to get DOM representation of the XML file
-			dom = db.parse(elasticScalerConfigFile);
-			
-
-		}catch(Exception ex) {
-			String msg = "Error occurred while parsing the "+elasticScalerConfigFile+".";
-			handleException(msg, ex);
-		}
-	}
-	
-	/**
-	 * Constructor to be used in the test cases.
-	 * @param file path to elastic-scaler-config xml file.
-	 */
-	public ElasticScalerConfigFileReader(String file) {
-        
-        /**
-         * Parse the configuration file.
-         */
-        try {
-            //Using factory, get an instance of document builder
-            DocumentBuilder db = dbf.newDocumentBuilder();
-            
-            //parse using builder to get DOM representation of the XML file
-            dom = db.parse(file);
-            
-
-        }catch(Exception ex) {
-            String msg = "Error occurred when parsing the "+file+".";
-            handleException(msg, ex);
-        }
-    }
-	
-	/**
-	 * Returns the serialization directory specified in the configuration file.
-	 * @return the path to the directory or an empty string if element cannot be found.
-	 */
-	public String getSerializationDir() {
-        
-	    docEle = dom.getDocumentElement();
-	    NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.SERIALIZATION_DIR_ELEMENT);
-
-        // there should be only one serializationDir element, we neglect all the others
-        if (nl != null && nl.getLength() > 0) {
-            
-            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
-                Element prop = (Element) nl.item(0);
-
-                return prop.getTextContent();
-
-            }
-        }
-        
-        return "";
-    }
-	
-	/**
-	 * Load all IaasProviders from the configuration file and returns a list.
-	 * @return a list of IaasProvider instances.
-	 */
-	public List<IaasProvider> getIaasProvidersList() {
-	    List<IaasProvider> iaasProviders = new ArrayList<IaasProvider>();
-	    
-	    docEle = dom.getDocumentElement();
-	    NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.IAAS_PROVIDER_ELEMENT);
-	    
-	    if (nl != null && nl.getLength() > 0) {
-	        
-	        for(int i=0; i< nl.getLength() ; i++){
-	            iaasProviders.add(getIaasProvider(nl.item(i)));
-	        }
-	        
-	    }
-	    else{
-	        String msg = "Essential '"+AutoscalerConstant.IAAS_PROVIDER_ELEMENT+"' element cannot" +
-	        		" be found in "+elasticScalerConfigFile;
-	        handleException(msg);
-	    }
-	    
-	    return iaasProviders;
-	    
-    }
-
-    private IaasProvider getIaasProvider(Node item) {
-
-        IaasProvider iaas = new IaasProvider();
-        
-        if (item.getNodeType() == Node.ELEMENT_NODE) {
-            Element iaasElt = (Element) item;
-            iaas.setType(iaasElt.getAttribute(AutoscalerConstant.IAAS_PROVIDER_TYPE_ATTR));
-            
-            if("".equals(iaas.getType())){
-                String msg = "'"+AutoscalerConstant.IAAS_PROVIDER_ELEMENT+"' element's '"+
-            AutoscalerConstant.IAAS_PROVIDER_TYPE_ATTR+"' attribute should be specified!";
-                
-                handleException(msg);
-
-            }
-            
-            // this is not mandatory
-            iaas.setName(iaasElt.getAttribute(AutoscalerConstant.IAAS_PROVIDER_NAME_ATTR));
-            
-            iaas.setProperties(loadProperties(iaasElt));
-            loadTemplate(iaas, iaasElt);
-            loadScalingOrders(iaas, iaasElt);
-            loadProvider(iaas, iaasElt);
-            loadIdentity(iaas, iaasElt);
-            loadCredentials(iaas, iaasElt);
-        }
-        
-        
-        return iaas;
-    }
-    
-    /**
-     * Load all ServiceTemplates from the configuration file and returns a list.
-     * @return a list of ServiceTemplate instances.
-     */
-    public List<ServiceTemplate> getTemplates() {
-        
-        List<ServiceTemplate> templates = new ArrayList<ServiceTemplate>();
-        
-        // build default template object
-        ServiceTemplate template = new ServiceTemplate();
-        
-        Element docEle = dom.getDocumentElement();
-        NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.DEFAULT_SERVICE_ELEMENT);
-        
-        if (nl != null && nl.getLength() > 0) {
-
-            Node item = nl.item(0);
-
-            if (item.getNodeType() == Node.ELEMENT_NODE) {
-                Element defaultElt = (Element) item;
-                template.setProperties(loadProperties(defaultElt));
-            }
-
-        }
-        
-        // append / overwrite the default template object with values in each domain
-        nl = docEle.getElementsByTagName(AutoscalerConstant.SERVICE_ELEMENT);
-        
-        if (nl != null && nl.getLength() > 0) {
-
-            for (int i = 0; i < nl.getLength(); i++) {
-                Node item = nl.item(i);
-
-                // clone the default template to an independent object
-                try {
-                    ServiceTemplate temp = (ServiceTemplate) template.clone();
-
-                    if (item.getNodeType() == Node.ELEMENT_NODE) {
-                        Element imageElt = (Element) item;
-
-                        if ("".equals(imageElt.getAttribute(
-                                             AutoscalerConstant.SERVICE_DOMAIN_ATTR))) {
-                            String msg =
-                                "Essential '"+AutoscalerConstant.SERVICE_DOMAIN_ATTR+"' " +
-                                		"attribute of '"+AutoscalerConstant.SERVICE_ELEMENT+
-                                		"' element cannot be found in " + elasticScalerConfigFile;
-
-                            handleException(msg);
-                        }
-
-                        // set domain name
-                        temp.setDomainName(imageElt.getAttribute(AutoscalerConstant.SERVICE_DOMAIN_ATTR));
-                        
-                        // set sub domain
-                        temp.setSubDomainName(imageElt.getAttribute(
-                                              AutoscalerConstant.SERVICE_SUB_DOMAIN_ATTR));
-                        
-                        // load custom properties
-                        Map<String, String> customProperties = loadProperties(imageElt);
-                        
-                        // add custom properties (overwrite default properties where necessary)
-                        for (Entry<String, String> pair : customProperties.entrySet()) {
-                            temp.setProperty(pair.getKey(), pair.getValue());
-                        }
-
-                    }
-                    
-                    // add each domain specific template to list
-                    templates.add(temp);
-
-                } catch (CloneNotSupportedException e) {
-                    String msg = "This is extraordinary!! ";
-                    handleException(msg, e);
-                }
-            }
-        }
-        
-        return templates;
-    }
-    
-    private void loadCredentials(IaasProvider iaas, Element iaasElt) {
-
-        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.CREDENTIAL_ELEMENT);
-
-        // there should be only one credential element, we neglect all the others
-        if (nl != null && nl.getLength() > 0) {
-            
-            if (nl.getLength() > 1){
-                log.warn(elasticScalerConfigFile +" contains more than one "+
-                         AutoscalerConstant.CREDENTIAL_ELEMENT+" elements!" +
-                        " Elements other than the first will be neglected.");
-            }
-            
-            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
-
-                // retrieve the value using secure vault
-                SecretResolver secretResolver = SecretResolverFactory.create(docEle, false);
-                String alias;
-
-                // FIXME following is a hack to find the correct alias.
-                if (iaas.getProvider().contains("ec2")) {
-                    alias = AutoscalerConstant.EC2_CREDENTIAL_ALIAS;
-                } else {
-                    alias = AutoscalerConstant.OPENSTACK_CREDENTIAL_ALIAS;
-                }
-
-                // retrieve the secured password
-                if (secretResolver != null && secretResolver.isInitialized() && 
-                        secretResolver.isTokenProtected(alias)) {
-
-                    iaas.setCredential(secretResolver.resolve(alias));
-
-                }
-
-            }
-        }
-        else{
-            String msg = "Essential '"+AutoscalerConstant.CREDENTIAL_ELEMENT+"' element" +
-            		" has not specified in "+elasticScalerConfigFile;
-            handleException(msg);
-        }
-    }
-
-    private void loadIdentity(IaasProvider iaas, Element iaasElt) {
-
-        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.IDENTITY_ELEMENT);
-
-        // there should be only one identity element, we neglect all the others
-        if (nl != null && nl.getLength() > 0) {
-            
-            if (nl.getLength() > 1){
-                log.warn(elasticScalerConfigFile +" contains more than one "+
-                        AutoscalerConstant.IDENTITY_ELEMENT+" elements!" +
-                        " Elements other than the first will be neglected.");
-            }
-            
-            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
-
-                // retrieve the value using secure vault
-                SecretResolver secretResolver = SecretResolverFactory.create(docEle, false);
-                String alias;
-                
-                //FIXME following is a hack to find the correct alias.
-                if(iaas.getProvider().contains("ec2")){
-                    alias = AutoscalerConstant.EC2_IDENTITY_ALIAS;
-                }
-                else{
-                    alias = AutoscalerConstant.OPENSTACK_IDENTITY_ALIAS;
-                }
-
-                // retrieve the secured password
-                if (secretResolver != null && secretResolver.isInitialized() && 
-                        secretResolver.isTokenProtected(alias)) {
-
-                    iaas.setIdentity(secretResolver.resolve(alias));
-
-                }
-
-            }
-        }
-        else{
-            String msg = "Essential '"+AutoscalerConstant.IDENTITY_ELEMENT+"' element" +
-            		" has not specified in "+elasticScalerConfigFile;
-            handleException(msg);
-        }
-    }
-
-    private void loadProvider(IaasProvider iaas, Element iaasElt) {
-
-        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.PROVIDER_ELEMENT);
-
-        // there should be only one provider element, we neglect all the others
-        if (nl != null && nl.getLength() > 0) {
-            
-            if (nl.getLength() > 1){
-                log.warn(elasticScalerConfigFile +" contains more than one "+
-                        AutoscalerConstant.PROVIDER_ELEMENT+" elements!" +
-                        " Elements other than the first will be neglected.");
-            }
-            
-            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
-                Element prop = (Element) nl.item(0);
-
-                iaas.setProvider(prop.getTextContent());
-
-            }
-        }
-        else{
-            String msg = "Essential '"+AutoscalerConstant.PROVIDER_ELEMENT+"' element " +
-            		"has not specified in "+elasticScalerConfigFile;
-            handleException(msg);
-        }
-    }
-
-    private void loadScalingOrders(IaasProvider iaas, Element iaasElt) {
-
-        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.SCALE_UP_ORDER_ELEMENT);
-
-        // there should be only one scaleUpOrder element, we neglect all the others
-        if (nl != null && nl.getLength() > 0) {
-            
-            if (nl.getLength() > 1){
-                log.warn(elasticScalerConfigFile +" contains more than one "+
-                        AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+" elements!" +
-                        " Elements other than the first will be neglected.");
-            }
-            
-            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
-                Element prop = (Element) nl.item(0);
-
-                try {
-                    iaas.setScaleUpOrder(Integer.parseInt(prop.getTextContent()));
-                }catch (NumberFormatException e) {
-                    String msg = AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+" element contained" +
-                    		" in "+elasticScalerConfigFile +"" +
-                    		" has a value which is not an Integer value.";
-                    handleException(msg, e);
-                }
-
-            }
-        }
-        else{
-            String msg = "Essential '"+AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+"' element" +
-            		" has not specified in "+elasticScalerConfigFile;
-            handleException(msg);
-        }
-        
-        
-        nl = iaasElt.getElementsByTagName(AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT);
-
-        // there should be only one scaleDownOrder element, we neglect all the others
-        if (nl != null && nl.getLength() > 0) {
-            
-            if (nl.getLength() > 1){
-                log.warn(elasticScalerConfigFile +" contains more than one "+
-                        AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+" elements!" +
-                        " Elements other than the first will be neglected.");
-            }
-            
-            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
-                Element prop = (Element) nl.item(0);
-
-                try {
-                    iaas.setScaleDownOrder(Integer.parseInt(prop.getTextContent()));
-                }catch (NumberFormatException e) {
-                    String msg = AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+" element contained" +
-                            " in "+elasticScalerConfigFile +"" +
-                            " has a value which is not an Integer value.";
-                    handleException(msg, e);
-                }
-
-            }
-        }
-        else{
-            String msg = "Essential '"+AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+"' element" +
-                    " has not specified in "+elasticScalerConfigFile;
-            handleException(msg);
-        }
-    }
-
-    private void loadTemplate(IaasProvider iaas, Element iaasElt) {
-
-        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.IMAGE_ID_ELEMENT);
-
-        // there should be only one imageId element, we neglect all the others
-        if (nl != null && nl.getLength() > 0) {
-            
-            if (nl.getLength() > 1){
-                log.warn(elasticScalerConfigFile +" contains more than one "+
-                        AutoscalerConstant.IMAGE_ID_ELEMENT+" elements!" +
-                        " Elements other than the first will be neglected.");
-            }
-            
-            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
-                Element prop = (Element) nl.item(0);
-
-                iaas.setTemplate(prop.getTextContent());
-
-            }
-        }
-        else{
-            String msg = "Essential '"+AutoscalerConstant.IMAGE_ID_ELEMENT+"' element" +
-                    " has not specified in "+elasticScalerConfigFile;
-            handleException(msg);
-        }
-    }
-
-    private Map<String, String> loadProperties(Element iaasElt) {
-
-        Map<String, String> propertyMap = new HashMap<String, String>();
-        
-        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.PROPERTY_ELEMENT);
-        
-        if (nl != null && nl.getLength() > 0) {
-            for(int i=0; i< nl.getLength() ; i++){
-                
-                if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
-                    Element prop = (Element) nl.item(i);
-                    
-                    if("".equals(prop.getAttribute(AutoscalerConstant.PROPERTY_NAME_ATTR)) ||
-                            "".equals(prop.getAttribute(AutoscalerConstant.PROPERTY_VALUE_ATTR))){
-                        
-                        String msg ="Property element's, name and value attributes should be specified " +
-                        		"in "+elasticScalerConfigFile;
-
-                        handleException(msg);
-                    }
-                    propertyMap.put(prop.getAttribute(AutoscalerConstant.PROPERTY_NAME_ATTR), 
-                                    prop.getAttribute(AutoscalerConstant.PROPERTY_VALUE_ATTR));
-                    
-                }
-            }
-        }
-        
-        return propertyMap;
-    }
-    
-    private void handleException(String msg){
-        log.error(msg);
-        throw new MalformedConfigurationFileException(msg);
-    }
-    
-    private void handleException(String msg, Exception e) {
-        log.error(msg, e);
-        throw new MalformedConfigurationFileException(msg, e);
-    }
-	
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
deleted file mode 100644
index 04dd8d8..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<serviceGroup>
-    <service name="AutoscalerService" scope="application">
-        <parameter name="ServiceClass">org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImplpl</parameter>
-        <messageReceivers>
-        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
-        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
-    </messageReceivers>
-    </service>
-</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java
deleted file mode 100644
index 9a742ee..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.util;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.IaasContextComparator;
-import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
-
-import junit.framework.TestCase;
-
-public class IaasContextComparatorTest extends TestCase {
-    
-    List<IaasContext> iaasContexts = new ArrayList<IaasContext>();
-    
-    @Override
-    protected void setUp() throws Exception {
-        IaasContext a = new IaasContext(Iaases.ec2, null);
-        a.setScaleUpOrder(1);
-        a.setScaleDownOrder(5);
-        
-        IaasContext b = new IaasContext(Iaases.openstack, null);
-        b.setScaleUpOrder(3);
-        b.setScaleDownOrder(0);
-        
-        iaasContexts.add(a);
-        iaasContexts.add(b);
-        
-        super.setUp();
-    }
-
-    public void testSort() {
-        
-        // scale up order sort test
-        Collections.sort(iaasContexts,
-                         IaasContextComparator.ascending(
-                         IaasContextComparator.getComparator(
-                         IaasContextComparator.SCALE_UP_SORT)));
-        
-        assertEquals("ec2", iaasContexts.get(0).getName().toString());
-        assertEquals("openstack", iaasContexts.get(1).getName().toString());
-        
-        // scale down order sort test
-        Collections.sort(iaasContexts,
-                         IaasContextComparator.ascending(
-                         IaasContextComparator.getComparator(
-                         IaasContextComparator.SCALE_DOWN_SORT)));
-        
-        assertEquals("openstack", iaasContexts.get(0).getName().toString());
-        assertEquals("ec2", iaasContexts.get(1).getName().toString());
-        
-        
-        IaasContext c = new IaasContext(Iaases.ec2, null);
-        c.setScaleUpOrder(0);
-        c.setScaleDownOrder(4);
-        
-        iaasContexts.add(c);
-        
-        // scale up order sort test
-        Collections.sort(iaasContexts,
-                         IaasContextComparator.ascending(
-                         IaasContextComparator.getComparator(
-                         IaasContextComparator.SCALE_UP_SORT)));
-        
-        assertEquals("ec2", iaasContexts.get(0).getName().toString());
-        assertEquals("ec2", iaasContexts.get(1).getName().toString());
-        
-        // scale down order sort test
-        Collections.sort(iaasContexts,
-                         IaasContextComparator.ascending(
-                         IaasContextComparator.getComparator(
-                         IaasContextComparator.SCALE_DOWN_SORT)));
-        
-        assertEquals("openstack", iaasContexts.get(0).getName().toString());
-        assertEquals("ec2", iaasContexts.get(1).getName().toString());
-        
-        
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java
deleted file mode 100644
index 2297a6f..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.util;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.NodeMetadataBuilder;
-import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
-import org.apache.stratos.lb.common.conf.util.Constants;
-
-import junit.framework.TestCase;
-
-public class IaasContextTest extends TestCase {
-
-    IaasContext ctx;
-    NodeMetadata node1, node2, node3, node4;
-    
-    String[] domains = {"wso2.a", "wso2.b", "wso2.c"};
-    String[] subDomains = {"mgt", "worker"};
-    String[] nodeIds = {"1", "2", "3", "4", "5"};
-    String[] ips = {"192.168.1.2", "192.168.1.3", "192.168.1.4"};
-
-    public IaasContextTest(String name) {
-        super(name);
-    }
-
-    protected void setUp() throws Exception {
-        super.setUp();
-
-        node1 = new NodeMetadataBuilder().id("1")
-                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
-                                         .publicAddresses(new ArrayList<String>(Arrays.asList("192.168.1.2")))
-                                         .build();
-        node2 = new NodeMetadataBuilder().id("2")
-                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
-                                         .build();
-        node3 = new NodeMetadataBuilder().id("3")
-                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
-                                         .build();
-        node4 = new NodeMetadataBuilder().id("4")
-                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
-                                         .build();
-
-        ctx = new IaasContext(Iaases.ec2, null);
-        
-        
-        ctx.addInstanceContext(new InstanceContext(domains[0], subDomains[0], null));
-        ctx.addInstanceContext(new InstanceContext(domains[1], subDomains[1], null));
-        ctx.addInstanceContext(new InstanceContext(domains[2], subDomains[0], null));
-        ctx.addInstanceContext(new InstanceContext(domains[2], Constants.DEFAULT_SUB_DOMAIN, null));
-        
-        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[0], "");
-        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[1], ips[0]);
-        ctx.addNodeDetails(domains[1], subDomains[1], nodeIds[2], ips[1]);
-        ctx.addNodeDetails(domains[2], subDomains[0], nodeIds[3], ips[2]);
-        ctx.addNodeDetails(domains[2], Constants.DEFAULT_SUB_DOMAIN, nodeIds[4], "");
-        
-        
-//        ctx.addNodeIdToDomainMap(node1.getId(), "wso2.a");
-//        ctx.addPublicIpToDomainMap("192.168.1.2", "wso2.a");
-//        ctx.addPublicIpToNodeIdMap("192.168.1.2", node1.getId());
-//        ctx.addNodeIdToDomainMap(node2.getId(), "wso2.b");
-//        ctx.addNodeIdToDomainMap(node3.getId(), "wso2.a");
-//        ctx.addPublicIpToDomainMap("192.168.1.3", "wso2.a");
-//        ctx.addPublicIpToNodeIdMap("192.168.1.3", node3.getId());
-//        ctx.addNodeIdToDomainMap(node4.getId(), "wso2.c");
-    }
-
-    public final void testGetLastMatchingNode() {
-
-        assertEquals(nodeIds[1], ctx.getLastMatchingNode(domains[0], subDomains[0]));
-        ctx.removeNodeId(nodeIds[1]);
-        assertEquals(nodeIds[0], ctx.getLastMatchingNode(domains[0], subDomains[0]));
-        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[1], ips[0]);
-    }
-
-    public final void testGetFirstMatchingNode() {
-        assertEquals(nodeIds[0], ctx.getFirstMatchingNode(domains[0], subDomains[0]));
-    }
-    
-    public final void testGetLastMatchingPublicIp() {
-        assertEquals(ips[0], ctx.getLastMatchingPublicIp(domains[0], subDomains[0]));
-        assertEquals(null, ctx.getLastMatchingPublicIp(domains[2], Constants.DEFAULT_SUB_DOMAIN));
-    }
-
-    public final void testGetNodeWithPublicIp() {
-        assertEquals(nodeIds[3], ctx.getNodeWithPublicIp(ips[2]));
-    }
-
-    public final void testGetNodeIds() {
-        assertEquals(new ArrayList<String>(Arrays.asList(nodeIds[0], nodeIds[1])), ctx.getNodeIds(domains[0], subDomains[0]));
-        assertEquals(new ArrayList<String>(Arrays.asList(nodeIds[2])), ctx.getNodeIds(domains[1], subDomains[1]));
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
deleted file mode 100644
index 54502b7..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.xml;
-
-import java.util.List;
-import org.apache.stratos.autoscaler.service.util.IaasProvider;
-import junit.framework.TestCase;
-
-public class ElasticScalerConfigFileReaderTest extends TestCase {
-
-    public void testGetIaasProvidersListy() throws Exception {
-        
-        String file = "src/test/resources/elastic-scaler-config.xml";
-        ElasticScalerConfigFileReader reader = new ElasticScalerConfigFileReader(file);
-        
-        List<IaasProvider> list =reader.getIaasProvidersList();
-        
-        assertEquals(2, list.size());
-        
-        assertEquals("ec2", list.get(0).getType());
-        //assertEquals("cdcd", list.get(0).getIdentity());
-        assertEquals(2, list.get(0).getScaleDownOrder());
-        assertEquals(1, list.get(0).getScaleUpOrder());
-        assertEquals("a", list.get(0).getProperties().get("A.x"));
-        assertEquals("b", list.get(0).getProperties().get("B"));
-        assertEquals(null, list.get(0).getProperties().get("AA"));
-        
-        assertEquals("openstack", list.get(1).getType());
-        //assertEquals("bebbe", list.get(1).getIdentity());
-        assertEquals(1, list.get(1).getScaleDownOrder());
-        assertEquals(2, list.get(1).getScaleUpOrder());
-        assertEquals("x", list.get(1).getProperties().get("X"));
-        assertEquals("y", list.get(1).getProperties().get("Y"));
-        assertEquals(null, list.get(1).getProperties().get("x"));
-        
-        
-        List<org.apache.stratos.autoscaler.service.util.ServiceTemplate> temps =reader.getTemplates();
-      
-        assertEquals("wso2.as.domain", temps.get(0).getDomainName());
-        assertEquals("manager,default", temps.get(0).getProperty("securityGroups"));
-        
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
deleted file mode 100644
index d05bb14..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
+++ /dev/null
@@ -1,71 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-
-<!--
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-  -->
-
-<elasticScalerConfig xmlns:svns="http://org.wso2.securevault/configuration">
-
-<svns:secureVault provider="org.wso2.securevault.secret.handler.SecretManagerSecretCallbackHandler"/>
-	<iaasProviders>
-		<iaasProvider type="ec2" name="EC2 specific details">
-			<provider>aws-ec2</provider>
-			<identity svns:secretAlias="elastic.scaler.ec2.identity">cdcd</identity>
-			<credential svns:secretAlias="elastic.scaler.ec2.credential">cdccdc</credential>
-			<scaleUpOrder>1</scaleUpOrder>
-			<scaleDownOrder>2</scaleDownOrder>
-			<property name="A.x" value="a"/>
-			<property name="B" value="b"/>
-			<imageId>tempEC2</imageId>
-		</iaasProvider>
-		<iaasProvider type="openstack" >
-			<provider>lxc</provider>
-			<identity svns:secretAlias="elastic.scaler.openstack.identity">bebbe</identity>
-			<credential svns:secretAlias="elastic.scaler.openstack.credential">bebebe</credential>
-			<scaleUpOrder>2</scaleUpOrder>
-			<scaleDownOrder>1</scaleDownOrder>
-			<property name="X" value="x"/>
-			<property name="Y" value="y"/>
-			<imageId>tempLXC</imageId>
-		</iaasProvider>
-	</iaasProviders>
-	
-	<services>
-		<default>
-			<property name="availabilityZone" value="us-east-1c"/>
-			<property name="securityGroups" value="manager,cep,mb,default"/>
-            <property name="instanceType.ec2" value="m1.large"/>
-            <property name="instanceType.openstack" value="1"/>
-            <property name="minAppInstances" value="1"/>
-            <property name="maxAppInstances" value="5"/>
-            <property name="queueLengthPerNode" value="50"/>
-            <property name="roundsToAverage" value="100"/>
-            <property name="instancesPerScaleUp" value="1"/>
-            <property name="messageExpiryTime" value="60000"/>
-            <property name="keyPair" value="aa"/>
-		</default>
-		<service domain="wso2.as.domain" subDomain="mgt">
-			<property name="securityGroups" value="manager,default"/>
-            <property name="availabilityZone" value="us-east-1c"/>
-            <property name="payload" value="resources/as.zip"/>
-		</service>
-	</services>
-
-</elasticScalerConfig>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml
deleted file mode 100644
index c55c091..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/pom.xml
+++ /dev/null
@@ -1,137 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-     ~  Licensed to the Apache Software Foundation (ASF) under one
-     ~  or more contributor license agreements.  See the NOTICE file
-     ~  distributed with this work for additional information
-     ~  regarding copyright ownership.  The ASF licenses this file
-     ~  to you under the Apache License, Version 2.0 (the
-     ~  "License"); you may not use this file except in compliance
-     ~  with the License.  You may obtain a copy of the License at
-     ~
-     ~    http://www.apache.org/licenses/LICENSE-2.0
-     ~
-     ~  Unless required by applicable law or agreed to in writing,
-     ~  software distributed under the License is distributed on an
-     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-     ~  KIND, either express or implied.  See the License for the
-     ~  specific language governing permissions and limitations
-     ~  under the License.
-     ~
- -->
-
-
-<!--
-We need to modify this file since this copied from branch
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../../../pom.xml</relativePath>
-    </parent>
-
-    <version>4.1.3</version>
-    <modelVersion>4.0.0</modelVersion>
-    <groupId>org.apache.stratos</groupId>
-    <artifactId>org.apache.stratos.mediator.autoscale</artifactId>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Autoscale Mediator BE</name>
-    <url>http://apache.org</url>
-
-    <build>
-        <plugins>
-			<plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                <version>1.4.0</version>
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Export-Package>
-                            !org.org.apache.stratos.mediator.autoscale.lbautoscale.internal,
-                            org.apache.stratos.mediator.autoscale.*
-                        </Export-Package>
-                        <Private-Package>org.apache.stratos.mediator.autoscale.lbautoscale.internal</Private-Package>
-                        <Import-Package>
-                            !javax.xml.namespace,
-                            javax.xml.namespace; version=0.0.0,
-                            !org.apache.commons.logging,
-                            org.apache.commons.logging; version=0.0.0,
-                            org.apache.axis2.*,
-                            org.apache.synapse.*,
-                            org.wso2.carbon.task.*; version=0.0.0,
-                            org.wso2.carbon.core.*,
-                            org.apache.stratos.lb.common.*,
-                            org.wso2.carbon.load.balance.cartridge.autoscaler.service.stub.*; version=0.0.0,
-                            org.wso2.carbon.utils.*,
-                            org.apache.axiom.om; version="${axiom.osgi.version.range}",
-                            org.wso2.carbon.stratos.cloud.controller.*,
-                            *; resolution:=optional
-                        </Import-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-    <dependencies>
-        <dependency>
-          <groupId>org.apache.axis2.wso2</groupId>
-          <artifactId>axis2</artifactId>
-          <version>1.6.1.wso2v9</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.synapse</groupId>
-            <artifactId>synapse-core</artifactId>
-            <version>${synapse.core.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.load.balance.cartridge.autoscaler.service.stub</artifactId>
-            <version>4.1.1</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.core</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.utils</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.stratos</groupId>
-            <artifactId>org.apache.stratos.lb.common</artifactId>
-            <version>4.1.3</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.stratos.cloud.controller</artifactId>
-            <version>2.1.1</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.task</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.synapse</groupId>
-            <artifactId>synapse-tasks</artifactId>
-            <version>2.1.1-wso2v4</version>
-        </dependency>
-
-    </dependencies>
-
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
deleted file mode 100644
index c535489..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.mediator.autoscale.lbautoscale.callables;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-
-import java.util.concurrent.Callable;
-
-/** Performing sanity checks for each service domain, sub domain combination **/
-public class AppNodeSanityCheckCallable implements Callable<Boolean> {
-
-    private static final Log log = LogFactory.getLog(AppNodeSanityCheckCallable.class);
-    private String domain;
-    private String subDomain;
-    private CloudControllerClient client;
-    private AppDomainContext appDomainContext;
-    private ServiceConfiguration serviceConfig;
-    
-    public AppNodeSanityCheckCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
-        this.domain = domain;
-        this.subDomain = subDomain;
-        this.client = client;
-        this.appDomainContext = appCtxt;
-        serviceConfig =
-                AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig().getServiceConfig(this.domain,
-                    this.subDomain);
-    }
-    
-    @Override
-    public Boolean call() throws Exception {
-
-        if (appDomainContext != null) {
-            int currentInstances = 0;
-            // we're considering both running and pending instance count
-            currentInstances = appDomainContext.getInstances();
-
-            int requiredInstances = serviceConfig.getMinAppInstances();
-
-            // we try to maintain the minimum number of instances required
-            if (currentInstances < requiredInstances) {
-                log.debug("App domain Sanity check failed for " +
-                    AutoscaleUtil.domainSubDomainString(domain, subDomain) +
-                        " . Current instances: " +
-                        currentInstances +
-                        ". Required instances: " +
-                        requiredInstances);
-
-                int diff = requiredInstances - currentInstances;
-
-                // Launch diff number of App instances
-                log.debug("Launching " +
-                    diff +
-                    " App instances for " +AutoscaleUtil.domainSubDomainString(domain, subDomain));
-
-                // FIXME: should we need to consider serviceConfig.getInstancesPerScaleUp()?
-                AutoscaleUtil.runInstances(client, appDomainContext, this.domain, this.subDomain, diff);
-            }
-        }
-
-        return true;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
deleted file mode 100644
index 84705bb..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.callables;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.state.check.TerminatingInstancesStateChecker;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-
-import java.util.concurrent.Callable;
-
-/** Take auto-scaling decisions for each service domain, sub domain combination **/
-public class AutoscaleDeciderCallable implements Callable<Boolean> {
-
-    private static final Log log = LogFactory.getLog(AutoscaleDeciderCallable.class);
-    private String domain;
-    private String subDomain;
-    private CloudControllerClient client;
-    private AppDomainContext appDomainContext;
-    private ServiceConfiguration serviceConfig;
-    private String clusterStr;
-    
-    public AutoscaleDeciderCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
-        this.domain = domain;
-        this.subDomain = subDomain;
-        this.client = client;
-        this.appDomainContext = appCtxt;
-        clusterStr = AutoscaleUtil.domainSubDomainString(domain, subDomain);
-    }
-    
-    @Override
-    public Boolean call() throws Exception {
-
-        // expire tokens
-        if (appDomainContext != null) {
-            appDomainContext.expireRequestTokens();
-
-            serviceConfig = appDomainContext.getServiceConfig();
-
-            appDomainContext.recordRequestTokenListLength();
-            if (!appDomainContext.canMakeScalingDecision()) {
-                return true;
-            }
-
-            long average = appDomainContext.getAverageRequestsInFlight();
-            int runningAppInstances = appDomainContext.getRunningInstanceCount();
-            int terminatingAppInstances = appDomainContext.getTerminatingInstanceCount();
-
-            int maxRPS = serviceConfig.getMaxRequestsPerSecond();
-            double taskInterval =
-                AutoscalerTaskDSHolder
-                    .getInstance()
-                    .getWholeLoadBalancerConfig()
-                    .getLoadBalancerConfig()
-                    .getAutoscalerTaskInterval() / (double)1000;
-            double aur = serviceConfig.getAlarmingUpperRate();
-            double alr = serviceConfig.getAlarmingLowerRate();
-            double scaleDownFactor = serviceConfig.getScaleDownFactor();
-
-            // scale up early
-            double maxhandleableReqs = maxRPS * taskInterval * aur;
-            // scale down slowly
-            double minhandleableReqs = maxRPS * taskInterval * alr * scaleDownFactor;
-
-            if (log.isDebugEnabled()) {
-                log.debug(clusterStr +": Average requests in flight: " + average + " **** Handleable requests: " +
-                    (runningAppInstances * maxhandleableReqs));
-            }
-            if (average > (runningAppInstances * maxhandleableReqs) && maxhandleableReqs > 0) {
-                
-                // estimate number of instances we might want to spawn
-                int requiredInstances = (int) Math.ceil(average/maxhandleableReqs);
-                
-                log.debug(clusterStr+" : Required instance count: "+requiredInstances);
-                
-                // current average is higher than that can be handled by current nodes.
-                scaleUp(requiredInstances - runningAppInstances);
-            } else if (terminatingAppInstances == 0 && average < ((runningAppInstances - 1) * minhandleableReqs)) {
-                // current average is less than that can be handled by (current nodes - 1).
-                scaleDown();
-            }
-        }
-
-        return true;
-    }
-
-    private void scaleDown() {
-
-        int runningInstances = appDomainContext.getRunningInstanceCount();
-//        int pendingInstances = appDomainContext.getPendingInstanceCount();
-        int terminatingInstances = appDomainContext.getTerminatingInstanceCount();
-        int minAppInstances = serviceConfig.getMinAppInstances();
-//        int serverStartupDelay = AutoscalerTaskDSHolder
-//                                            .getInstance()
-//                                            .getWholeLoadBalancerConfig()
-//                                            .getLoadBalancerConfig()
-//                                            .getServerStartupDelay();
-
-        if ( (runningInstances - terminatingInstances) > minAppInstances) {
-
-            if (log.isDebugEnabled()) {
-                log.debug("Scale Down - " +
-                    clusterStr +
-                        ". Running instances:" +
-                        runningInstances +
-                        ". Terminating instances: " +
-                        terminatingInstances +
-                        ". Min instances:" +
-                        minAppInstances);
-            }
-            // ask to scale down
-            try {
-                if (client.terminateInstance(domain, subDomain)) {
-                    
-                    Thread th = new Thread(new TerminatingInstancesStateChecker(appDomainContext, domain, subDomain));
-                    th.start();
-                    
-//                        log.debug(clusterStr +": There's an instance who's in shutting down state " +
-//                            "(but still not left ELB), hence we should wait till " +
-//                            "it leaves the cluster.");
-//
-//                        int totalWaitedTime = 0;
-//
-//                        log.debug(clusterStr +": Task will wait maximum of (milliseconds) : " +
-//                            serverStartupDelay +
-//                                ", to let the member leave the cluster.");
-//                        
-//                        // for each sub domain, get the clustering group management agent
-//                        GroupManagementAgent agent =
-//                            AutoscalerTaskDSHolder.getInstance().getAgent()
-//                                .getGroupManagementAgent(domain,
-//                                    subDomain);
-//
-//                        // we give some time for the server to be terminated, we'll check time to time
-//                        // whether the instance has actually left the cluster.
-//                        while (agent.getMembers().size() == runningInstances &&
-//                            totalWaitedTime < serverStartupDelay) {
-//
-//                            try {
-//                                Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
-//                            } catch (InterruptedException ignore) {
-//                            }
-//
-//                            totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
-//                        }
-//
-//                        log.debug(clusterStr+ " : task waited for (milliseconds) : " + totalWaitedTime);
-//
-//                        // we recalculate number of alive instances
-//                        runningInstances = agent.getMembers().size();
-//                        
-//                        appDomainContext.setRunningInstanceCount(runningInstances);
-//
-//                        log.debug(clusterStr+" : New running instance count: " + runningInstances);
-                }
-
-            } catch (Exception e) {
-                log.error("Instance termination failed for " + clusterStr, e);
-            }
-        }
-
-    }
-
-    private void scaleUp(int requiredInstanceCount) {
-
-        int maxAppInstances = serviceConfig.getMaxAppInstances();
-//        int instancesPerScaleUp = serviceConfig.getInstancesPerScaleUp();
-//        int runningInstances = appDomainContext.getRunningInstanceCount();
-//        int pendingInstances = appDomainContext.getPendingInstanceCount();
-        int totalInstanceCount = appDomainContext.getInstances();
-        
-        log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain)+ " - Total Running/Pending instance count: "+totalInstanceCount);
-        
-        if(maxAppInstances > totalInstanceCount){
-            
-            int availableQuotaOfInstances = maxAppInstances - totalInstanceCount;
-            
-            log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain)+ " - Available Quota of Instances: "+availableQuotaOfInstances);
-            
-            requiredInstanceCount = requiredInstanceCount <= availableQuotaOfInstances ? requiredInstanceCount : availableQuotaOfInstances;
-            
-            log.debug(clusterStr + " - Going to start " +
-                    requiredInstanceCount + " instance/s.");
-
-                AutoscaleUtil.runInstances(client, appDomainContext, domain, subDomain,
-                    requiredInstanceCount);
-                
-        } else if (totalInstanceCount > maxAppInstances) {
-            log.fatal("Number of running instances has over reached the maximum limit of " +
-                maxAppInstances + " of " + clusterStr);
-        }
-
-//        int failedInstances = 0;
-//        if (runningInstances < maxAppInstances && pendingInstances == 0) {
-//
-//            log.debug(clusterStr + " - Going to start " +
-//                    requiredInstanceCount + " instance/s. Running instances:" + runningInstances);
-//
-//                AutoscaleUtil.runInstances(client, appDomainContext, domain, subDomain,
-//                    requiredInstanceCount);
-
-//            if (successfullyStarted != instancesPerScaleUp) {
-//                failedInstances = instancesPerScaleUp - successfullyStarted;
-//                if (log.isDebugEnabled()) {
-//                    log.debug(successfullyStarted +
-//                        " instances successfully started and\n" + failedInstances +
-//                        " instances failed to start for " + clusterStr);
-//                }
-//            }
-//
-//            // we increment the pending instance count
-//            // appDomainContext.incrementPendingInstances(instancesPerScaleUp);
-//            else {
-//                log.debug("Successfully started " + successfullyStarted +
-//                    " instances of " + clusterStr);
-//            }
-
-       
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
deleted file mode 100644
index 90c2c3a..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.callables;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-
-/** Calculate instances of each service domain, sub domain combination **/
-public class InstanceCountCallable implements Callable<Boolean> {
-
-    private static final Log log = LogFactory.getLog(InstanceCountCallable.class);
-    private String domain;
-    private String subDomain;
-    private CloudControllerClient client;
-    private AppDomainContext appCtxt;
-    private ExecutorService executor = Executors.newFixedThreadPool(10);
-    
-    public InstanceCountCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
-        this.domain = domain;
-        this.subDomain = subDomain;
-        this.client = client;
-        this.appCtxt = appCtxt;
-    }
-    
-    @Override
-    public Boolean call() throws Exception {
-        log.debug("Computation of instance counts started for domain: " + this.domain +
-            " and sub domain: " + this.subDomain);
-
-        Callable<Integer> worker = new RunningInstanceCountCallable(this.domain, this.subDomain);
-        Future<Integer> runningInstanceCount = executor.submit(worker);
-
-//        worker = new PendingInstanceCountCallable(this.domain, this.subDomain, client);
-//        Future<Integer> pendingInstanceCount = executor.submit(worker);
-
-        int runningInstances = 0, pendingInstances = 0;
-        if (appCtxt != null) {
-
-            try {
-                // get the values of Callables
-                runningInstances = runningInstanceCount.get();
-                pendingInstances = appCtxt.getPendingInstanceCount();
-            } catch (Exception e) {
-                // no need to throw
-                log.error(e.getMessage(), e);
-            }
-
-            appCtxt.setRunningInstanceCount(runningInstances);
-            appCtxt.setPendingInstanceCount(pendingInstances);
-            
-        }
-        return true;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
deleted file mode 100644
index 27cf50e..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.callables;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-
-import java.util.concurrent.Callable;
-
-/** Calculate pending instances of each service domain, sub domain combination **/
-public class PendingInstanceCountCallable implements Callable<Integer> {
-
-    private static final Log log = LogFactory.getLog(PendingInstanceCountCallable.class);
-    private String domain;
-    private String subDomain;
-    private CloudControllerClient client;
-    
-    public PendingInstanceCountCallable(String domain, String subDomain, CloudControllerClient client){
-        this.domain = domain;
-        this.subDomain = subDomain;
-        this.client = client;
-    }
-    
-    @Override
-    public Integer call() throws Exception {
-        int pendingInstanceCount = 0;
-
-        try {
-            pendingInstanceCount =
-                client.getPendingInstanceCount(this.domain,
-                    this.subDomain);
-
-        } catch (Exception e) {
-            log.error("Failed to retrieve pending instance count for domain: " +
-                this.domain + " and sub domain: " + this.subDomain, e);
-        }
-
-        log.debug("Pending instance count for domain: " +
-            this.domain +
-            ", sub domain: " +
-            this.subDomain +
-            " is " +
-            pendingInstanceCount);
-
-        return pendingInstanceCount;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
deleted file mode 100644
index 3bc3db5..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.callables;
-
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-
-import java.util.concurrent.Callable;
-
-/** Calculate running instances of each service domain, sub domain combination **/
-public class RunningInstanceCountCallable implements Callable<Integer> {
-
-    private static final Log log = LogFactory.getLog(RunningInstanceCountCallable.class);
-    private String domain;
-    private String subDomain;
-    
-    public RunningInstanceCountCallable(String domain, String subDomain){
-        this.domain = domain;
-        this.subDomain = subDomain;
-    }
-    
-    @Override
-    public Integer call() throws Exception {
-        int runningInstances;
-        // for each sub domain, get the clustering group management agent
-        GroupManagementAgent agent =
-            AutoscalerTaskDSHolder.getInstance().getAgent()
-                .getGroupManagementAgent(this.domain,
-                    this.subDomain);
-
-        // if it isn't null
-        if (agent != null) {
-            // we calculate running instance count for this service domain
-            runningInstances = agent.getMembers().size();
-        } else {
-            // if agent is null, we assume no service instances are running
-            runningInstances = 0;
-        }
-
-        log.debug("Running instance count for domain: " +
-            this.domain +
-                ", sub domain: " +
-                this.subDomain +
-                " is " +
-                runningInstances);
-        
-        return runningInstances;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
deleted file mode 100644
index ec9e1bb..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.clients;
-
-/**
- * Each Implementation which provides access to Cloud Controller, should implement this interface.
- */
-public abstract class CloudControllerClient {
-
-    /**
-     * Initializes the client.
-     */
-    public abstract void init();
-    
-    /**
-     * Should start an instance.
-     * @param domainName clustering domain.
-     * @param subDomainName clustering sub domain.
-     * @return Public IP of the spawned instance.
-     * @throws Exception 
-     */
-    public abstract String startInstance(String domainName, String subDomainName) throws Exception;
-    
-    /**
-     * Terminates an instance belongs to the given cluster.
-     * @param domainName clustering domain.
-     * @param subDomainName clustering sub domain.
-     * @return whether the termination is successful or not.
-     * @throws Exception
-     */
-    public abstract boolean terminateInstance(String domainName, String subDomainName) throws Exception;
-    
-    /**
-     * Terminates lastly spawned instance of the given cluster.
-     * @param domainName clustering domain.
-     * @param subDomainName clustering sub domain.
-     * @return whether the termination is successful or not.
-     * @throws Exception
-     */
-    public abstract boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception;
-    
-    /**
-     * Return pending instance count of the given cluster.
-     * @param domainName clustering domain.
-     * @param subDomainName clustering sub domain.
-     * @return pending instance count.
-     * @throws Exception
-     */
-    public abstract int getPendingInstanceCount(String domainName, String subDomainName) throws Exception;
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
deleted file mode 100644
index ad95a89..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.clients;
-
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
-
-/**
- * This is the client class this calls Autoscaler service.
- */
-public class CloudControllerOsgiClient extends CloudControllerClient {
-
-    private CloudControllerService cloudControllerService;
-
-    private static final Log log = LogFactory.getLog(CloudControllerOsgiClient.class);
-
-    // public CloudControllerStubClient(String epr) throws AxisFault {
-    //
-    // try {
-    //
-    // stub = new CloudControllerServiceStub(epr);
-    // stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(90000);
-    //
-    // } catch (AxisFault axisFault) {
-    // String msg =
-    // "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
-    // log.error(msg, axisFault);
-    // throw new AxisFault(msg, axisFault);
-    // }
-    // }
-
-    // public boolean init(boolean isSpi) throws Exception {
-    //
-    // return stub.initAutoscaler(isSpi);
-    // }
-
-    public String startInstance(String domainName, String subDomainName) throws Exception {
-
-        return cloudControllerService.startInstance(domainName, subDomainName);
-    }
-
-    public boolean terminateInstance(String domainName, String subDomainName) throws Exception {
-
-        return cloudControllerService.terminateInstance(domainName, subDomainName);
-    }
-
-    public boolean
-        terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception {
-
-        return cloudControllerService.terminateLastlySpawnedInstance(domainName, subDomainName);
-    }
-
-    public int getPendingInstanceCount(String domainName, String subDomainName) throws Exception {
-
-        return cloudControllerService.getPendingInstanceCount(domainName, subDomainName);
-    }
-
-    @Override
-    public void init() {
-
-        cloudControllerService = AutoscalerTaskDSHolder.getInstance().getCloudControllerService();
-    }
-
-}


[44/45] git commit: fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
fixing component version issues and adding currently refactored components to the parent pom


Project: http://git-wip-us.apache.org/repos/asf/incubator-stratos/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-stratos/commit/ac065d73
Tree: http://git-wip-us.apache.org/repos/asf/incubator-stratos/tree/ac065d73
Diff: http://git-wip-us.apache.org/repos/asf/incubator-stratos/diff/ac065d73

Branch: refs/heads/master
Commit: ac065d7307ff915f08d199dacbac0f0faa34ad17
Parents: 20cfe7e
Author: Isuru <is...@wso2.com>
Authored: Wed Jul 10 22:20:47 2013 +0530
Committer: Isuru <is...@wso2.com>
Committed: Wed Jul 10 22:20:47 2013 +0530

----------------------------------------------------------------------
 .../4.1.0/pom.xml                               |  210 ---
 .../autoscaler/service/IAutoscalerService.java  |  112 --
 .../exception/AutoscalerServiceException.java   |   33 -
 .../exception/DeserializationException.java     |   33 -
 .../MalformedConfigurationFileException.java    |   33 -
 .../exception/NoInstanceFoundException.java     |   39 -
 .../exception/SerializationException.java       |   33 -
 .../service/impl/AutoscalerServiceImpl.java     | 1389 ------------------
 .../internal/AutoscalerServiceDSComponent.java  |   48 -
 .../autoscaler/service/io/Deserializer.java     |   68 -
 .../autoscaler/service/io/Serializer.java       |   61 -
 .../service/jcloud/ComputeServiceBuilder.java   |   65 -
 .../service/util/AutoscalerConstant.java        |   73 -
 .../autoscaler/service/util/IaasContext.java    |  391 -----
 .../autoscaler/service/util/IaasProvider.java   |  141 --
 .../service/util/InstanceContext.java           |   93 --
 .../service/util/ServiceTemplate.java           |   84 --
 .../xml/ElasticScalerConfigFileReader.java      |  557 -------
 .../src/main/resources/META-INF/services.xml    |    9 -
 .../service/util/IaasContextComparatorTest.java |   98 --
 .../service/util/IaasContextTest.java           |  113 --
 .../xml/ElasticScalerConfigFileReaderTest.java  |   60 -
 .../test/resources/elastic-scaler-config.xml    |   71 -
 .../4.1.3/pom.xml                               |  137 --
 .../callables/AppNodeSanityCheckCallable.java   |   86 --
 .../callables/AutoscaleDeciderCallable.java     |  241 ---
 .../callables/InstanceCountCallable.java        |   78 -
 .../callables/PendingInstanceCountCallable.java |   65 -
 .../callables/RunningInstanceCountCallable.java |   68 -
 .../clients/CloudControllerClient.java          |   66 -
 .../clients/CloudControllerOsgiClient.java      |   82 --
 .../clients/CloudControllerStubClient.java      |   93 --
 .../lbautoscale/context/AppDomainContext.java   |  170 ---
 .../context/LoadBalancerContext.java            |  104 --
 .../AutoscalerTaskServiceComponent.java         |  325 ----
 .../lbautoscale/internal/RegistryManager.java   |   54 -
 .../mediators/AutoscaleInMediator.java          |  174 ---
 .../mediators/AutoscaleOutMediator.java         |   78 -
 .../check/PendingInstancesStateChecker.java     |  148 --
 .../check/TerminatingInstancesStateChecker.java |   89 --
 .../task/AutoscalerTaskInitializer.java         |   50 -
 .../task/AutoscalerTaskMgmtAdminService.java    |  348 -----
 .../lbautoscale/task/AutoscalingJob.java        |   68 -
 .../task/ServiceRequestsInFlightAutoscaler.java |  524 -------
 .../lbautoscale/task/TaskSchedulingManager.java |  188 ---
 .../lbautoscale/util/AutoscaleConstants.java    |   68 -
 .../lbautoscale/util/AutoscaleUtil.java         |  359 -----
 .../util/AutoscalerTaskDSHolder.java            |  129 --
 ...rg.apache.synapse.config.xml.MediatorFactory |    2 -
 ...apache.synapse.config.xml.MediatorSerializer |    2 -
 .../src/main/resources/synapse-load-average.xml |  138 --
 .../resources/synapse-messages-in-flight.xml    |  135 --
 .../synapse-service-messages-in-flight.xml      |  108 --
 .../lbautoscale/AppDomainContextsTest.java      |  105 --
 .../4.1.3/src/test/resources/loadbalancer.conf  |   50 -
 .../4.1.3/pom.xml                               |  116 --
 .../stratos/lb/endpoint/EndpointConstants.java  |   31 -
 .../stratos/lb/endpoint/EndpointDeployer.java   |   71 -
 ...TenantAwareLoadBalanceEndpointException.java |   39 -
 .../TenantLoadBalanceMembershipHandler.java     |  208 ---
 .../lb/endpoint/builder/TopologySyncher.java    |  159 --
 .../manager/ClusterDomainManagerImpl.java       |  228 ---
 .../TenantAwareLoadBalanceEndpoint.java         |  531 -------
 .../group/mgt/GroupMgtAgentBuilder.java         |   80 -
 .../LoadBalanceEndpointServiceComponent.java    |  397 -----
 .../lb/endpoint/internal/RegistryManager.java   |   54 -
 .../endpoint/subscriber/TopicHealthChecker.java |   68 -
 .../endpoint/subscriber/TopologyListener.java   |   47 -
 .../endpoint/subscriber/TopologySubscriber.java |   95 --
 .../stratos/lb/endpoint/util/ConfigHolder.java  |  192 ---
 .../lb/endpoint/util/TopologyConstants.java     |   31 -
 .../org.apache.stratos.activation/2.1.2/pom.xml |   96 --
 .../internal/ActivationServiceComponent.java    |  152 --
 .../activation/module/ActivationHandler.java    |  161 --
 .../activation/module/ActivationModule.java     |   65 -
 .../activation/service/ActivationService.java   |   85 --
 .../activation/utils/ActivationManager.java     |   96 --
 .../activation/activation/utils/Util.java       |  138 --
 .../src/main/resources/META-INF/module.xml      |   33 -
 .../src/main/resources/META-INF/services.xml    |   30 -
 .../org.apache.stratos.activation/pom.xml       |   94 ++
 .../internal/ActivationServiceComponent.java    |  152 ++
 .../activation/module/ActivationHandler.java    |  161 ++
 .../activation/module/ActivationModule.java     |   65 +
 .../activation/service/ActivationService.java   |   85 ++
 .../activation/utils/ActivationManager.java     |   96 ++
 .../activation/activation/utils/Util.java       |  138 ++
 .../src/main/resources/META-INF/module.xml      |   33 +
 .../src/main/resources/META-INF/services.xml    |   30 +
 .../2.1.3/pom.xml                               |  125 --
 .../2.1.3/src/main/assembly/src.xml             |   36 -
 .../2.1.3/src/main/java/Main.iml                |  204 ---
 .../org/apache/stratos/adc/mgt/cli/CliTool.java |   76 -
 .../org/apache/stratos/adc/mgt/cli/Command.java |   67 -
 .../stratos/adc/mgt/cli/CommandContext.java     |   88 --
 .../adc/mgt/cli/CommandLineApplication.java     |  190 ---
 .../stratos/adc/mgt/cli/CommandLineService.java |  556 -------
 .../stratos/adc/mgt/cli/StratosApplication.java |  504 -------
 .../adc/mgt/cli/StratosCommandContext.java      |   31 -
 .../cli/commands/AddDomainMappingCommand.java   |   87 --
 .../adc/mgt/cli/commands/CartridgesCommand.java |   71 -
 .../adc/mgt/cli/commands/ExitCommand.java       |   70 -
 .../adc/mgt/cli/commands/HelpCommand.java       |   73 -
 .../adc/mgt/cli/commands/InfoCommand.java       |   75 -
 .../adc/mgt/cli/commands/ListCommand.java       |  123 --
 .../adc/mgt/cli/commands/PoliciesCommand.java   |   71 -
 .../commands/RemoveDomainMappingCommand.java    |   75 -
 .../adc/mgt/cli/commands/SubscribeCommand.java  |  208 ---
 .../adc/mgt/cli/commands/SyncCommand.java       |   76 -
 .../mgt/cli/commands/UnsubscribeCommand.java    |  130 --
 .../adc/mgt/cli/completer/CommandCompleter.java |  133 --
 .../adc/mgt/cli/exception/CommandException.java |   39 -
 .../stratos/adc/mgt/cli/utils/CliConstants.java |  130 --
 .../adc/mgt/cli/utils/CommandLineUtils.java     |   94 --
 .../stratos/adc/mgt/cli/utils/RowMapper.java    |   23 -
 .../src/main/resources/Resources.properties     |   25 -
 .../2.1.3/src/main/resources/log4j.properties   |   15 -
 .../2.1.3/src/main/resources/wso2carbon.jks     |  Bin 33260 -> 0 bytes
 .../org.apache.stratos.adc.mgt.cli/pom.xml      |  123 ++
 .../src/main/assembly/src.xml                   |   36 +
 .../src/main/java/Main.iml                      |  204 +++
 .../org/apache/stratos/adc/mgt/cli/CliTool.java |   76 +
 .../org/apache/stratos/adc/mgt/cli/Command.java |   67 +
 .../stratos/adc/mgt/cli/CommandContext.java     |   88 ++
 .../adc/mgt/cli/CommandLineApplication.java     |  190 +++
 .../stratos/adc/mgt/cli/CommandLineService.java |  556 +++++++
 .../stratos/adc/mgt/cli/StratosApplication.java |  504 +++++++
 .../adc/mgt/cli/StratosCommandContext.java      |   31 +
 .../cli/commands/AddDomainMappingCommand.java   |   87 ++
 .../adc/mgt/cli/commands/CartridgesCommand.java |   71 +
 .../adc/mgt/cli/commands/ExitCommand.java       |   70 +
 .../adc/mgt/cli/commands/HelpCommand.java       |   73 +
 .../adc/mgt/cli/commands/InfoCommand.java       |   75 +
 .../adc/mgt/cli/commands/ListCommand.java       |  123 ++
 .../adc/mgt/cli/commands/PoliciesCommand.java   |   71 +
 .../commands/RemoveDomainMappingCommand.java    |   75 +
 .../adc/mgt/cli/commands/SubscribeCommand.java  |  208 +++
 .../adc/mgt/cli/commands/SyncCommand.java       |   76 +
 .../mgt/cli/commands/UnsubscribeCommand.java    |  130 ++
 .../adc/mgt/cli/completer/CommandCompleter.java |  133 ++
 .../adc/mgt/cli/exception/CommandException.java |   39 +
 .../stratos/adc/mgt/cli/utils/CliConstants.java |  130 ++
 .../adc/mgt/cli/utils/CommandLineUtils.java     |   94 ++
 .../stratos/adc/mgt/cli/utils/RowMapper.java    |   23 +
 .../src/main/resources/Resources.properties     |   25 +
 .../src/main/resources/log4j.properties         |   15 +
 .../src/main/resources/wso2carbon.jks           |  Bin 0 -> 33260 bytes
 .../2.1.1/pom.xml                               |   87 --
 .../service/RepositorySynchronizer.java         |   37 -
 .../src/main/webapp/WEB-INF/cxf-servlet.xml     |   34 -
 .../2.1.1/src/main/webapp/WEB-INF/web.xml       |   49 -
 .../2.1.1/src/main/webapp/servicelist.css       |  117 --
 .../pom.xml                                     |   85 ++
 .../service/RepositorySynchronizer.java         |   37 +
 .../src/main/webapp/WEB-INF/cxf-servlet.xml     |   34 +
 .../src/main/webapp/WEB-INF/web.xml             |   49 +
 .../src/main/webapp/servicelist.css             |  117 ++
 .../org.apache.stratos.adc.mgt/2.1.3/pom.xml    |  144 --
 .../2.1.3/src/conf/cartridge-config.properties  |   38 -
 .../2.1.3/src/conf/tenant-resource-policy.xml   |    1 -
 .../adc/mgt/client/CartridgeAgentClient.java    |   39 -
 .../client/CloudControllerServiceClient.java    |   94 --
 .../stratos/adc/mgt/client/RegistryClient.java  |  112 --
 .../adc/mgt/custom/domain/RegistryManager.java  |  106 --
 .../adc/mgt/dao/CartridgeSubscription.java      |  186 ---
 .../stratos/adc/mgt/dao/DataCartridge.java      |   49 -
 .../apache/stratos/adc/mgt/dao/PortMapping.java |   56 -
 .../apache/stratos/adc/mgt/dao/Repository.java  |   56 -
 .../adc/mgt/dao/RepositoryCredentials.java      |   27 -
 .../apache/stratos/adc/mgt/dns/DNSManager.java  |   86 --
 .../org/apache/stratos/adc/mgt/dto/AppRepo.java |   85 --
 .../apache/stratos/adc/mgt/dto/Cartridge.java   |  198 ---
 .../stratos/adc/mgt/dto/CartridgeDetail.java    |    1 -
 .../adc/mgt/dto/CartridgeInformation.java       |    1 -
 .../stratos/adc/mgt/dto/CartridgeWrapper.java   |   49 -
 .../org/apache/stratos/adc/mgt/dto/Policy.java  |  145 --
 .../stratos/adc/mgt/dto/PolicyDefinition.java   |   80 -
 .../adc/mgt/dto/RepositoryInformation.java      |   43 -
 .../stratos/adc/mgt/dto/SubscriptionInfo.java   |   43 -
 .../stratos/adc/mgt/exception/ADCException.java |   46 -
 .../exception/AlreadySubscribedException.java   |   45 -
 .../exception/DomainMappingExistsException.java |   45 -
 .../DuplicateCartridgeAliasException.java       |   53 -
 .../InvalidCartridgeAliasException.java         |   54 -
 .../exception/InvalidRepositoryException.java   |   32 -
 .../mgt/exception/NotSubscribedException.java   |   46 -
 .../adc/mgt/exception/PolicyException.java      |   38 -
 .../RepositoryCredentialsRequiredException.java |   37 -
 .../exception/RepositoryRequiredException.java  |   37 -
 .../exception/RepositoryTransportException.java |   37 -
 .../UnregisteredCartridgeException.java         |   45 -
 .../internal/ADCManagementServerComponent.java  |  106 --
 .../stratos/adc/mgt/internal/DataHolder.java    |   77 -
 .../adc/mgt/internal/HostingConstants.java      |   37 -
 .../internal/HostingManagementActivator.java    |   60 -
 .../service/ApplicationManagementService.java   |  620 --------
 .../InstanceInformationManagementService.java   |   55 -
 .../mgt/service/RepoNotificationService.java    |  179 ---
 .../adc/mgt/service/RepositoryInfoBean.java     |   78 -
 .../service/RepositoryInformationService.java   |   66 -
 .../mgt/utils/ApplicationManagementUtil.java    | 1095 --------------
 .../stratos/adc/mgt/utils/CartridgeAppType.java |   41 -
 .../mgt/utils/CartridgeConfigFileReader.java    |   59 -
 .../adc/mgt/utils/CartridgeConstants.java       |   74 -
 .../stratos/adc/mgt/utils/CartridgeDomain.java  |  143 --
 .../stratos/adc/mgt/utils/DomainInfo.java       |   40 -
 .../adc/mgt/utils/PersistenceManager.java       |  853 -----------
 .../stratos/adc/mgt/utils/PolicyHolder.java     |  289 ----
 .../adc/mgt/utils/RepositoryCreator.java        |  266 ----
 .../adc/mgt/utils/RepositoryFactory.java        |  129 --
 .../stratos/adc/mgt/utils/StratosDBUtils.java   |  210 ---
 .../mgt/utils/SynchronizeRepositoryRequest.java |  143 --
 .../src/main/resources/META-INF/services.xml    |   86 --
 .../2.1.3/src/main/resources/policies.xsd       |   36 -
 .../2.1.3/src/scripts/append_zone_file.sh       |   24 -
 .../stratos/adc/mgt/test/PolicyHolderTest.java  |   63 -
 .../2.1.3/src/test/resources/log4j.properties   |    8 -
 .../2.1.3/src/test/resources/policies-1.xml     |   22 -
 components/org.apache.stratos.adc.mgt/pom.xml   |  142 ++
 .../src/conf/cartridge-config.properties        |   38 +
 .../src/conf/tenant-resource-policy.xml         |    1 +
 .../adc/mgt/client/CartridgeAgentClient.java    |   39 +
 .../client/CloudControllerServiceClient.java    |   94 ++
 .../stratos/adc/mgt/client/RegistryClient.java  |  112 ++
 .../adc/mgt/custom/domain/RegistryManager.java  |  106 ++
 .../adc/mgt/dao/CartridgeSubscription.java      |  186 +++
 .../stratos/adc/mgt/dao/DataCartridge.java      |   49 +
 .../apache/stratos/adc/mgt/dao/PortMapping.java |   56 +
 .../apache/stratos/adc/mgt/dao/Repository.java  |   56 +
 .../adc/mgt/dao/RepositoryCredentials.java      |   27 +
 .../apache/stratos/adc/mgt/dns/DNSManager.java  |   86 ++
 .../org/apache/stratos/adc/mgt/dto/AppRepo.java |   85 ++
 .../apache/stratos/adc/mgt/dto/Cartridge.java   |  198 +++
 .../stratos/adc/mgt/dto/CartridgeDetail.java    |    1 +
 .../adc/mgt/dto/CartridgeInformation.java       |    1 +
 .../stratos/adc/mgt/dto/CartridgeWrapper.java   |   49 +
 .../org/apache/stratos/adc/mgt/dto/Policy.java  |  145 ++
 .../stratos/adc/mgt/dto/PolicyDefinition.java   |   80 +
 .../adc/mgt/dto/RepositoryInformation.java      |   43 +
 .../stratos/adc/mgt/dto/SubscriptionInfo.java   |   43 +
 .../stratos/adc/mgt/exception/ADCException.java |   46 +
 .../exception/AlreadySubscribedException.java   |   45 +
 .../exception/DomainMappingExistsException.java |   45 +
 .../DuplicateCartridgeAliasException.java       |   53 +
 .../InvalidCartridgeAliasException.java         |   54 +
 .../exception/InvalidRepositoryException.java   |   32 +
 .../mgt/exception/NotSubscribedException.java   |   46 +
 .../adc/mgt/exception/PolicyException.java      |   38 +
 .../RepositoryCredentialsRequiredException.java |   37 +
 .../exception/RepositoryRequiredException.java  |   37 +
 .../exception/RepositoryTransportException.java |   37 +
 .../UnregisteredCartridgeException.java         |   45 +
 .../internal/ADCManagementServerComponent.java  |  106 ++
 .../stratos/adc/mgt/internal/DataHolder.java    |   77 +
 .../adc/mgt/internal/HostingConstants.java      |   37 +
 .../internal/HostingManagementActivator.java    |   60 +
 .../service/ApplicationManagementService.java   |  620 ++++++++
 .../InstanceInformationManagementService.java   |   55 +
 .../mgt/service/RepoNotificationService.java    |  179 +++
 .../adc/mgt/service/RepositoryInfoBean.java     |   78 +
 .../service/RepositoryInformationService.java   |   66 +
 .../mgt/utils/ApplicationManagementUtil.java    | 1095 ++++++++++++++
 .../stratos/adc/mgt/utils/CartridgeAppType.java |   41 +
 .../mgt/utils/CartridgeConfigFileReader.java    |   59 +
 .../adc/mgt/utils/CartridgeConstants.java       |   74 +
 .../stratos/adc/mgt/utils/CartridgeDomain.java  |  143 ++
 .../stratos/adc/mgt/utils/DomainInfo.java       |   40 +
 .../adc/mgt/utils/PersistenceManager.java       |  853 +++++++++++
 .../stratos/adc/mgt/utils/PolicyHolder.java     |  289 ++++
 .../adc/mgt/utils/RepositoryCreator.java        |  266 ++++
 .../adc/mgt/utils/RepositoryFactory.java        |  129 ++
 .../stratos/adc/mgt/utils/StratosDBUtils.java   |  210 +++
 .../mgt/utils/SynchronizeRepositoryRequest.java |  143 ++
 .../src/main/resources/META-INF/services.xml    |   86 ++
 .../src/main/resources/policies.xsd             |   36 +
 .../src/scripts/append_zone_file.sh             |   24 +
 .../stratos/adc/mgt/test/PolicyHolderTest.java  |   63 +
 .../src/test/resources/log4j.properties         |    8 +
 .../src/test/resources/policies-1.xml           |   22 +
 .../2.1.3/pom.xml                               |  137 --
 .../topology/mgt/builder/TopologySyncher.java   |  114 --
 .../mgt/exception/TopologyMgtException.java     |   35 -
 .../mgt/group/mgt/GroupMgtAgentBuilder.java     |  109 --
 .../mgt/SubDomainAwareGroupManagementAgent.java |   32 -
 .../mgt/internal/TopologyMgtDSComponent.java    |  290 ----
 .../mgt/service/TopologyManagementService.java  |   69 -
 .../impl/TopologyManagementServiceImpl.java     |  127 --
 .../mgt/serviceobjects/DomainContext.java       |   90 --
 .../mgt/subscriber/TopicHealthChecker.java      |   67 -
 .../mgt/subscriber/TopologyListener.java        |   44 -
 .../mgt/subscriber/TopologySubscriber.java      |   92 --
 .../mgt/subscriber/TopologySubscriberTask.java  |    1 -
 .../adc/topology/mgt/util/ConfigHolder.java     |  197 ---
 .../topology/mgt/util/TopologyConstants.java    |   13 -
 .../adc/topology/mgt/util/TopologyMgtUtil.java  |    5 -
 .../src/main/resources/META-INF/services.xml    |    9 -
 .../org.apache.stratos.adc.topology.mgt/pom.xml |  135 ++
 .../topology/mgt/builder/TopologySyncher.java   |  114 ++
 .../mgt/exception/TopologyMgtException.java     |   35 +
 .../mgt/group/mgt/GroupMgtAgentBuilder.java     |  109 ++
 .../mgt/SubDomainAwareGroupManagementAgent.java |   32 +
 .../mgt/internal/TopologyMgtDSComponent.java    |  290 ++++
 .../mgt/service/TopologyManagementService.java  |   69 +
 .../impl/TopologyManagementServiceImpl.java     |  127 ++
 .../mgt/serviceobjects/DomainContext.java       |   90 ++
 .../mgt/subscriber/TopicHealthChecker.java      |   67 +
 .../mgt/subscriber/TopologyListener.java        |   44 +
 .../mgt/subscriber/TopologySubscriber.java      |   92 ++
 .../mgt/subscriber/TopologySubscriberTask.java  |    1 +
 .../adc/topology/mgt/util/ConfigHolder.java     |  197 +++
 .../topology/mgt/util/TopologyConstants.java    |   13 +
 .../adc/topology/mgt/util/TopologyMgtUtil.java  |    5 +
 .../src/main/resources/META-INF/services.xml    |    9 +
 .../pom.xml                                     |  208 +++
 .../autoscaler/service/IAutoscalerService.java  |  112 ++
 .../exception/AutoscalerServiceException.java   |   33 +
 .../exception/DeserializationException.java     |   33 +
 .../MalformedConfigurationFileException.java    |   33 +
 .../exception/NoInstanceFoundException.java     |   39 +
 .../exception/SerializationException.java       |   33 +
 .../service/impl/AutoscalerServiceImpl.java     | 1389 ++++++++++++++++++
 .../internal/AutoscalerServiceDSComponent.java  |   48 +
 .../autoscaler/service/io/Deserializer.java     |   68 +
 .../autoscaler/service/io/Serializer.java       |   61 +
 .../service/jcloud/ComputeServiceBuilder.java   |   65 +
 .../service/util/AutoscalerConstant.java        |   73 +
 .../autoscaler/service/util/IaasContext.java    |  391 +++++
 .../autoscaler/service/util/IaasProvider.java   |  141 ++
 .../service/util/InstanceContext.java           |   93 ++
 .../service/util/ServiceTemplate.java           |   84 ++
 .../xml/ElasticScalerConfigFileReader.java      |  557 +++++++
 .../src/main/resources/META-INF/services.xml    |    9 +
 .../service/util/IaasContextComparatorTest.java |   98 ++
 .../service/util/IaasContextTest.java           |  113 ++
 .../xml/ElasticScalerConfigFileReaderTest.java  |   60 +
 .../test/resources/elastic-scaler-config.xml    |   71 +
 .../2.1.3/pom.xml                               |  129 --
 .../cartridge/agent/ClusteringClient.java       |  270 ----
 .../cartridge/agent/ELBMembershipListener.java  |   83 --
 .../InstanceStateNotificationClientThread.java  |   63 -
 .../apache/stratos/cartridge/agent/Main.java    |  158 --
 .../agent/RegistrantMembershipListener.java     |   71 -
 .../exception/CartridgeAgentException.java      |   41 -
 .../agent/internal/CartridgeAgentConstants.java |   28 -
 .../CartridgeAgentServiceComponent.java         |  142 --
 .../cartridge/agent/internal/DataHolder.java    |   45 -
 .../cartridge/agent/registrant/PortMapping.java |   90 --
 .../cartridge/agent/registrant/Registrant.java  |  199 ---
 .../agent/registrant/RegistrantDatabase.java    |  143 --
 .../registrant/RegistrantHealthChecker.java     |  115 --
 .../agent/registrant/RegistrantUtil.java        |  177 ---
 .../agent/service/CartridgeAgentService.java    |   68 -
 .../src/main/resources/META-INF/services.xml    |   37 -
 .../org.apache.stratos.cartridge.agent/pom.xml  |  128 ++
 .../cartridge/agent/ClusteringClient.java       |  270 ++++
 .../cartridge/agent/ELBMembershipListener.java  |   83 ++
 .../InstanceStateNotificationClientThread.java  |   63 +
 .../apache/stratos/cartridge/agent/Main.java    |  158 ++
 .../agent/RegistrantMembershipListener.java     |   71 +
 .../exception/CartridgeAgentException.java      |   41 +
 .../agent/internal/CartridgeAgentConstants.java |   28 +
 .../CartridgeAgentServiceComponent.java         |  142 ++
 .../cartridge/agent/internal/DataHolder.java    |   45 +
 .../cartridge/agent/registrant/PortMapping.java |   90 ++
 .../cartridge/agent/registrant/Registrant.java  |  199 +++
 .../agent/registrant/RegistrantDatabase.java    |  143 ++
 .../registrant/RegistrantHealthChecker.java     |  115 ++
 .../agent/registrant/RegistrantUtil.java        |  177 +++
 .../agent/service/CartridgeAgentService.java    |   68 +
 .../src/main/resources/META-INF/services.xml    |   37 +
 .../2.1.1/pom.xml                               |   77 -
 .../cartridge/messages/ClusterDomain.java       |  117 --
 .../messages/ClusterDomainManager.java          |   35 -
 .../messages/CreateClusterDomainMessage.java    |  129 --
 .../CreateRemoveClusterDomainMessage.java       |   77 -
 .../pom.xml                                     |   76 +
 .../cartridge/messages/ClusterDomain.java       |  117 ++
 .../messages/ClusterDomainManager.java          |   35 +
 .../messages/CreateClusterDomainMessage.java    |  129 ++
 .../CreateRemoveClusterDomainMessage.java       |   77 +
 .../org.apache.stratos.cloud.controller/pom.xml |    3 +-
 .../org.apache.stratos.common/2.1.2/pom.xml     |   87 --
 .../stratos/common/TenantBillingService.java    |   42 -
 .../stratos/common/beans/TenantInfoBean.java    |  138 --
 .../common/config/CloudServiceConfig.java       |  166 ---
 .../common/config/CloudServiceConfigParser.java |   66 -
 .../common/config/CloudServicesDescConfig.java  |   61 -
 .../stratos/common/config/PermissionConfig.java |   71 -
 .../common/constants/StratosConstants.java      |  143 --
 .../common/constants/UsageConstants.java        |   58 -
 .../common/exception/StratosException.java      |   42 -
 .../internal/CloudCommonServiceComponent.java   |  139 --
 .../common/listeners/TenantMgtListener.java     |   43 -
 .../stratos/common/packages/PackageInfo.java    |  111 --
 .../common/packages/PackageInfoHolder.java      |  164 ---
 .../common/services/PackageInfoService.java     |   35 -
 .../stratos/common/util/ClaimsMgtUtil.java      |  278 ----
 .../stratos/common/util/CloudServicesUtil.java  |  200 ---
 .../apache/stratos/common/util/CommonUtil.java  |  623 --------
 .../util/MeteringAccessValidationUtils.java     |   53 -
 .../common/util/StratosConfiguration.java       |  319 ----
 .../src/main/resources/META-INF/services.xml    |   34 -
 .../src/main/resources/cloud-services-desc.xml  |  109 --
 .../apache/stratos/common/test/CommonTest.java  |   49 -
 components/org.apache.stratos.common/pom.xml    |   85 ++
 .../stratos/common/TenantBillingService.java    |   42 +
 .../stratos/common/beans/TenantInfoBean.java    |  138 ++
 .../common/config/CloudServiceConfig.java       |  166 +++
 .../common/config/CloudServiceConfigParser.java |   66 +
 .../common/config/CloudServicesDescConfig.java  |   61 +
 .../stratos/common/config/PermissionConfig.java |   71 +
 .../common/constants/StratosConstants.java      |  143 ++
 .../common/constants/UsageConstants.java        |   58 +
 .../common/exception/StratosException.java      |   42 +
 .../internal/CloudCommonServiceComponent.java   |  139 ++
 .../common/listeners/TenantMgtListener.java     |   43 +
 .../stratos/common/packages/PackageInfo.java    |  111 ++
 .../common/packages/PackageInfoHolder.java      |  164 +++
 .../common/services/PackageInfoService.java     |   35 +
 .../stratos/common/util/ClaimsMgtUtil.java      |  278 ++++
 .../stratos/common/util/CloudServicesUtil.java  |  200 +++
 .../apache/stratos/common/util/CommonUtil.java  |  623 ++++++++
 .../util/MeteringAccessValidationUtils.java     |   53 +
 .../common/util/StratosConfiguration.java       |  319 ++++
 .../src/main/resources/META-INF/services.xml    |   34 +
 .../src/main/resources/cloud-services-desc.xml  |  109 ++
 .../apache/stratos/common/test/CommonTest.java  |   49 +
 .../org.apache.stratos.deployment/2.1.0/pom.xml |  106 --
 .../deployment/CloudDeploymentInterceptor.java  |   91 --
 .../deployment/SuperTenantRolePlayer.java       |   45 -
 .../CloudDeploymentServiceComponent.java        |   73 -
 .../stratos/deployment/internal/DataHolder.java |   45 -
 .../org.apache.stratos.deployment/pom.xml       |  104 ++
 .../deployment/CloudDeploymentInterceptor.java  |   91 ++
 .../deployment/SuperTenantRolePlayer.java       |   45 +
 .../CloudDeploymentServiceComponent.java        |   73 +
 .../stratos/deployment/internal/DataHolder.java |   45 +
 .../2.1.0/pom.xml                               |  127 --
 .../stratos/keystore/mgt/KeyStoreGenerator.java |  229 ---
 .../keystore/mgt/KeyStoreMgtException.java      |   39 -
 .../keystore/mgt/KeystoreTenantMgtListener.java |   79 -
 .../internal/KeyStoreMgtServiceComponent.java   |   87 --
 .../keystore/mgt/util/RealmServiceHolder.java   |   33 -
 .../mgt/util/RegistryServiceHolder.java         |   33 -
 .../org.apache.stratos.keystore.mgt/pom.xml     |  125 ++
 .../stratos/keystore/mgt/KeyStoreGenerator.java |  229 +++
 .../keystore/mgt/KeyStoreMgtException.java      |   39 +
 .../keystore/mgt/KeystoreTenantMgtListener.java |   79 +
 .../internal/KeyStoreMgtServiceComponent.java   |   87 ++
 .../keystore/mgt/util/RealmServiceHolder.java   |   33 +
 .../mgt/util/RegistryServiceHolder.java         |   33 +
 .../org.apache.stratos.lb.common/4.1.3/pom.xml  |  120 --
 .../stratos/lb/common/cache/LRUCache.java       |  103 --
 .../lb/common/cache/URLMappingCache.java        |   47 -
 .../common/conf/LoadBalancerConfiguration.java  | 1206 ---------------
 .../LoadBalancerConfigurationDSComponent.java   |   51 -
 .../stratos/lb/common/conf/structure/Node.java  |  356 -----
 .../lb/common/conf/structure/NodeBuilder.java   |  140 --
 .../stratos/lb/common/conf/util/Constants.java  |   50 -
 .../lb/common/conf/util/HostContext.java        |  161 --
 .../conf/util/LoadBalancerConfigUtil.java       |  291 ----
 .../common/conf/util/TenantDomainContext.java   |   80 -
 .../mgt/SubDomainAwareGroupManagementAgent.java |   58 -
 .../RequestTokenReplicationCommand.java         |   73 -
 .../LoadBalancerConfigurationService.java       |   79 -
 .../LoadBalancerConfigurationServiceImpl.java   |   60 -
 .../stratos/lb/common/util/DomainMapping.java   |   40 -
 .../src/main/resources/META-INF/services.xml    |    9 -
 .../test/LoadBalancerConfigurationTest.java     |  169 ---
 .../stratos/lb/common/test/NodeBuilderTest.java |  124 --
 .../4.1.3/src/test/resources/loadbalancer.conf  |   64 -
 .../4.1.3/src/test/resources/loadbalancer1.conf |   39 -
 .../4.1.3/src/test/resources/loadbalancer2.conf |   30 -
 .../4.1.3/src/test/resources/testng.xml         |   15 -
 components/org.apache.stratos.lb.common/pom.xml |  118 ++
 .../stratos/lb/common/cache/LRUCache.java       |  103 ++
 .../lb/common/cache/URLMappingCache.java        |   47 +
 .../common/conf/LoadBalancerConfiguration.java  | 1206 +++++++++++++++
 .../LoadBalancerConfigurationDSComponent.java   |   51 +
 .../stratos/lb/common/conf/structure/Node.java  |  356 +++++
 .../lb/common/conf/structure/NodeBuilder.java   |  140 ++
 .../stratos/lb/common/conf/util/Constants.java  |   50 +
 .../lb/common/conf/util/HostContext.java        |  161 ++
 .../conf/util/LoadBalancerConfigUtil.java       |  291 ++++
 .../common/conf/util/TenantDomainContext.java   |   80 +
 .../mgt/SubDomainAwareGroupManagementAgent.java |   58 +
 .../RequestTokenReplicationCommand.java         |   73 +
 .../LoadBalancerConfigurationService.java       |   79 +
 .../LoadBalancerConfigurationServiceImpl.java   |   60 +
 .../stratos/lb/common/util/DomainMapping.java   |   40 +
 .../src/main/resources/META-INF/services.xml    |    9 +
 .../test/LoadBalancerConfigurationTest.java     |  169 +++
 .../stratos/lb/common/test/NodeBuilderTest.java |  124 ++
 .../src/test/resources/loadbalancer.conf        |   64 +
 .../src/test/resources/loadbalancer1.conf       |   39 +
 .../src/test/resources/loadbalancer2.conf       |   30 +
 .../src/test/resources/testng.xml               |   15 +
 .../org.apache.stratos.lb.endpoint/pom.xml      |  114 ++
 .../stratos/lb/endpoint/EndpointConstants.java  |   31 +
 .../stratos/lb/endpoint/EndpointDeployer.java   |   71 +
 ...TenantAwareLoadBalanceEndpointException.java |   39 +
 .../TenantLoadBalanceMembershipHandler.java     |  208 +++
 .../lb/endpoint/builder/TopologySyncher.java    |  159 ++
 .../manager/ClusterDomainManagerImpl.java       |  228 +++
 .../TenantAwareLoadBalanceEndpoint.java         |  531 +++++++
 .../group/mgt/GroupMgtAgentBuilder.java         |   80 +
 .../LoadBalanceEndpointServiceComponent.java    |  397 +++++
 .../lb/endpoint/internal/RegistryManager.java   |   54 +
 .../endpoint/subscriber/TopicHealthChecker.java |   68 +
 .../endpoint/subscriber/TopologyListener.java   |   47 +
 .../endpoint/subscriber/TopologySubscriber.java |   95 ++
 .../stratos/lb/endpoint/util/ConfigHolder.java  |  192 +++
 .../lb/endpoint/util/TopologyConstants.java     |   31 +
 .../2.1.0/pom.xml                               |   76 -
 .../balance/agent/LoadBalanceAgentService.java  |   55 -
 .../src/main/resources/META-INF/services.xml    |   29 -
 .../pom.xml                                     |   74 +
 .../balance/agent/LoadBalanceAgentService.java  |   55 +
 .../src/main/resources/META-INF/services.xml    |   29 +
 .../pom.xml                                     |  135 ++
 .../callables/AppNodeSanityCheckCallable.java   |   86 ++
 .../callables/AutoscaleDeciderCallable.java     |  241 +++
 .../callables/InstanceCountCallable.java        |   78 +
 .../callables/PendingInstanceCountCallable.java |   65 +
 .../callables/RunningInstanceCountCallable.java |   68 +
 .../clients/CloudControllerClient.java          |   66 +
 .../clients/CloudControllerOsgiClient.java      |   82 ++
 .../clients/CloudControllerStubClient.java      |   93 ++
 .../lbautoscale/context/AppDomainContext.java   |  170 +++
 .../context/LoadBalancerContext.java            |  104 ++
 .../AutoscalerTaskServiceComponent.java         |  325 ++++
 .../lbautoscale/internal/RegistryManager.java   |   54 +
 .../mediators/AutoscaleInMediator.java          |  174 +++
 .../mediators/AutoscaleOutMediator.java         |   78 +
 .../check/PendingInstancesStateChecker.java     |  148 ++
 .../check/TerminatingInstancesStateChecker.java |   89 ++
 .../task/AutoscalerTaskInitializer.java         |   50 +
 .../task/AutoscalerTaskMgmtAdminService.java    |  348 +++++
 .../lbautoscale/task/AutoscalingJob.java        |   68 +
 .../task/ServiceRequestsInFlightAutoscaler.java |  524 +++++++
 .../lbautoscale/task/TaskSchedulingManager.java |  188 +++
 .../lbautoscale/util/AutoscaleConstants.java    |   68 +
 .../lbautoscale/util/AutoscaleUtil.java         |  359 +++++
 .../util/AutoscalerTaskDSHolder.java            |  129 ++
 ...rg.apache.synapse.config.xml.MediatorFactory |    2 +
 ...apache.synapse.config.xml.MediatorSerializer |    2 +
 .../src/main/resources/synapse-load-average.xml |  138 ++
 .../resources/synapse-messages-in-flight.xml    |  135 ++
 .../synapse-service-messages-in-flight.xml      |  108 ++
 .../lbautoscale/AppDomainContextsTest.java      |  105 ++
 .../src/test/resources/loadbalancer.conf        |   50 +
 .../pom.xml                                     |  144 ++
 .../ui/clients/TenantActivityServiceClient.java |  155 ++
 .../TenantActivityUIServiceComponent.java       |   55 +
 .../ui/utils/ManagerConfigurations.java         |  147 ++
 .../activity/ui/utils/TenantMonitorUtil.java    |  143 ++
 .../src/main/resources/META-INF/component.xml   |   35 +
 .../activity/ui/i18n/JSResources.properties     |    1 +
 .../activity/ui/i18n/Resources.properties       |   11 +
 .../web/tenant-activity/css/tenant-usage.css    |   28 +
 .../tenant-activity/docs/images/view-usage.png  |  Bin 0 -> 44786 bytes
 .../web/tenant-activity/docs/userguide.html     |   76 +
 .../find-tenant-ajaxprocessor.jsp               |   59 +
 .../web/tenant-activity/find-tenant.jsp         |  110 ++
 .../tenant-activity/get-data-ajaxprocessor.jsp  |   66 +
 .../images/instance-usage-report.gif            |  Bin 0 -> 849 bytes
 .../web/tenant-activity/images/search.gif       |  Bin 0 -> 191 bytes
 .../images/tenant-usage-report.gif              |  Bin 0 -> 1008 bytes
 .../images/user-usage-report.gif                |  Bin 0 -> 1033 bytes
 .../web/tenant-activity/show-active-tenants.jsp |  129 ++
 .../web/tenant-activity/tenant-activity.jsp     |  174 +++
 .../org.apache.stratos.tenant.activity/pom.xml  |  144 ++
 .../activity/beans/PaginatedTenantDataBean.java |   52 +
 .../tenant/activity/beans/TenantDataBean.java   |   97 ++
 .../GetActiveTenantsInMemberRequest.java        |   59 +
 .../GetActiveTenantsInMemberResponse.java       |   54 +
 .../TenantActivityServiceComponent.java         |   96 ++
 .../services/TenantActivityService.java         |   83 ++
 .../activity/util/TenantActivityUtil.java       |   79 +
 .../stratos/tenant/activity/util/Util.java      |   82 ++
 .../src/main/resources/META-INF/component.xml   |   37 +
 .../src/main/resources/META-INF/services.xml    |   42 +
 .../2.1.0/pom.xml                               |   93 --
 .../dispatcher/MultitenantDispatcher.java       |   68 -
 .../TenantDispatcherServiceComponent.java       |  146 --
 .../pom.xml                                     |   92 ++
 .../dispatcher/MultitenantDispatcher.java       |   68 +
 .../TenantDispatcherServiceComponent.java       |  146 ++
 .../2.1.0/pom.xml                               |   82 --
 .../tenant/mgt/core/DefaultTenantPersistor.java |  340 -----
 .../internal/TenantMgtCoreServiceComponent.java |  129 --
 .../tenant/mgt/core/util/TenantCoreUtil.java    |   76 -
 .../org.apache.stratos.tenant.mgt.core/pom.xml  |   80 +
 .../tenant/mgt/core/DefaultTenantPersistor.java |  340 +++++
 .../internal/TenantMgtCoreServiceComponent.java |  129 ++
 .../tenant/mgt/core/util/TenantCoreUtil.java    |   76 +
 .../2.1.0/pom.xml                               |  103 --
 .../mgt/email/sender/internal/DataHolder.java   |  104 --
 .../TenantMgtEmailSenderServiceComponent.java   |  105 --
 .../sender/listener/EmailSenderListener.java    |   70 -
 .../sender/util/TenantMgtEmailSenderUtil.java   |  482 ------
 .../pom.xml                                     |  105 ++
 .../mgt/email/sender/internal/DataHolder.java   |  104 ++
 .../TenantMgtEmailSenderServiceComponent.java   |  106 ++
 .../sender/listener/EmailSenderListener.java    |   70 +
 .../sender/util/TenantMgtEmailSenderUtil.java   |  482 ++++++
 .../2.1.0/pom.xml                               |   59 +-
 .../ui/clients/PackageInfoServiceClient.java    |    4 +-
 .../org.apache.stratos.tenant.mgt/2.1.0/pom.xml |  125 --
 .../mgt/beans/PaginatedTenantInfoBean.java      |   52 -
 .../exception/TenantManagementException.java    |   33 -
 .../mgt/internal/TenantMgtServiceComponent.java |  261 ----
 .../mgt/internal/util/TenantMgtRampartUtil.java |   48 -
 .../mgt/realm/CloudWSRealmConfigBuilder.java    |  138 --
 .../mgt/realm/IdaasWSRealmConfigBuilder.java    |   87 --
 .../services/GAppTenantRegistrationService.java |  120 --
 .../InMemoryPasswordcallbackHandler.java        |   38 -
 .../mgt/services/TenantMgtAdminService.java     |  496 -------
 .../services/TenantSelfRegistrationService.java |  193 ---
 .../stratos/tenant/mgt/util/TenantMgtUtil.java  |  443 ------
 .../util/TenantRegistryDataDeletionUtil.java    |  119 --
 .../mgt/util/TenantUMDataDeletionUtil.java      |  112 --
 .../src/main/resources/META-INF/component.xml   |   41 -
 .../src/main/resources/META-INF/services.xml    |  155 --
 .../org.apache.stratos.tenant.mgt/pom.xml       |  123 ++
 .../mgt/beans/PaginatedTenantInfoBean.java      |   52 +
 .../exception/TenantManagementException.java    |   33 +
 .../mgt/internal/TenantMgtServiceComponent.java |  261 ++++
 .../mgt/internal/util/TenantMgtRampartUtil.java |   48 +
 .../mgt/realm/CloudWSRealmConfigBuilder.java    |  138 ++
 .../mgt/realm/IdaasWSRealmConfigBuilder.java    |   87 ++
 .../services/GAppTenantRegistrationService.java |  120 ++
 .../InMemoryPasswordcallbackHandler.java        |   38 +
 .../mgt/services/TenantMgtAdminService.java     |  496 +++++++
 .../services/TenantSelfRegistrationService.java |  193 +++
 .../stratos/tenant/mgt/util/TenantMgtUtil.java  |  443 ++++++
 .../util/TenantRegistryDataDeletionUtil.java    |  119 ++
 .../mgt/util/TenantUMDataDeletionUtil.java      |  112 ++
 .../src/main/resources/META-INF/component.xml   |   41 +
 .../src/main/resources/META-INF/services.xml    |  155 ++
 components/pom.xml                              |   46 +-
 .../pom.xml                                     |  142 --
 .../ui/clients/TenantActivityServiceClient.java |  155 --
 .../TenantActivityUIServiceComponent.java       |   55 -
 .../ui/utils/ManagerConfigurations.java         |  147 --
 .../activity/ui/utils/TenantMonitorUtil.java    |  143 --
 .../src/main/resources/META-INF/component.xml   |   35 -
 .../activity/ui/i18n/JSResources.properties     |    1 -
 .../activity/ui/i18n/Resources.properties       |   11 -
 .../web/tenant-activity/css/tenant-usage.css    |   28 -
 .../tenant-activity/docs/images/view-usage.png  |  Bin 44786 -> 0 bytes
 .../web/tenant-activity/docs/userguide.html     |   76 -
 .../find-tenant-ajaxprocessor.jsp               |   59 -
 .../web/tenant-activity/find-tenant.jsp         |  110 --
 .../tenant-activity/get-data-ajaxprocessor.jsp  |   66 -
 .../images/instance-usage-report.gif            |  Bin 849 -> 0 bytes
 .../web/tenant-activity/images/search.gif       |  Bin 191 -> 0 bytes
 .../images/tenant-usage-report.gif              |  Bin 1008 -> 0 bytes
 .../images/user-usage-report.gif                |  Bin 1033 -> 0 bytes
 .../web/tenant-activity/show-active-tenants.jsp |  129 --
 .../web/tenant-activity/tenant-activity.jsp     |  174 ---
 .../org.apache.stratos.tenant.activity/pom.xml  |  145 --
 .../activity/beans/PaginatedTenantDataBean.java |   52 -
 .../tenant/activity/beans/TenantDataBean.java   |   97 --
 .../GetActiveTenantsInMemberRequest.java        |   59 -
 .../GetActiveTenantsInMemberResponse.java       |   54 -
 .../TenantActivityServiceComponent.java         |   96 --
 .../services/TenantActivityService.java         |   83 --
 .../activity/util/TenantActivityUtil.java       |   79 -
 .../stratos/tenant/activity/util/Util.java      |   82 --
 .../src/main/resources/META-INF/component.xml   |   37 -
 .../src/main/resources/META-INF/services.xml    |   42 -
 components/tenant-activity/pom.xml              |   42 -
 pom.xml                                         |    1 +
 674 files changed, 39798 insertions(+), 39858 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/pom.xml b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/pom.xml
deleted file mode 100644
index 2bbb943..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/pom.xml
+++ /dev/null
@@ -1,210 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-     ~  Licensed to the Apache Software Foundation (ASF) under one
-     ~  or more contributor license agreements.  See the NOTICE file
-     ~  distributed with this work for additional information
-     ~  regarding copyright ownership.  The ASF licenses this file
-     ~  to you under the Apache License, Version 2.0 (the
-     ~  "License"); you may not use this file except in compliance
-     ~  with the License.  You may obtain a copy of the License at
-     ~
-     ~    http://www.apache.org/licenses/LICENSE-2.0
-     ~
-     ~  Unless required by applicable law or agreed to in writing,
-     ~  software distributed under the License is distributed on an
-     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-     ~  KIND, either express or implied.  See the License for the
-     ~  specific language governing permissions and limitations
-     ~  under the License.
-     ~
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <groupId>org.apache.stratos</groupId>
-    <artifactId>org.apache.stratos.autoscaler.service</artifactId>
-    <packaging>aar</packaging>
-    <name>Apache Stratos - Autoscaler Service</name>
-    <url>http://apache.org</url>
-
-    <build>
-        <plugins>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-shade-plugin</artifactId>
-                <version>1.7.1</version>
-                <executions>
-                    <execution>
-                        <phase>package</phase>
-                        <goals>
-                            <goal>shade</goal>
-                        </goals>
-                        <configuration>
-                            <artifactSet>
-                                <includes>
-                                    <include>org.jclouds:*</include>
-                                    <include>org.jclouds.*:*</include>
-                                </includes>
-                            </artifactSet>
-                            <filtering>true</filtering>
-                            <filters>
-                                <filter>
-                                    <artifact>org.jclouds*:*</artifact>
-                                    <includes>
-                                        <include>META-INF/services/org.jclouds.apis.ApiMetadata</include>
-                                        <include>META-INF/services/org.jclouds.providers.ProviderMetadata</include>
-                                    </includes>
-                                </filter>
-                            </filters>
-                            <transformers>
-                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer">
-                                </transformer>
-                            </transformers>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.axis2</groupId>
-                <artifactId>axis2-aar-maven-plugin</artifactId>
-                <version>1.4</version>
-                <extensions>true</extensions>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                <version>1.4.0</version>
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Export-Package>
-                            org.apache.stratos.autoscaler.service
-                        </Export-Package>
-                        <Private-Package>
-                            org.apache.stratos.autoscaler.service.*, !org.apache.stratos.autoscaler.service
-                        </Private-Package>
-                        <Import-Package>
-                        	  !org.apache.commons.logging,
-                            org.apache.commons.logging; version=0.0.0,
-                            org.wso2.carbon.utils.*,
-                            org.jclouds.compute*;version="${jclouds.version}";resolution:=optional,
-                            org.jclouds*;version="${jclouds.version}",
-                            *; resolution:=optional
-                        </Import-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.utils</artifactId>
-	    <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.stratos</groupId>
-            <artifactId>org.apache.stratos.lb.common</artifactId>
-            <version>4.1.3</version>
-            <!--version>${wso2carbon.version}</version-->
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.securevault</artifactId>
-            <version>4.1.0</version>
-            <!--version>${wso2carbon.version}</version-->
-        </dependency>
-        <!--dependency>
-            <groupId>org.apache.synapse</groupId>
-            <artifactId>synapse-core</artifactId>
-            <version>${synapse.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.synapse</groupId>
-            <artifactId>synapse-commons</artifactId>
-            <version>${synapse.version}</version>
-        </dependency--> 
-	
-        <!--  Jclouds dependencies -->
-         <dependency>
-           <groupId>org.jclouds</groupId>
-           <artifactId>jclouds-allcompute</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds</groupId>
-           <artifactId>jclouds-compute</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.driver</groupId>
-           <artifactId>jclouds-bouncycastle</artifactId>
-           <version>${jclouds.version}</version>
-           <exclusions>
-              <exclusion>
-                 <groupId>org.bouncycastle</groupId>
-                 <artifactId>bcprov-jdk16</artifactId>
-              </exclusion>
-           </exclusions>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.driver</groupId>
-           <artifactId>jclouds-sshj</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.driver</groupId>
-           <artifactId>jclouds-log4j</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.driver</groupId>
-           <artifactId>jclouds-enterprise</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <!--dependency>
-           <groupId>org.jclouds.api</groupId>
-           <artifactId>ec2</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.provider</groupId>
-           <artifactId>aws-ec2</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency>
-         <dependency>
-           <groupId>org.jclouds.api</groupId>
-           <artifactId>openstack-nova</artifactId>
-           <version>${jclouds.version}</version>
-         </dependency-->
-       
-    </dependencies>
-
-    <properties>
-        <jclouds.version>1.5.0-beta.5</jclouds.version>
-    </properties>
-
-</project>
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/IAutoscalerService.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/IAutoscalerService.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/IAutoscalerService.java
deleted file mode 100644
index 9bf06fc..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/IAutoscalerService.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service;
-
-import org.apache.stratos.lb.common.conf.util.Constants;
-
-/**
- * This Interface provides a way for a component, to communicate with an underline
- * Infrastructure which are supported by <i>JClouds</i>.
- * 
- */
-public interface IAutoscalerService {
-    
-    /**
-     * Initialize the service.
-     * @param isSpi if this service is to be used by SPI, this parameter should be set to
-     * true. When this is true, you should specify an image id, each time you
-     * are starting an instance i.e. you should use {@link #startSpiInstance(String, String)}
-     * method, instead of using {@link #startInstance(String)}.
-     * @return
-     */
-    public boolean initAutoscaler(boolean isSpi);
-
-    
-    /**
-     * Calling this method will result in an instance startup, which is belong
-     * to the provided service domain. This method is non-blocking, means we do not
-     * wait till the instance is started up. Also note that the instance that is starting up
-     * belongs to the group whose name is derived from its service domain, replacing <i>.</i>
-     * by a hyphen (<i>-</i>). 
-     * @param domainName service clustering domain of the instance to be started up.
-     * @param sudDomainName service clustering sub domain of the instance to be started up.
-     * If this is null, the default value will be used. Default value is 
-     * {@link Constants}.DEFAULT_SUB_DOMAIN.
-     * @return whether the starting up is successful or not.
-     */
-    public boolean startInstance(String domainName, String sudDomainName);
-    
-    /**
-     * Calling this method will result in an instance startup, which is belong
-     * to the provided service domain. This method will return the public IP address of
-     * the instance that is started. Thus, this method is blocking, since we need to 
-     * return the IP Address and for that we have to wait till the instance started up.
-     * @param domainName should be in following format.
-     * <code>${service-domain}\t\${tenant-id}</code>.
-     * @param imageId starting instance will be an instance of this image. Image id should
-     * be a valid one.
-     * @param sudDomainName service clustering sub domain of the instance to be started up.
-     * If this is null, the default value will be used. Default value is 
-     * {@link Constants}.DEFAULT_SUB_DOMAIN.
-     * @return public IP address of the instance in String format. If instance failed to 
-     * start, this will return an empty String.
-     */
-    public String startSpiInstance(String domainName, String subDomainName, String imageId);
-    
-   
-    /**
-     * Calling this method will result in termination of an instance which is belong
-     * to the provided service domain.
-     * @param domainName service domain of the instance to be terminated.
-     * @param sudDomainName service clustering sub domain of the instance to be started up.
-     * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
-     * @return whether an instance terminated successfully or not.
-     */
-	public boolean terminateInstance(String domainName, String subDomainName);
-	
-	/**
-	 * Calling this method will result in termination of the lastly spawned instance which is
-	 * belong to the provided service domain.
-	 * @param domainName service domain of the instance to be terminated.
-	 * @param sudDomainName service clustering sub domain of the instance to be started up.
-     * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
-	 * @return whether the termination is successful or not.
-	 */
-	public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName);
-	
-	/**
-     * Calling this method will result in termination of an instance which has the
-     * provided public IP address.
-     * @param publicIp public IP address of the instance to be terminated.
-     * @return whether the instance terminated successfully or not.
-     */
-    public boolean terminateSpiInstance(String publicIp);
-	
-	/**
-	 * Calling this method will result in returning the pending instances
-	 * count of a particular domain.
-	 * @param domainName service domain
-	 * @param sudDomainName service clustering sub domain of the instance to be started up.
-     * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
-	 * @return number of pending instances for this domain. If no instances of this 
-	 * domain is present, this will return zero.
-	 */
-	public int getPendingInstanceCount(String domainName, String subDomainName);
-	
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/AutoscalerServiceException.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/AutoscalerServiceException.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/AutoscalerServiceException.java
deleted file mode 100644
index 70e82c8..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/AutoscalerServiceException.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.exception;
-
-public class AutoscalerServiceException extends RuntimeException {
-    
-    private static final long serialVersionUID = -6326227079367867222L;
-
-    public AutoscalerServiceException(String msg) {
-        super(msg);
-    }
-    
-    public AutoscalerServiceException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/DeserializationException.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/DeserializationException.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/DeserializationException.java
deleted file mode 100644
index 01819d1..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/DeserializationException.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.exception;
-
-public class DeserializationException extends RuntimeException {
-    
-    private static final long serialVersionUID = -2426068347954381831L;
-
-    public DeserializationException(String msg) {
-        super(msg);
-    }
-    
-    public DeserializationException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/MalformedConfigurationFileException.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/MalformedConfigurationFileException.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/MalformedConfigurationFileException.java
deleted file mode 100644
index 090e931..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/MalformedConfigurationFileException.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.exception;
-
-public class MalformedConfigurationFileException extends RuntimeException {
-
-    private static final long serialVersionUID = -1662095377704279326L;
-    
-    public MalformedConfigurationFileException(String msg) {
-        super(msg);
-    }
-    
-    public MalformedConfigurationFileException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/NoInstanceFoundException.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/NoInstanceFoundException.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/NoInstanceFoundException.java
deleted file mode 100644
index be9356f..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/NoInstanceFoundException.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.exception;
-
-/**
- * This will throw when no instance is found
- */
-public class NoInstanceFoundException extends Exception {
-
-    /**
-     * For serializing requirement
-     */
-    private static final long serialVersionUID = -435060299292679892L;
-
-
-    public NoInstanceFoundException(String msg) {
-        super(msg);
-    }
-    
-    public NoInstanceFoundException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/SerializationException.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/SerializationException.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/SerializationException.java
deleted file mode 100644
index 0ccbd61..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/exception/SerializationException.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.exception;
-
-public class SerializationException extends RuntimeException {
-    
-    private static final long serialVersionUID = -3701458642228072331L;
-
-    public SerializationException(String msg) {
-        super(msg);
-    }
-    
-    public SerializationException(String msg, Exception ex) {
-        super(msg, ex);
-    }
-
-}


[25/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/builder/TopologySyncher.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/builder/TopologySyncher.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/builder/TopologySyncher.java
deleted file mode 100644
index 71acee0..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/builder/TopologySyncher.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * WSO2 Inc. licenses this file to you under the Apache License,
- * Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.adc.topology.mgt.builder;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.topology.mgt.group.mgt.GroupMgtAgentBuilder;
-import org.apache.stratos.adc.topology.mgt.util.ConfigHolder;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.apache.stratos.lb.common.conf.structure.Node;
-import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
-
-
-public class TopologySyncher implements Runnable {
-
-	@SuppressWarnings("rawtypes")
-    private BlockingQueue sharedQueue;
-	private static final Log log = LogFactory.getLog(TopologySyncher.class);
-	
-	public TopologySyncher(@SuppressWarnings("rawtypes") BlockingQueue queue){
-		
-		sharedQueue = queue;
-		
-	}
-	
-	public void run() {
-
-	    LoadBalancerConfiguration lbconfig = LoadBalancerConfiguration.getInstance();
-	    
-	    //FIXME Currently there has to be at least one dummy cluster defined in the loadbalancer conf
-	    // in order to proper initialization of TribesClusteringAgent.
-	    generateGroupMgtAgents(lbconfig);
-	    
-        while (true) {
-            try {
-
-                Object obj;
-                String msg = null;
-
-                obj = sharedQueue.take();
-                msg = (String) obj;
-
-                ConfigHolder data = ConfigHolder.getInstance();
-
-                Node topologyNode = NodeBuilder.buildNode(msg);
-
-                List<ServiceConfiguration> currentServiceConfigs = lbconfig.createServicesConfig(topologyNode);
-
-                data.setServiceConfigs(lbconfig.getServiceNameToServiceConfigurations());
-                generateGroupMgtAgents(lbconfig);
-                resetGroupMgtAgents(lbconfig, currentServiceConfigs);
-
-            } catch (InterruptedException ignore) {
-            }
-        }
-
-	}
-
-    /**
-     * @param lbconfig
-     */
-    private void generateGroupMgtAgents(LoadBalancerConfiguration lbconfig) {
-        for (List<ServiceConfiguration> serviceConfigsList : lbconfig.getServiceNameToServiceConfigurations()
-                                                                     .values()) {
-
-        	for (ServiceConfiguration serviceConfiguration : serviceConfigsList) {
-        		GroupMgtAgentBuilder.createGroupMgtAgent(serviceConfiguration.getDomain(),
-        		                                         serviceConfiguration.getSubDomain());
-        	}
-        }
-    }
-    
-    private void resetGroupMgtAgents(LoadBalancerConfiguration lbConfig,
-        List<ServiceConfiguration> currentServiceConfigs) {
-
-        for (Iterator<?> iterator = lbConfig.getServiceConfigurations().values().iterator(); iterator.hasNext();) {
-            @SuppressWarnings("unchecked")
-            Map<String, ServiceConfiguration> valuesMap = (Map<String, ServiceConfiguration>) iterator.next();
-
-            for (Iterator<ServiceConfiguration> iterator2 = valuesMap.values().iterator(); iterator2.hasNext();) {
-                ServiceConfiguration oldServiceConfig = (ServiceConfiguration) iterator2.next();
-
-                if (!currentServiceConfigs.contains(oldServiceConfig)) {
-                    // if the ServiceConfiguration is not there any more in the latest topology
-                    lbConfig.removeServiceConfiguration(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
-                    GroupMgtAgentBuilder.resetGroupMgtAgent(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
-                }
-            }
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/exception/TopologyMgtException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/exception/TopologyMgtException.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/exception/TopologyMgtException.java
deleted file mode 100644
index 51faeb8..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/exception/TopologyMgtException.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.topology.mgt.exception;
-
-public class TopologyMgtException extends RuntimeException {
-
-    private static final long serialVersionUID = -663839410798538370L;
-
-    public TopologyMgtException(String msg) {
-        super(msg);
-    }
-
-    public TopologyMgtException(String msg, Throwable cause) {
-        super(msg, cause);
-    }
-
-    public TopologyMgtException(Throwable cause) {
-        super(cause);
-    }
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java
deleted file mode 100644
index 1ef804f..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * WSO2 Inc. licenses this file to you under the Apache License,
- * Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.adc.topology.mgt.group.mgt;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.topology.mgt.util.ConfigHolder;
-import org.apache.synapse.SynapseException;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.util.HostContext;
-import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
-
-public class GroupMgtAgentBuilder {
-
-	private static LoadBalancerConfiguration lbConfig;
-	/**
-     * Key - host name 
-     * Value - {@link HostContext}
-     */
-    private static Map<String, HostContext> hostContexts = new HashMap<String, HostContext>();
-    
-    private static final Log log = LogFactory.getLog(GroupMgtAgentBuilder.class);
-	
-	public static void createGroupMgtAgents() {
-		lbConfig = ConfigHolder.getInstance().getLbConfig();
-		hostContexts = lbConfig.getHostContextMap();
-		
-		ClusteringAgent clusteringAgent = ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
-        if (clusteringAgent == null) {
-            throw new SynapseException("Axis2 ClusteringAgent not defined in axis2.xml");
-        }
-
-        // Add the Axis2 GroupManagement agents
-        if (hostContexts != null) {
-            // iterate through each host context
-            for (HostContext hostCtxt : hostContexts.values()) {
-                // each host can has multiple Tenant Contexts, iterate through them
-                for (TenantDomainContext tenantCtxt : hostCtxt.getTenantDomainContexts()) {
-
-                    String domain = tenantCtxt.getDomain();
-                    String subDomain = tenantCtxt.getSubDomain();
-
-                    if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
-                        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
-                            subDomain),
-                            domain, subDomain, -1);
-                        log.info("Group management agent added to cluster domain: " +
-                            domain + " and sub domain: " + subDomain);
-                    }
-                }
-            }
-        }
-    }
-	
-	public static void createGroupMgtAgent(String domain, String subDomain) {
-		
-		ClusteringAgent clusteringAgent = ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
-        if (clusteringAgent == null) {
-            throw new SynapseException("Axis2 ClusteringAgent not defined in axis2.xml");
-        }
-		
-        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
-            clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
-                subDomain),
-                domain, subDomain, -1);
-            log.info("Group management agent added to cluster domain: " +
-                domain + " and sub domain: " + subDomain);
-        }
-	}
-	
-	public static void resetGroupMgtAgent(String domain, String subDomain) {
-
-        ClusteringAgent clusteringAgent =
-            ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
-        
-        if (clusteringAgent == null) {
-            throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
-        }
-
-        // checks the existence. 
-        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) != null) {
-            
-            clusteringAgent.resetGroupManagementAgent(domain, subDomain);
-            
-            log.info("Group management agent of cluster domain: " +
-                domain + " and sub domain: " + subDomain+" is removed.");
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java
deleted file mode 100644
index d674c4c..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package org.apache.stratos.adc.topology.mgt.group.mgt;
-
-import org.apache.axis2.clustering.Member;
-import org.apache.axis2.clustering.management.DefaultGroupManagementAgent;
-
-/**
- * This GroupManagementAgent can handle group membership based on cluster sub-domains
- */
-public class SubDomainAwareGroupManagementAgent extends DefaultGroupManagementAgent {
-
-    private String subDomain;
-
-    public SubDomainAwareGroupManagementAgent(String subDomain) {
-        this.subDomain = subDomain;
-    }
-
-    @Override
-    public void applicationMemberAdded(Member member) {
-        String subDomain = member.getProperties().getProperty("subDomain");
-        if (subDomain == null || subDomain.equals(this.subDomain)) {
-            super.applicationMemberAdded(member);
-        }
-    }
-
-    @Override
-    public void applicationMemberRemoved(Member member) {
-        String subDomain = member.getProperties().getProperty("subDomain");
-        if (subDomain == null || subDomain.equals(this.subDomain)) {
-            super.applicationMemberRemoved(member);
-        }
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/internal/TopologyMgtDSComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/internal/TopologyMgtDSComponent.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/internal/TopologyMgtDSComponent.java
deleted file mode 100644
index 2500485..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/internal/TopologyMgtDSComponent.java
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- */
-
-package org.apache.stratos.adc.topology.mgt.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.topology.mgt.builder.TopologySyncher;
-import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
-import org.apache.stratos.adc.topology.mgt.service.impl.TopologyManagementServiceImpl;
-import org.apache.stratos.adc.topology.mgt.subscriber.TopologySubscriber;
-import org.apache.stratos.adc.topology.mgt.util.ConfigHolder;
-import org.apache.stratos.adc.topology.mgt.util.TopologyConstants;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.utils.ConfigurationContextService;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
-import org.wso2.carbon.ntask.core.service.TaskService;
-
-//* @scr.reference name="synapse.config.service"
-//* interface="org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService"
-//* cardinality="1..1" policy="dynamic" bind="setSynapseConfigurationService"
-//* unbind="unsetSynapseConfigurationService"
-//* @scr.reference name="registry.service"
-//* interface="org.wso2.carbon.registry.core.service.RegistryService"
-//* cardinality="1..1" policy="dynamic"
-//* bind="setRegistryService" unbind="unsetRegistryService"
-//* @scr.reference name="dependency.mgt.service"
-//* interface="org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService"
-//* cardinality="0..1" policy="dynamic"
-//* bind="setDependencyManager" unbind="unsetDependencyManager"
-//* @scr.reference name="user.realmservice.default"
-//* interface="org.wso2.carbon.user.core.service.RealmService"
-//* cardinality="1..1" policy="dynamic" bind="setRealmService"
-//* unbind="unsetRealmService"
-
-/**
- * @scr.component name="topology.mgt.service" immediate="true"
- * @scr.reference name="configuration.context.service"
- * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
- * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
- * @scr.reference name="org.apache.stratos.lb.common"
- * interface="org.apache.stratos.lb.common.service.LoadBalancerConfigurationService"
- * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
- * unbind="unsetLoadBalancerConfigurationService"
- * @scr.reference name="ntask.component" interface="org.wso2.carbon.ntask.core.service.TaskService"
- * cardinality="1..1" policy="dynamic" bind="setTaskService" unbind="unsetTaskService"
- */
-@SuppressWarnings({"UnusedDeclaration", "JavaDoc"})
-public class TopologyMgtDSComponent {
-
-    private static final Log log = LogFactory.getLog(TopologyMgtDSComponent.class);
-
-//    private boolean activated = false;
-
-    protected void activate(ComponentContext ctxt) {
-    	try {
-    		// start consumer
-    		// initialize TopologyBuilder Consumer
-            if (System.getProperty("mb.server.ip") != null) {
-                Thread topologyConsumer = new Thread(new TopologySyncher(ConfigHolder.getInstance().getSharedTopologyDiffQueue()));
-                // start consumer
-                topologyConsumer.start();
-
-                TopologySubscriber.subscribe(TopologyConstants.TOPIC_NAME);
-            }
-
-    		
-            BundleContext bundleContext = ctxt.getBundleContext();
-            bundleContext.registerService(TopologyManagementService.class.getName(),
-                                          new TopologyManagementServiceImpl(), null);
-
-            log.debug("******* Topology Mgt Service bundle is activated ******* ");
-        } catch (Throwable e) {
-            log.error("******* Topology Mgt Service Service bundle is failed to activate ****", e);
-        }
-//    	log.info("**************************************");
-//    	for (String str : ConfigHolder.getInstance().getLbConfig().getServiceDomains()) {
-//	        log.info(str);
-//        }
-//    	log.info("**************************************");
-    	
-//    	if(!activated){
-//    		GroupMgtAgentBuilder.createGroupMgtAgents();
-//    		activated = true;
-//    	}
-    	
-    	
-    	// topology synching task activation
-//    	TaskManager tm = null;
-//		try {
-//			// topology sync
-//			ConfigHolder.getInstance().getTaskService()
-//			          .registerTaskType(TopologyConstants.TOPOLOGY_SYNC_TASK_TYPE);
-//
-//			tm =
-//					ConfigHolder.getInstance().getTaskService()
-//			               .getTaskManager(TopologyConstants.TOPOLOGY_SYNC_TASK_TYPE);
-//
-//			TriggerInfo triggerInfo = new TriggerInfo(TopologyConstants.TOPOLOGY_SYNC_CRON);
-//			TaskInfo taskInfo =
-//			                    new TaskInfo(TopologyConstants.TOPOLOGY_SYNC_TASK_NAME,
-//			                                 TopologySubscriberTask.class.getName(),
-//			                                 new HashMap<String, String>(), triggerInfo);
-//			tm.registerTask(taskInfo);
-//
-//			// start consumer
-//			// initialize TopologyBuilder Consumer
-//	        Thread topologyConsumer = new Thread(new TopologyBuilder(ConfigHolder.getInstance().getSharedTopologyDiffQueue()));
-//	        // start consumer
-//	        topologyConsumer.start();
-//			
-//		} catch (Exception e) {
-//			String msg = "Error scheduling task: " + TopologyConstants.TOPOLOGY_SYNC_TASK_NAME;
-//			log.error(msg, e);
-//			if (tm != null) {
-//				try {
-//					tm.deleteTask(TopologyConstants.TOPOLOGY_SYNC_TASK_NAME);
-//				} catch (TaskException e1) {
-//					log.error(e1);
-//				}
-//			}
-//			throw new TopologyMgtException(msg, e);
-//		}
-    }
-
-    protected void deactivate(ComponentContext context) {}
-
-    protected void setConfigurationContextService(ConfigurationContextService cfgCtxService) {
-        ConfigHolder.getInstance().setAxisConfiguration(
-                cfgCtxService.getServerConfigContext().getAxisConfiguration());
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService cfgCtxService) {
-        ConfigHolder.getInstance().setAxisConfiguration(null);
-    }
-
-//    protected void setSynapseConfigurationService(
-//            SynapseConfigurationService synapseConfigurationService) {
-//
-//        ConfigHolder.getInstance().setSynapseConfiguration(
-//                synapseConfigurationService.getSynapseConfiguration());
-//    }
-//
-//    protected void unsetSynapseConfigurationService(
-//            SynapseConfigurationService synapseConfigurationService) {
-//
-//        ConfigHolder.getInstance().setSynapseConfiguration(null);
-//    }
-
-    /**
-     * Here we receive an event about the creation of a SynapseEnvironment. If this is
-     * SuperTenant we have to wait until all the other constraints are met and actual
-     * initialization is done in the activate method. Otherwise we have to do the activation here.
-     *
-     * @param synapseEnvironmentService SynapseEnvironmentService which contains information
-     *                                  about the new Synapse Instance
-     */
-//    protected void setSynapseEnvironmentService(
-//            SynapseEnvironmentService synapseEnvironmentService) {
-//        boolean alreadyCreated = ConfigHolder.getInstance().getSynapseEnvironmentServices().
-//                containsKey(synapseEnvironmentService.getTenantId());
-//
-//        ConfigHolder.getInstance().addSynapseEnvironmentService(
-//                synapseEnvironmentService.getTenantId(),
-//                synapseEnvironmentService);
-//        if (activated) {
-//            if (!alreadyCreated) {
-//                try {
-//                    registerDeployer(synapseEnvironmentService.getConfigurationContext().getAxisConfiguration(),
-//                            synapseEnvironmentService.getSynapseEnvironment());
-//                    if (log.isDebugEnabled()) {
-//                        log.debug("Endpoint Admin bundle is activated ");
-//                    }
-//                } catch (Throwable e) {
-//                    log.error("Failed to activate Endpoint Admin bundle ", e);
-//                }
-//            }
-//        }
-//    }
-
-//    /**
-//     * Here we receive an event about Destroying a SynapseEnvironment. This can be the super tenant
-//     * destruction or a tenant destruction.
-//     *
-//     * @param synapseEnvironmentService synapseEnvironment
-//     */
-//    protected void unsetSynapseEnvironmentService(
-//            SynapseEnvironmentService synapseEnvironmentService) {
-//        ConfigHolder.getInstance().removeSynapseEnvironmentService(
-//                synapseEnvironmentService.getTenantId());
-//    }
-//
-//    protected void setRegistryService(RegistryService regService) {
-//        if (log.isDebugEnabled()) {
-//            log.debug("RegistryService bound to the endpoint component");
-//        }
-//        try {
-//            ConfigHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
-//            ConfigHolder.getInstance().setGovernanceRegistry(regService.getGovernanceSystemRegistry());
-//        } catch (RegistryException e) {
-//            log.error("Couldn't retrieve the registry from the registry service");
-//        }
-//    }
-//
-//    protected void unsetRegistryService(RegistryService regService) {
-//        if (log.isDebugEnabled()) {
-//            log.debug("RegistryService unbound from the endpoint component");
-//        }
-//        ConfigHolder.getInstance().setConfigRegistry(null);
-//    }
-//
-//    protected void setDependencyManager(DependencyManagementService dependencyMgr) {
-//        if (log.isDebugEnabled()) {
-//            log.debug("Dependency management service bound to the endpoint component");
-//        }
-//        ConfigHolder.getInstance().setDependencyManager(dependencyMgr);
-//    }
-//
-//    protected void unsetDependencyManager(DependencyManagementService dependencyMgr) {
-//        if (log.isDebugEnabled()) {
-//            log.debug("Dependency management service unbound from the endpoint component");
-//        }
-//        ConfigHolder.getInstance().setDependencyManager(null);
-//    }
-//
-//    protected void setSynapseRegistrationsService(
-//            SynapseRegistrationsService synapseRegistrationsService) {
-//
-//    }
-
-//    protected void unsetSynapseRegistrationsService(
-//            SynapseRegistrationsService synapseRegistrationsService) {
-//        int tenantId = synapseRegistrationsService.getTenantId();
-//        if (ConfigHolder.getInstance().getSynapseEnvironmentServices().containsKey(tenantId)) {
-//            SynapseEnvironment env = ConfigHolder.getInstance().
-//                    getSynapseEnvironmentService(tenantId).getSynapseEnvironment();
-//
-//            ConfigHolder.getInstance().removeSynapseEnvironmentService(
-//                    synapseRegistrationsService.getTenantId());
-//
-//            AxisConfiguration axisConfig = synapseRegistrationsService.getConfigurationContext().
-//                    getAxisConfiguration();
-//            if (axisConfig != null) {
-//                try {
-//                    unregisterDeployer(axisConfig, env);
-//                } catch (Exception e) {
-//                    log.warn("Couldn't remove the EndpointDeployer");
-//                }
-//            }
-//        }
-//    }
-
-//    protected void setRealmService(RealmService realmService) {
-//        ConfigHolder.getInstance().setRealmService(realmService);
-//    }
-//
-//    protected void unsetRealmService(RealmService realmService) {
-//        ConfigHolder.getInstance().setRealmService(null);
-//    }
-//    
-    protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
-        ConfigHolder.getInstance().setLbConfigService(lbConfigSer);
-    }
-    
-    protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
-        ConfigHolder.getInstance().setLbConfigService(null);
-    }
-    
-    protected void setTaskService(TaskService taskService) {
-        ConfigHolder.getInstance().setTaskService(taskService);
-    }
-
-    protected void unsetTaskService(TaskService taskService) {
-        ConfigHolder.getInstance().setTaskService(null);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/service/TopologyManagementService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/service/TopologyManagementService.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/service/TopologyManagementService.java
deleted file mode 100644
index 9b490e9..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/service/TopologyManagementService.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- */
-
-package org.apache.stratos.adc.topology.mgt.service;
-
-import org.apache.stratos.adc.topology.mgt.serviceobjects.DomainContext;
-
-/**
- * This exposes details regarding up-to-date topology
- *
- */
-public interface TopologyManagementService {
-
-	/**
-	 * Provide service cluster domains corresponds to the given information.
-	 * @param cartridgeType cartridge type
-	 * @param tenantId tenant id
-	 * @return String array of service cluster domains
-	 */
-	String[] getDomains(String cartridgeType, int tenantId);
-
-	/**
-	 * Provide service cluster sub domains corresponds to the given information.
-	 * @param cartridgeType cartridge type
-	 * @param tenantId tenant id
-	 * @return String array of service cluster sub domains
-	 */
-	String[] getSubDomains(String cartridgeType, int tenantId);
-
-//	/**
-//	 * Provide public IPs corresponds to the given information.
-//	 * @param cartridgeType cartridge type
-//	 * @param tenantId tenant id
-//	 * @return String array of public IPs
-//	 */
-//	String[] getActiveIPs(String cartridgeType, int tenantId);
-	
-	/**
-	 * Provide public IPs corresponds to the given information.
-	 * @param cartridgeType cartridge type
-	 * @param domain service cluster domain
-	 * @param subDomain service cluster sub domain
-	 * @return String array of public IPs
-	 */
-	String[] getActiveIPs(String cartridgeType, String domain, String subDomain);
-	
-	/**
-	 * Provide domains and the relevant subdomains corresponding to the given information
-	 * 
-	 * @param cartridgeType cartridge type
-	 * @param tenantId tenant id
-	 * @return DomainContext instances array of domains and sub domains 
-	 */
-	DomainContext[] getDomainsAndSubdomains (String cartridgeType, int tenantId);
-	
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java
deleted file mode 100644
index 9b976cf..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- */
-
-package org.apache.stratos.adc.topology.mgt.service.impl;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
-import org.apache.stratos.adc.topology.mgt.serviceobjects.DomainContext;
-import org.apache.stratos.adc.topology.mgt.util.ConfigHolder;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.apache.stratos.lb.common.conf.util.LoadBalancerConfigUtil;
-
-public class TopologyManagementServiceImpl implements TopologyManagementService {
-	
-	ConfigHolder data = ConfigHolder.getInstance();
-
-	public String[] getDomains(String cartridgeType, int tenantId) {
-		List<String> domains = new ArrayList<String>();
-		if(data.getServiceConfigs() != null){
-			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
-			if(serviceConfigs != null){
-				
-				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
-	                
-					List<Integer> tenantIds = LoadBalancerConfigUtil.getTenantIds(serviceConfiguration.getTenantRange());
-					if(!tenantIds.isEmpty() && (tenantIds.contains(tenantId) || tenantIds.contains(0))){
-						if (!domains.contains(serviceConfiguration.getDomain())) {
-							domains.add(serviceConfiguration.getDomain());
-						}
-					}
-                }
-			}
-		}
-		return domains.toArray(new String[domains.size()]);
-	}
-
-	public String[] getSubDomains(String cartridgeType, int tenantId) {
-		List<String> subDomains = new ArrayList<String>();
-		if(data.getServiceConfigs() != null){
-			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
-			if(serviceConfigs != null){
-				
-				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
-	                
-					List<Integer> tenantIds = LoadBalancerConfigUtil.getTenantIds(serviceConfiguration.getTenantRange());
-					if(!tenantIds.isEmpty() && (tenantIds.contains(tenantId) || tenantIds.contains(0))){
-						if (!subDomains.contains(serviceConfiguration.getSubDomain())) {
-							subDomains.add(serviceConfiguration.getSubDomain());
-						}
-					}
-                }
-			}
-		}
-		return subDomains.toArray(new String[subDomains.size()]);
-	}
-
-    public String[] getActiveIPs(String cartridgeType, String domain, String subDomain) {
-		List<String> publicIps = new ArrayList<String>();
-		
-		if(domain == null || subDomain == null){
-			return new String[0];
-		}
-		
-		if(data.getServiceConfigs() != null){
-			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
-			if(serviceConfigs != null){
-				
-				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
-	                
-					if(domain.equals(serviceConfiguration.getDomain()) && subDomain.equals(serviceConfiguration.getSubDomain())){
-						
-						String ipStr = serviceConfiguration.getPublicIp();
-						if(ipStr != null && !ipStr.isEmpty()){
-							for (String ip : ipStr.split(",")) {
-								if (!publicIps.contains(ip)) {
-									publicIps.add(ip);
-								}
-							}
-						}
-					}
-                }
-			}
-		}
-		return publicIps.toArray(new String[publicIps.size()]);
-	}
-
-	/* (non-Javadoc)
-	 * @see org.wso2.carbon.stratos.topology.mgt.service.TopologyManagementService#getDomainsAndSubdomains(java.lang.String, int)
-	 */
-	public DomainContext[] getDomainsAndSubdomains(String cartridgeType, int tenantId) {
-		List<DomainContext> domainContexts = new ArrayList<DomainContext>();
-		
-		if(data.getServiceConfigs() != null){
-			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
-			if(serviceConfigs != null){
-				
-				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
-	                
-					List<Integer> tenantIds = LoadBalancerConfigUtil.getTenantIds(serviceConfiguration.getTenantRange());
-					if(!tenantIds.isEmpty() && (tenantIds.contains(tenantId) || tenantIds.contains(0))){
-						DomainContext domainCtx = new DomainContext(serviceConfiguration.getDomain(), serviceConfiguration.getSubDomain());
-						if (!domainContexts.contains(domainCtx)) {
-							domainContexts.add(domainCtx);
-						}
-					}
-                }
-			}
-		}
-		return domainContexts.toArray(new DomainContext[domainContexts.size()]);
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/serviceobjects/DomainContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/serviceobjects/DomainContext.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/serviceobjects/DomainContext.java
deleted file mode 100644
index 54357d2..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/serviceobjects/DomainContext.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- */
-package org.apache.stratos.adc.topology.mgt.serviceobjects;
-
-/**
- * Class to hold domain and subdomain details
- *
- */
-public class DomainContext {
-    
-    private String domain;
-    private String subDomain;
-    
-    /**
-     * Constructor
-     * 
-     * @param domain domain name
-     * @param subDomain subdomain name
-     */
-    public DomainContext (String domain, String subDomain) {
-        this.domain = domain;
-        this.subDomain = subDomain;
-    }
-
-    /**
-     * Returns the domain 
-     * 
-     * @return the domain
-     */
-    public String getDomain() {
-        return domain;
-    }
-
-    /**
-     * Returns the sub domain
-     * 
-     * @return the subDomain
-     */
-    public String getSubDomain() {
-        return subDomain;
-    }
-    
-    /**
-     * Overridden equals method
-     */
-    public boolean equals (Object object) {
-        if (object == null) 
-            return false;
-        if (object == this)  
-            return true;
-        if (!(object instanceof DomainContext))
-            return false;
-        
-        DomainContext domainCtx = (DomainContext)object;
-        if(this.getDomain().equals(domainCtx.getDomain()) &&
-                this.getSubDomain().equals(domainCtx.getSubDomain()))
-            return true;
-        else
-            return false;
-    }
-    
-    /**
-     * Overridden hashCode method
-     */
-    public int hashCode () {
-        int domainHash = 0;
-        int subDomainHash = 0;
-        
-        if(domain != null)
-            domainHash = domain.hashCode();
-        if(subDomain != null)
-            subDomainHash = subDomain.hashCode();
-        
-        return domainHash + subDomainHash;
-    }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopicHealthChecker.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopicHealthChecker.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopicHealthChecker.java
deleted file mode 100644
index de8f9df..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopicHealthChecker.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.adc.topology.mgt.subscriber;
-
-import javax.jms.TopicSubscriber;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * This health checker runs forever, and is responsible for re-establishing a connection
- * between SC and CC.
- */
-public class TopicHealthChecker implements Runnable{
-    
-    private static final Log log = LogFactory.getLog(TopicHealthChecker.class);
-    private String topicName;
-    private TopicSubscriber subscriber;
-
-    public TopicHealthChecker(String topicName, TopicSubscriber subscriber) {
-        this.topicName = topicName;
-        this.subscriber = subscriber;
-    }
-    
-    @Override
-    public void run() {
-        log.info("Topic Health Checker is running... ");
-
-        while (true) {
-            try {
-                subscriber.getTopic();
-                
-                // health checker runs in every 30s
-                Thread.sleep(30000);
-
-            } catch (Exception e) {
-                // implies connection is not established
-                // sleep for 5s and retry
-                try {
-                    log.info("Health checker failed and will retry to establish a connection after a 5s.");
-                    Thread.sleep(5000);
-                    break;
-                } catch (InterruptedException ignore) {
-                }
-            }
-
-        }
-
-        TopologySubscriber.subscribe(topicName);
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologyListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologyListener.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologyListener.java
deleted file mode 100644
index 57289d7..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologyListener.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- */
-
-package org.apache.stratos.adc.topology.mgt.subscriber;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.TextMessage;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.topology.mgt.util.ConfigHolder;
-
-public class TopologyListener implements MessageListener {
-
-    private static final Log log = LogFactory.getLog(TopologyListener.class);
-
-    @SuppressWarnings("unchecked")
-    public void onMessage(Message message) {
-        TextMessage receivedMessage = (TextMessage) message;
-        try {
-
-            ConfigHolder.getInstance().getSharedTopologyDiffQueue().add(receivedMessage.getText());
-
-        } catch (JMSException e) {
-            log.error(e.getMessage(), e);
-        }
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriber.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriber.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriber.java
deleted file mode 100644
index 97bf94f..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriber.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- */
-
-package org.apache.stratos.adc.topology.mgt.subscriber;
-
-import java.util.Properties;
-
-import javax.jms.*;
-import javax.naming.InitialContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.topology.mgt.util.TopologyConstants;
-
-public class TopologySubscriber {
-
-	private static final Log log = LogFactory.getLog(TopologySubscriber.class);
-	
-    public static void subscribe(String topicName) {
-        Properties initialContextProperties = new Properties();
-        TopicSubscriber topicSubscriber = null;
-        TopicSession topicSession = null;
-        TopicConnection topicConnection = null;
-        InitialContext initialContext = null;
-
-        initialContextProperties.put("java.naming.factory.initial",
-            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");
-
-        String mbServerIp =
-            System.getProperty(TopologyConstants.MB_SERVER_IP) == null
-                ? TopologyConstants.DEFAULT_MB_SERVER_IP
-                : System.getProperty(TopologyConstants.MB_SERVER_IP);
-
-        String connectionString =
-            "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" +
-                mbServerIp + "'&reconnect='true'";
-        initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);
-
-        try {
-            initialContext = new InitialContext(initialContextProperties);
-            TopicConnectionFactory topicConnectionFactory =
-                (TopicConnectionFactory) initialContext.lookup("qpidConnectionfactory");
-            topicConnection = topicConnectionFactory.createTopicConnection();
-            topicConnection.start();
-            topicSession =
-                topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
-
-            Topic topic = topicSession.createTopic(topicName);
-            topicSubscriber =
-                topicSession.createSubscriber(topic);
-
-            topicSubscriber.setMessageListener(new TopologyListener());
-
-        } catch (Exception e) {
-            log.error(e.getMessage(), e);
-
-            try {
-                if (topicSubscriber != null) {
-                    topicSubscriber.close();
-                }
-
-                if (topicSession != null) {
-                    topicSession.close();
-                }
-
-                if (topicConnection != null) {
-                    topicConnection.close();
-                }
-            } catch (JMSException e1) {
-                // ignore
-            }
-
-        } finally {
-            // start the health checker
-            Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
-            healthChecker.start();
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriberTask.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriberTask.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriberTask.java
deleted file mode 100644
index 525de89..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriberTask.java
+++ /dev/null
@@ -1 +0,0 @@
-package org.apache.stratos.adc.topology.mgt.subscriber;

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java
deleted file mode 100644
index a45aa8f..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/**
- *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- */
-
-package org.apache.stratos.adc.topology.mgt.util;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.topology.mgt.exception.TopologyMgtException;
-import org.apache.synapse.config.SynapseConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
-import org.wso2.carbon.ntask.core.service.TaskService;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.user.core.service.RealmService;
-
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-
-/**
- *
- */
-public class ConfigHolder {
-
-    private static ConfigHolder instance;
-    private static final Log log = LogFactory.getLog(ConfigHolder.class);
-
-    private SynapseConfiguration synapseConfiguration;
-    private ConfigurationContext configCtxt;
-    private AxisConfiguration axisConfiguration;
-    private UserRegistry configRegistry;
-    private UserRegistry governanceRegistry;
-    private TaskService taskService;
-    private BlockingQueue sharedTopologyDiffQueue = new LinkedBlockingQueue();
-    private String previousMessage;
-    private Map<String, List<ServiceConfiguration>> serviceNameToServiceConfigurations;
-//    private DependencyManagementService dependencyManager;
-    private LoadBalancerConfigurationService lbConfigService;
-    
-
-//    private Map<Integer, SynapseEnvironmentService> synapseEnvironmentServices =
-//            new HashMap<Integer, SynapseEnvironmentService>();
-
-    public RealmService getRealmService() {
-        return realmService;
-    }
-
-    public void setRealmService(RealmService realmService) {
-        this.realmService = realmService;
-    }
-
-    private RealmService realmService;
-
-    private ConfigHolder() {
-    }
-
-    public static ConfigHolder getInstance() {
-        if (instance == null) {
-            instance = new ConfigHolder();
-        }
-        return instance;
-    }
-
-    public SynapseConfiguration getSynapseConfiguration() throws TopologyMgtException{
-        assertNull("SynapseConfiguration", synapseConfiguration);
-        return synapseConfiguration;
-    }
-
-    public void setSynapseConfiguration(SynapseConfiguration synapseConfiguration) {
-        this.synapseConfiguration = synapseConfiguration;
-    }
-
-    public AxisConfiguration getAxisConfiguration() throws TopologyMgtException {
-        assertNull("AxisConfiguration", axisConfiguration);
-        return axisConfiguration;
-    }
-
-    public void setAxisConfiguration(AxisConfiguration axisConfiguration) {
-        this.axisConfiguration = axisConfiguration;
-    }
-
-    public UserRegistry getConfigRegistry() throws TopologyMgtException {
-        assertNull("Registry", configRegistry);
-        return configRegistry;
-    }
-
-    public void setConfigRegistry(UserRegistry configRegistry) {
-        this.configRegistry = configRegistry;
-    }
-
-////    public DependencyManagementService getDependencyManager() {
-////        return dependencyManager;
-////    }
-//
-//    public void setDependencyManager(DependencyManagementService dependencyManager) {
-//        this.dependencyManager = dependencyManager;
-//    }
-
-    private void assertNull(String name, Object object) throws TopologyMgtException {
-        if (object == null) {
-            String message = name + " reference in the proxy admin config holder is null";
-            log.error(message);
-            throw new TopologyMgtException(message);
-        }
-    }
-
-    public UserRegistry getGovernanceRegistry() {
-        return governanceRegistry;
-    }
-
-    public void setGovernanceRegistry(UserRegistry governanceRegistry) {
-        this.governanceRegistry = governanceRegistry;
-    }
-
-//    public SynapseEnvironmentService getSynapseEnvironmentService(int id) {
-//        return synapseEnvironmentServices.get(id);
-//    }
-//
-//    public void addSynapseEnvironmentService(int id,
-//                                             SynapseEnvironmentService synapseEnvironmentService) {
-//        synapseEnvironmentServices.put(id, synapseEnvironmentService);
-//    }
-//
-//    public void removeSynapseEnvironmentService(int id) {
-//        synapseEnvironmentServices.remove(id);
-//    }
-//
-//    public Map<Integer, SynapseEnvironmentService> getSynapseEnvironmentServices() {
-//        return synapseEnvironmentServices;
-//    }
-
-    public ConfigurationContext getConfigCtxt() {
-        return configCtxt;
-    }
-
-    public void setConfigCtxt(ConfigurationContext configCtxt) {
-        this.configCtxt = configCtxt;
-    }
-    
-    public void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
-        this.lbConfigService = lbConfigSer;
-    }
-
-    public LoadBalancerConfiguration getLbConfig() {
-        return (LoadBalancerConfiguration) lbConfigService.getLoadBalancerConfig();
-    }
-    
-    public TaskService getTaskService() {
-        return taskService;
-    }
-
-    public void setTaskService(TaskService taskService) {
-        this.taskService = taskService;
-    }
-
-    public BlockingQueue getSharedTopologyDiffQueue() {
-	    return sharedTopologyDiffQueue;
-    }
-
-	public void setSharedTopologyDiffQueue(BlockingQueue sharedTopologyDiffQueue) {
-	    this.sharedTopologyDiffQueue = sharedTopologyDiffQueue;
-    }
-
-	public void setServiceConfigs(Map<String, List<ServiceConfiguration>> serviceNameToServiceConfigurations) {
-
-		this.serviceNameToServiceConfigurations = serviceNameToServiceConfigurations;
-    }
-	
-	public Map<String, List<ServiceConfiguration>> getServiceConfigs(){
-		return serviceNameToServiceConfigurations;
-	}
-
-	public String getPreviousMessage() {
-	    return previousMessage;
-    }
-
-	public void setPreviousMessage(String previousMessage) {
-	    this.previousMessage = previousMessage;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyConstants.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyConstants.java
deleted file mode 100644
index 984610d..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyConstants.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package org.apache.stratos.adc.topology.mgt.util;
-
-public class TopologyConstants {
-    
-    public static final String TOPIC_NAME = "cloud-controller-topology";
-    public static final String MB_SERVER_IP = "mb.server.ip";
-    public static final String DEFAULT_MB_SERVER_IP = "localhost:5673";
-    
-    public static final String TOPOLOGY_SYNC_CRON = "1 * * * * ? *";
-	public static final String TOPOLOGY_SYNC_TASK_NAME = "TopologySubscriberTaskOfADC";
-	public static final String TOPOLOGY_SYNC_TASK_TYPE = "TOPOLOGY_SUBSCRIBER_TASK";
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyMgtUtil.java b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyMgtUtil.java
deleted file mode 100644
index 01ff6db..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyMgtUtil.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package org.apache.stratos.adc.topology.mgt.util;
-
-public class TopologyMgtUtil {
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/resources/META-INF/services.xml
deleted file mode 100644
index ef91287..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<serviceGroup>
-    <service name="TopologyMgtService" scope="application">
-        <parameter name="ServiceClass">org.apache.stratos.adc.topology.mgt.service.impl.TopologyManagementServiceImpl</parameter>
-        <messageReceivers>
-        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
-        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
-    </messageReceivers>
-    </service>
-</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/pom.xml b/components/org.apache.stratos.adc.topology.mgt/pom.xml
new file mode 100644
index 0000000..66f0f14
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/pom.xml
@@ -0,0 +1,135 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.apache.stratos</groupId>
+    <artifactId>org.apache.stratos.adc.topology.mgt</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Topology Management</name>
+    <url>http://apache.org</url>
+    
+    <dependencies>
+        <!-- <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.mediation.initializer</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency> -->
+        <!-- <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.mediation.dependency.mgt</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency> -->
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-core</artifactId>
+            <version>${synapse.core.version}</version>
+        </dependency>
+         <!--dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+            <version>1.6.1.wso2v9</version>
+        </dependency-->
+        <dependency>
+            <groupId>org.apache.axis2</groupId>
+            <artifactId>axis2-kernel</artifactId>
+            <version>${axis2.kernel.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.logging</artifactId>
+	    <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.lb.common</artifactId>
+            <version>${apache.stratos.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ntask.core</artifactId>
+	    <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+                <groupId>org.wso2.andes.wso2</groupId>
+                <artifactId>andes-client</artifactId>
+                <version>0.13.wso2v3</version>
+            </dependency>
+        <dependency>
+                <groupId>org.apache.geronimo.specs.wso2</groupId>
+                <artifactId>geronimo-jms_1.1_spec</artifactId>
+                <version>${orbit.version.geronimo-jms_1.1_spec}</version>
+            </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <!-- <Private-Package>
+                        	org.wso2.carbon.stratos.topology.mgt.service.impl.*
+                        </Private-Package> -->
+                        <Export-Package>
+                            org.apache.stratos.adc.topology.mgt.subscriber.*,
+                            org.apache.stratos.adc.topology.mgt.service.*,
+                            org.apache.stratos.adc.topology.mgt.group.mgt.*,
+							org.apache.stratos.adc.topology.mgt.serviceobjects.*
+                        </Export-Package>
+                        <Import-Package>
+                            org.apache.stratos.lb.common.*; version=4.1.3,
+                            org.apache.stratos.registry.core.service; version=1.0.1,
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/builder/TopologySyncher.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/builder/TopologySyncher.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/builder/TopologySyncher.java
new file mode 100644
index 0000000..71acee0
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/builder/TopologySyncher.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.adc.topology.mgt.builder;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.topology.mgt.group.mgt.GroupMgtAgentBuilder;
+import org.apache.stratos.adc.topology.mgt.util.ConfigHolder;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.lb.common.conf.structure.Node;
+import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
+
+
+public class TopologySyncher implements Runnable {
+
+	@SuppressWarnings("rawtypes")
+    private BlockingQueue sharedQueue;
+	private static final Log log = LogFactory.getLog(TopologySyncher.class);
+	
+	public TopologySyncher(@SuppressWarnings("rawtypes") BlockingQueue queue){
+		
+		sharedQueue = queue;
+		
+	}
+	
+	public void run() {
+
+	    LoadBalancerConfiguration lbconfig = LoadBalancerConfiguration.getInstance();
+	    
+	    //FIXME Currently there has to be at least one dummy cluster defined in the loadbalancer conf
+	    // in order to proper initialization of TribesClusteringAgent.
+	    generateGroupMgtAgents(lbconfig);
+	    
+        while (true) {
+            try {
+
+                Object obj;
+                String msg = null;
+
+                obj = sharedQueue.take();
+                msg = (String) obj;
+
+                ConfigHolder data = ConfigHolder.getInstance();
+
+                Node topologyNode = NodeBuilder.buildNode(msg);
+
+                List<ServiceConfiguration> currentServiceConfigs = lbconfig.createServicesConfig(topologyNode);
+
+                data.setServiceConfigs(lbconfig.getServiceNameToServiceConfigurations());
+                generateGroupMgtAgents(lbconfig);
+                resetGroupMgtAgents(lbconfig, currentServiceConfigs);
+
+            } catch (InterruptedException ignore) {
+            }
+        }
+
+	}
+
+    /**
+     * @param lbconfig
+     */
+    private void generateGroupMgtAgents(LoadBalancerConfiguration lbconfig) {
+        for (List<ServiceConfiguration> serviceConfigsList : lbconfig.getServiceNameToServiceConfigurations()
+                                                                     .values()) {
+
+        	for (ServiceConfiguration serviceConfiguration : serviceConfigsList) {
+        		GroupMgtAgentBuilder.createGroupMgtAgent(serviceConfiguration.getDomain(),
+        		                                         serviceConfiguration.getSubDomain());
+        	}
+        }
+    }
+    
+    private void resetGroupMgtAgents(LoadBalancerConfiguration lbConfig,
+        List<ServiceConfiguration> currentServiceConfigs) {
+
+        for (Iterator<?> iterator = lbConfig.getServiceConfigurations().values().iterator(); iterator.hasNext();) {
+            @SuppressWarnings("unchecked")
+            Map<String, ServiceConfiguration> valuesMap = (Map<String, ServiceConfiguration>) iterator.next();
+
+            for (Iterator<ServiceConfiguration> iterator2 = valuesMap.values().iterator(); iterator2.hasNext();) {
+                ServiceConfiguration oldServiceConfig = (ServiceConfiguration) iterator2.next();
+
+                if (!currentServiceConfigs.contains(oldServiceConfig)) {
+                    // if the ServiceConfiguration is not there any more in the latest topology
+                    lbConfig.removeServiceConfiguration(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
+                    GroupMgtAgentBuilder.resetGroupMgtAgent(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
+                }
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/exception/TopologyMgtException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/exception/TopologyMgtException.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/exception/TopologyMgtException.java
new file mode 100644
index 0000000..51faeb8
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/exception/TopologyMgtException.java
@@ -0,0 +1,35 @@
+/**
+ * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.topology.mgt.exception;
+
+public class TopologyMgtException extends RuntimeException {
+
+    private static final long serialVersionUID = -663839410798538370L;
+
+    public TopologyMgtException(String msg) {
+        super(msg);
+    }
+
+    public TopologyMgtException(String msg, Throwable cause) {
+        super(msg, cause);
+    }
+
+    public TopologyMgtException(Throwable cause) {
+        super(cause);
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java
new file mode 100644
index 0000000..1ef804f
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.adc.topology.mgt.group.mgt;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.topology.mgt.util.ConfigHolder;
+import org.apache.synapse.SynapseException;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
+
+public class GroupMgtAgentBuilder {
+
+	private static LoadBalancerConfiguration lbConfig;
+	/**
+     * Key - host name 
+     * Value - {@link HostContext}
+     */
+    private static Map<String, HostContext> hostContexts = new HashMap<String, HostContext>();
+    
+    private static final Log log = LogFactory.getLog(GroupMgtAgentBuilder.class);
+	
+	public static void createGroupMgtAgents() {
+		lbConfig = ConfigHolder.getInstance().getLbConfig();
+		hostContexts = lbConfig.getHostContextMap();
+		
+		ClusteringAgent clusteringAgent = ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
+        if (clusteringAgent == null) {
+            throw new SynapseException("Axis2 ClusteringAgent not defined in axis2.xml");
+        }
+
+        // Add the Axis2 GroupManagement agents
+        if (hostContexts != null) {
+            // iterate through each host context
+            for (HostContext hostCtxt : hostContexts.values()) {
+                // each host can has multiple Tenant Contexts, iterate through them
+                for (TenantDomainContext tenantCtxt : hostCtxt.getTenantDomainContexts()) {
+
+                    String domain = tenantCtxt.getDomain();
+                    String subDomain = tenantCtxt.getSubDomain();
+
+                    if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+                        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                            subDomain),
+                            domain, subDomain, -1);
+                        log.info("Group management agent added to cluster domain: " +
+                            domain + " and sub domain: " + subDomain);
+                    }
+                }
+            }
+        }
+    }
+	
+	public static void createGroupMgtAgent(String domain, String subDomain) {
+		
+		ClusteringAgent clusteringAgent = ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
+        if (clusteringAgent == null) {
+            throw new SynapseException("Axis2 ClusteringAgent not defined in axis2.xml");
+        }
+		
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+            clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                subDomain),
+                domain, subDomain, -1);
+            log.info("Group management agent added to cluster domain: " +
+                domain + " and sub domain: " + subDomain);
+        }
+	}
+	
+	public static void resetGroupMgtAgent(String domain, String subDomain) {
+
+        ClusteringAgent clusteringAgent =
+            ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
+        
+        if (clusteringAgent == null) {
+            throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
+        }
+
+        // checks the existence. 
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) != null) {
+            
+            clusteringAgent.resetGroupManagementAgent(domain, subDomain);
+            
+            log.info("Group management agent of cluster domain: " +
+                domain + " and sub domain: " + subDomain+" is removed.");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java
new file mode 100644
index 0000000..d674c4c
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java
@@ -0,0 +1,32 @@
+package org.apache.stratos.adc.topology.mgt.group.mgt;
+
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.management.DefaultGroupManagementAgent;
+
+/**
+ * This GroupManagementAgent can handle group membership based on cluster sub-domains
+ */
+public class SubDomainAwareGroupManagementAgent extends DefaultGroupManagementAgent {
+
+    private String subDomain;
+
+    public SubDomainAwareGroupManagementAgent(String subDomain) {
+        this.subDomain = subDomain;
+    }
+
+    @Override
+    public void applicationMemberAdded(Member member) {
+        String subDomain = member.getProperties().getProperty("subDomain");
+        if (subDomain == null || subDomain.equals(this.subDomain)) {
+            super.applicationMemberAdded(member);
+        }
+    }
+
+    @Override
+    public void applicationMemberRemoved(Member member) {
+        String subDomain = member.getProperties().getProperty("subDomain");
+        if (subDomain == null || subDomain.equals(this.subDomain)) {
+            super.applicationMemberRemoved(member);
+        }
+    }
+}
\ No newline at end of file


[17/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/UsageConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/UsageConstants.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/UsageConstants.java
new file mode 100644
index 0000000..607aa27
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/constants/UsageConstants.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.constants;
+
+public class UsageConstants {
+    final public static String ANY_DURATION = "anyDuration";
+
+    public static final String SYSTEM_METERING_PATH =
+            "/repository/components/org.wso2.carbon.system-metering";
+
+    public static final String CUSTOM_METERING_PATH =
+        "/repository/components/org.wso2.carbon.system-metering";
+
+    // the measurements
+    final public static String CAPACITY_USAGE = "capacity-usage";
+    
+    final public static String SERVICE_REQUEST_COUNT = "serviceRequestCount";
+    final public static String SERVICE_RESPONSE_COUNT = "serviceResponseCount";
+    final public static String SERVICE_FAULT_COUNT = "serviceFaultCount";
+    
+    public static final String BANDWIDTH_KEY_PATTERN = "%Bandwidth%";
+    public static final String REGISTRY_BANDWIDTH = "RegistryBandwidth";
+    public static final String SERVICE_BANDWIDTH = "ServiceBandwidth";
+    public static final String WEBAPP_BANDWIDTH = "WebappBandwidth";
+    public static final String IN_LABLE = "-In";
+    public static final String OUT_LABLE = "-Out";
+    public static final String REGISTRY_CONTENT_BANDWIDTH = "ContentBandwidth";
+    
+    final public static String REGISTRY_INCOMING_BW = REGISTRY_BANDWIDTH + IN_LABLE;
+    final public static String REGISTRY_OUTGOING_BW = REGISTRY_BANDWIDTH + OUT_LABLE;
+    final public static String REGISTRY_TOTAL_BW = "registry-total-bw-usage";
+    final public static String NUMBER_OF_USERS = "number-of-users";
+
+    final public static String SERVICE_INCOMING_BW = SERVICE_BANDWIDTH + IN_LABLE;
+    final public static String SERVICE_OUTGOING_BW = SERVICE_BANDWIDTH + OUT_LABLE;
+    final public static String SERVICE_TOTAL_BW = "serviceRequestTotalBw";
+    
+    final public static String WEBAPP_INCOMING_BW = WEBAPP_BANDWIDTH + IN_LABLE;
+    final public static String WEBAPP_OUTGOING_BW = WEBAPP_BANDWIDTH + OUT_LABLE;
+
+    final public static String API_CALL_COUNT = "apiCallCount";
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/exception/StratosException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/exception/StratosException.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/exception/StratosException.java
new file mode 100644
index 0000000..8be9f89
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/exception/StratosException.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.common.exception;
+
+/**
+ * This class is defined as the general Exception implementation for Stratos. This can be used
+ * within Stratos components when handling exceptions.
+ */
+public class StratosException extends Exception{
+
+    public StratosException() {
+    }
+
+    public StratosException(String message) {
+        super(message);
+    }
+
+    public StratosException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    public StratosException(Throwable cause) {
+        super(cause);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java
new file mode 100644
index 0000000..e43c9a6
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.packages.PackageInfoHolder;
+import org.apache.stratos.common.util.CommonUtil;
+import org.apache.stratos.common.util.StratosConfiguration;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+
+/**
+ * @scr.component name="apache.stratos.common" immediate="true"
+ * @scr.reference name="registry.service"
+ *                interface="org.wso2.carbon.registry.core.service.RegistryService"
+ *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
+ *                unbind="unsetRegistryService"
+ * @scr.reference name="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1" policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ */
+public class CloudCommonServiceComponent {
+
+    private static Log log = LogFactory.getLog(CloudCommonServiceComponent.class);
+
+    private static BundleContext bundleContext;
+    private static RealmService realmService;
+    private static RegistryService registryService;
+    private static PackageInfoHolder packageInfos;
+
+    protected void activate(ComponentContext context) {
+        try {
+            bundleContext = context.getBundleContext();
+            if (CommonUtil.getStratosConfig() == null) {
+                StratosConfiguration stratosConfig = CommonUtil.loadStratosConfiguration();
+                CommonUtil.setStratosConfig(stratosConfig);
+            }
+
+            // Loading the EULA
+            if (CommonUtil.getEula() == null) {
+                String eula = CommonUtil.loadTermsOfUsage();
+                CommonUtil.setEula(eula);
+            }
+            
+			packageInfos = new PackageInfoHolder();
+			context.getBundleContext().registerService(
+					PackageInfoHolder.class.getName(), packageInfos, null);
+
+            //Register manager configuration OSGI service
+            try {
+                StratosConfiguration stratosConfiguration = CommonUtil.loadStratosConfiguration();
+                bundleContext.registerService(StratosConfiguration.class.getName(), stratosConfiguration, null);
+                if (log.isDebugEnabled()) {
+                    log.debug("******* Cloud Common Service bundle is activated ******* ");
+                }
+            } catch (Exception ex) {
+                String msg = "An error occurred while initializing Cloud Common Service as an OSGi Service";
+                log.error(msg, ex);
+            }
+        } catch (Throwable e) {
+            log.error("Error in activating Cloud Common Service Component" + e.toString());
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Tenant Core bundle is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        CloudCommonServiceComponent.registryService = registryService;
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        CloudCommonServiceComponent.realmService = realmService;
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        setRealmService(null);
+    }
+
+    public static BundleContext getBundleContext() {
+        return bundleContext;
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static TenantManager getTenantManager() {
+        return realmService.getTenantManager();
+    }
+
+    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getGovernanceSystemRegistry(tenantId);
+    }
+
+    public static UserRegistry getConfigSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getConfigSystemRegistry(tenantId);
+    }
+
+	public static PackageInfoHolder getPackageInfos() {
+		return packageInfos;
+	}
+
+    
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java
new file mode 100644
index 0000000..4a9a316
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.listeners;
+
+
+import org.apache.stratos.common.beans.TenantInfoBean;
+import org.apache.stratos.common.exception.StratosException;
+
+public interface TenantMgtListener {
+    public void onTenantCreate(TenantInfoBean tenantInfo) throws StratosException;
+
+    public void onTenantUpdate(TenantInfoBean tenantInfo) throws StratosException;
+
+    public void onTenantRename(int tenantId, String oldDomainName, 
+                             String newDomainName)throws StratosException;
+    
+    public void onTenantInitialActivation(int tenantId) throws StratosException;
+    
+    public void onTenantActivation(int tenantId) throws StratosException;
+    
+    public void onTenantDeactivation(int tenantId) throws StratosException;
+
+    public void onSubscriptionPlanChange(int tenentId, String oldPlan, 
+                                         String newPlan) throws StratosException;
+    
+    public int getListenerOrder();
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfo.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfo.java
new file mode 100644
index 0000000..f20a6cd
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfo.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.packages;
+
+/*
+ * Deserialize following XML
+<packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+    <package name="multitenancy-free">
+        <!--<subscriptionCharge>0</subscriptionCharge>--> <!-- $ per month -->
+        <users>
+            <limit>5</limit>
+            <charge>0</charge> <!-- charge per month -->
+        </users>
+        <resourceVolume>
+            <limit>10</limit> <!--mb per user -->
+        </resourceVolume>
+        <bandwidth>
+            <limit>1000</limit> <!-- mb per user -->
+            <overuseCharge>0</overuseCharge> <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="multitenancy-small">
+        ...
+    </package>
+</packages>
+ */
+public class PackageInfo {
+	
+	private String name;
+	private int usersLimit;
+	private int subscriptionCharge;
+	private int chargePerUser;
+	private int resourceVolumeLimit;
+	private int bandwidthLimit;
+	private int bandwidthOveruseCharge;
+
+	
+	public String getName() {
+		return name;
+	}
+
+	public void setName(String name) {
+		this.name = name;
+	}
+
+	public int getUsersLimit() {
+		return usersLimit;
+	}
+
+	public void setUsersLimit(int usersLimit) {
+		this.usersLimit = usersLimit;
+	}
+
+	public int getSubscriptionCharge() {
+		return subscriptionCharge;
+	}
+
+	public void setSubscriptionCharge(int subscriptionCharge) {
+		this.subscriptionCharge = subscriptionCharge;
+	}
+
+	public int getChargePerUser() {
+		return chargePerUser;
+	}
+
+	public void setChargePerUser(int chargePerUser) {
+		this.chargePerUser = chargePerUser;
+	}
+
+	public int getResourceVolumeLimit() {
+		return resourceVolumeLimit;
+	}
+
+	public void setResourceVolumeLimit(int resourceVolumeLimit) {
+		this.resourceVolumeLimit = resourceVolumeLimit;
+	}
+
+	public int getBandwidthLimit() {
+		return bandwidthLimit;
+	}
+
+	public void setBandwidthLimit(int bandwidthLimit) {
+		this.bandwidthLimit = bandwidthLimit;
+	}
+
+	public int getBandwidthOveruseCharge() {
+		return bandwidthOveruseCharge;
+	}
+
+	public void setBandwidthOveruseCharge(int bandwidthOveruseCharge) {
+		this.bandwidthOveruseCharge = bandwidthOveruseCharge;
+	}
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java
new file mode 100644
index 0000000..68fc5da
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.packages;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.exception.StratosException;
+import org.apache.stratos.common.util.CommonUtil;
+import org.jaxen.JaxenException;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.xml.namespace.QName;
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public class PackageInfoHolder {
+    private static Log log = LogFactory.getLog(PackageInfoHolder.class);
+    private static final String PACKAGE_DESCRIPTION_CONFIG = "multitenancy-packages.xml";
+    private static final String PACKAGE_DESCRIPTION_CONFIG_NS =
+            "http://wso2.com/carbon/multitenancy/billing/pacakges";
+    
+    List<PackageInfo> multitenancyPackages = new ArrayList<PackageInfo>();
+
+    public PackageInfoHolder() throws StratosException {
+        multitenancyPackages = deserializePackageDescriptionConfig();
+    }
+
+    public List<PackageInfo> getMultitenancyPackages() {
+        return multitenancyPackages;
+    }
+
+    /*
+     * Deserialize following XML
+    <packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+        <package name="multitenancy-free">
+            <!--<subscriptionCharge>0</subscriptionCharge>--> <!-- $ per month -->
+            <users>
+                <limit>5</limit>
+                <charge>0</charge> <!-- charge per month -->
+            </users>
+            <resourceVolume>
+                <limit>10</limit> <!--mb per user -->
+            </resourceVolume>
+            <bandwidth>
+                <limit>1000</limit> <!-- mb per user -->
+                <overuseCharge>0</overuseCharge> <!-- $ per user per month -->
+            </bandwidth>
+        </package>
+        <package name="multitenancy-small">
+            ...
+        </package>
+    </packages>
+     */
+    private List<PackageInfo> deserializePackageDescriptionConfig() throws StratosException {
+        String configFilePath = CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                PACKAGE_DESCRIPTION_CONFIG;
+        
+        OMElement packageConfigs;
+        try {
+            packageConfigs = CommonUtil.buildOMElement(new FileInputStream(configFilePath));
+        } catch (Exception e) {
+            String msg = "Error in deserializing the packageConfigs file: " + configFilePath + ".";
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+
+        @SuppressWarnings("unchecked")
+        Iterator<OMElement> packageConfigsChildsIt = packageConfigs.getChildElements();
+        while (packageConfigsChildsIt.hasNext()) {
+            OMElement packageConfigEle = packageConfigsChildsIt.next();
+            if (!new QName(PACKAGE_DESCRIPTION_CONFIG_NS, "package").equals(
+                    packageConfigEle.getQName())) {
+                continue;
+            }
+            
+            PackageInfo multitenancyPackage = new PackageInfo();
+            String packageName = packageConfigEle.getAttributeValue(new QName("name"));
+            String subscriptionCharge = getPackageConfigValue("subscriptionCharge", packageConfigEle);
+            String usersLimit = getPackageConfigValue("users.limit", packageConfigEle);
+            String usersCharge = getPackageConfigValue("users.charge", packageConfigEle);
+
+            String resourceVolumeLimit =
+                    getPackageConfigValue("resourceVolume.limit", packageConfigEle);
+            String resourceVolumeOveruseCharge =
+                    getPackageConfigValue("resourceVolume.overuseCharge", packageConfigEle);
+            String bandwidthLimit = getPackageConfigValue("bandwidth.limit", packageConfigEle);
+            String bandwidthOveruseCharge =
+                    getPackageConfigValue("bandwidth.overuseCharge", packageConfigEle);
+            int usersLimitInt = -1;
+            if (!usersLimit.equals("unlimited")) {
+                usersLimitInt = Integer.parseInt(usersLimit);
+            }
+            int resourceVolumeLimitInt = -1;
+            if (!resourceVolumeLimit.equals("unlimited")) {
+                resourceVolumeLimitInt = Integer.parseInt(resourceVolumeLimit);
+            }
+            int bandwidthLimitInt = -1;
+            if (!bandwidthLimit.equals("unlimited")) {
+                bandwidthLimitInt = Integer.parseInt(bandwidthLimit);
+            }
+
+            multitenancyPackage.setName(packageName);
+            //In the PackageInfo class subscriptionCharge, chargeperUser and bandwidthOverUsageCharge
+            //are declared as Integers. I think it is better to change them to float. If somebody
+            //enters a float value to the conf file it will cause an exception here
+            multitenancyPackage.setSubscriptionCharge(Integer.parseInt(subscriptionCharge));
+            multitenancyPackage.setUsersLimit(usersLimitInt);
+       //   multitenancyPackage.setChargePerUser(Integer.parseInt(usersCharge));
+            multitenancyPackage.setResourceVolumeLimit(resourceVolumeLimitInt);
+            multitenancyPackage.setBandwidthLimit(bandwidthLimitInt);
+          //  multitenancyPackage.setBandwidthOveruseCharge(Integer.parseInt(bandwidthOveruseCharge));
+
+            multitenancyPackages.add(multitenancyPackage);
+        }
+        return multitenancyPackages;
+    }
+
+    private String getPackageConfigValue(String key, OMElement packageNode) throws StratosException {
+        String qualifiedKey = "ns:" + key.replaceAll("\\.", "/ns:");
+        AXIOMXPath xpathExpression;
+        try {
+            xpathExpression = new AXIOMXPath(qualifiedKey);
+            xpathExpression.addNamespace("ns", PACKAGE_DESCRIPTION_CONFIG_NS);
+            List valueNodes = xpathExpression.selectNodes(packageNode);
+            if (valueNodes.isEmpty()) {
+                if (log.isDebugEnabled()) {
+                    String msg = "No results found parsing package configuration for key: " + 
+                            qualifiedKey + ".";
+                    log.debug(msg);
+                }
+                return null;
+            }
+            OMElement valueNode = (OMElement) valueNodes.get(0);
+            return valueNode.getText();
+        } catch (JaxenException e) {
+            String msg = "Error in retrieving the key: " + qualifiedKey + ".";
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/services/PackageInfoService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/services/PackageInfoService.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/services/PackageInfoService.java
new file mode 100644
index 0000000..6ace99f
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/services/PackageInfoService.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.services;
+
+import org.apache.stratos.common.internal.CloudCommonServiceComponent;
+import org.apache.stratos.common.packages.PackageInfo;
+
+import java.util.List;
+
+
+public class PackageInfoService {
+
+	public PackageInfo[] getPackageInfos() throws Exception {
+		List<PackageInfo> list = CloudCommonServiceComponent.getPackageInfos().
+		                                                     getMultitenancyPackages();
+		PackageInfo[] packageInfos = list.toArray(new PackageInfo[list.size()]);
+		return packageInfos;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java
new file mode 100644
index 0000000..d151df9
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java
@@ -0,0 +1,278 @@
+/*
+ * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.stratos.common.util;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.user.core.UserCoreConstants;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.UserStoreManager;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+/*
+ * This class handles the parameters that are input during the registration
+ * which later are
+ * stored as claims.
+ * 
+ * Current claims are:
+ * First Name - GIVEN_NAME
+ * Last Name - SURNAME
+ */
+public class ClaimsMgtUtil {
+
+    private static final Log log = LogFactory.getLog(ClaimsMgtUtil.class);
+
+    /* Methods to get the first and last names from the getNames() */
+    /**
+     * gets first name
+     * 
+     * @param realmService realmService
+     * @param tenantId
+     *            tenant id
+     * @return first name
+     * @throws Exception
+     *             if error in getting the first name
+     */
+    public static String getFirstName(RealmService realmService, int tenantId)throws Exception {
+        String names[] = getNames(realmService, tenantId);
+        return names[0];
+    }
+
+    /**
+     * gets last name
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant id
+     * @return last name
+     * @throws Exception
+     *             if error in getting the last name
+     */
+    public static String getLastName(RealmService realmService, int tenantId) throws Exception {
+        String names[] = getNames(realmService, tenantId);
+        return names[1];
+    }
+
+    /**
+     * Gets the first name of a tenant admin to address him/her in the
+     * notifications
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant Id
+     * @return first name / calling name
+     * @throws Exception
+     *             if unable to retrieve the admin name
+     */
+    public static String[] getNames(RealmService realmService, int tenantId) throws Exception {
+        String[] names = new String[2];
+        String firstname = "", lastname = "";
+        try {
+            firstname = getFirstNamefromUserStoreManager(realmService, tenantId);
+        } catch (Exception ignore) {
+            if (log.isDebugEnabled()) {
+                // Not exceptions,due to the existence of tenants with no full name.
+                String msg = "Unable to get the firstname from the user store manager";
+                log.debug(msg, ignore);
+            }
+        }
+        if (firstname != null && !firstname.trim().equals("")) {
+            lastname = getLastNamefromUserStoreManager(realmService, tenantId);
+            if ((lastname != null) && (!lastname.trim().equals(""))) {
+                names[0] = firstname;
+                names[1] = lastname;
+            } else {
+                // no last name - fullname was considered givenname;
+                names = getNamesfromFullName(realmService, firstname);
+            }
+        } else { 
+            // Work around for old tenants - where even full name is not input.
+            if (log.isDebugEnabled()) {
+                log.debug("First name is not available");
+            }
+            try {
+                firstname = getAdminUserNameFromTenantId(realmService, tenantId);
+                names[0] = firstname;
+                names[1] = lastname;
+            } catch (Exception e) {
+                String msg = "Unable to get the admin Name from the user store manager";
+                log.error(msg, e);
+                throw new Exception(msg, e);
+            }
+        }
+        return names;
+    }
+
+    /**
+     * Method to get the name of the admin user given the tenant id
+     * 
+     * @param tenantId
+     *            tenant id
+     * @return admin user name
+     * @throws Exception
+     *             UserStoreException
+     */
+    public static String getAdminUserNameFromTenantId(RealmService realmService, int tenantId)
+                                                                                              throws Exception {
+        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            return realmService.getBootstrapRealmConfiguration().getAdminUserName();
+        }
+        String tenantAdminName ="";
+        try {
+            if (realmService.getTenantManager().getTenant(tenantId) != null) {
+                tenantAdminName = realmService.getTenantManager().getTenant(tenantId).getAdminName();
+            }
+        } catch (org.wso2.carbon.user.api.UserStoreException e) {
+            String msg = "Unable to retrieve the admin name for the tenant with the tenant Id: " +
+                         tenantId;
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        return tenantAdminName;
+    }
+
+    /**
+     * Let's split the givenname into two.
+     * 
+     * @param fullName
+     *            full name of the tenant admin
+     * @return first name
+     */
+    public static String[] getNamesfromFullName(RealmService realmService, String fullName) {
+        String[] names = new String[0];
+
+        if (!fullName.trim().equals("")) {
+            names = fullName.split(" ", 2); // split by space.
+        }
+        return names; // first entry as the calling name.
+    }
+
+    /**
+     * Get the claims from the user store manager
+     * 
+     * @param tenant
+     *            tenant information
+     * @param tenantId
+     *            tenantId
+     * @param claim
+     *            claim name
+     * @return claim value
+     * @throws org.wso2.carbon.user.core.UserStoreException
+     *             exception in getting the user store manager
+     */
+    public static String getClaimfromUserStoreManager(RealmService realmService, int tenantId,
+                                                      String claim) throws UserStoreException {
+        UserStoreManager userStoreManager = null;
+        String claimValue = "";
+        try {
+            if (realmService.getTenantUserRealm(tenantId) != null) {
+                userStoreManager =
+                        (UserStoreManager) realmService.getTenantUserRealm(tenantId)
+                                .getUserStoreManager();
+            }
+
+        } catch (Exception e) {
+            String msg = "Error retrieving the user store manager for the tenant";
+            log.error(msg, e);
+            throw new UserStoreException(msg, e);
+        }
+        try {
+            if (userStoreManager != null) {
+                claimValue =
+                        userStoreManager.getUserClaimValue(
+                                getAdminUserNameFromTenantId(realmService, tenantId), claim,
+                                UserCoreConstants.DEFAULT_PROFILE);
+            }
+            return claimValue;
+        } catch (Exception e) {
+            String msg = "Unable to retrieve the claim for the given tenant";
+            log.error(msg, e);
+            throw new UserStoreException(msg, e);
+        }
+    }
+
+    /**
+     * Gets first name from the user store manager
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant id
+     * @return first name
+     * @throws UserStoreException
+     *             , if error in getting the claim GIVEN_NAME
+     */
+    public static String getFirstNamefromUserStoreManager(RealmService realmService,
+                                                          int tenantId) throws UserStoreException {
+        try {
+            return getClaimfromUserStoreManager(realmService, tenantId,
+                                                UserCoreConstants.ClaimTypeURIs.GIVEN_NAME);
+        } catch (Exception e) {
+            String msg = "First Name not found for the tenant";
+            log.debug(msg, e);
+            return ""; // returns empty string
+        }
+    }
+
+    /**
+     * Gets last name from the user store manager
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant id
+     * @return last name
+     * @throws UserStoreException
+     *             , if error in getting the claim SURNAME
+     */
+    public static String getLastNamefromUserStoreManager(RealmService realmService,
+                                                         int tenantId) throws UserStoreException {
+        String lastname = "";
+        try {
+            lastname = getClaimfromUserStoreManager(realmService, tenantId,
+                                                    UserCoreConstants.ClaimTypeURIs.SURNAME);
+        } catch (Exception e) {
+            String msg = "Last Name not found for the tenant";
+            log.debug(msg, e);
+        }
+        return lastname; // returns empty string, if couldn't get last name from
+                         // userStore manager
+    }
+
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java
new file mode 100644
index 0000000..4108973
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java
@@ -0,0 +1,200 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.util;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.config.CloudServiceConfig;
+import org.apache.stratos.common.config.CloudServicesDescConfig;
+import org.apache.stratos.common.config.PermissionConfig;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.registry.core.Collection;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.mgt.UserMgtConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+public class CloudServicesUtil {
+
+    private static final Log log = LogFactory.getLog(CloudServicesUtil.class);
+    // TODO protect using Java security
+
+    public static void activateAllServices(CloudServicesDescConfig cloudServicesDesc, int tenantId) throws Exception {
+
+        java.util.Collection<CloudServiceConfig> cloudServiceConfigList =
+                                                                          cloudServicesDesc.getCloudServiceConfigs().
+                                                                                            values();
+        if (cloudServiceConfigList != null) {
+            for (CloudServiceConfig cloudServiceConfig : cloudServiceConfigList) {
+                if (cloudServiceConfig.isDefaultActive()) {
+                    String cloudServiceName = cloudServiceConfig.getName();
+                    try {
+                        if (!CloudServicesUtil.isCloudServiceActive(cloudServiceName, tenantId)) {
+                            CloudServicesUtil.setCloudServiceActive(true,
+                                                                    cloudServiceName,
+                                                                    tenantId,
+                                                                    cloudServicesDesc.getCloudServiceConfigs().
+                                                                                      get(cloudServiceName));
+                        }
+                    } catch (Exception e) {
+                        String msg = "Error in activating the cloud service at the tenant" +
+                                     "creation. tenant id: " + tenantId + ", service name: " +
+                                     cloudServiceName;
+                        log.error(msg, e);
+                        throw new UserStoreException(msg, e);
+                    }
+                }
+            }
+        }     
+    }
+
+    public static void activateOriginalAndCompulsoryServices(CloudServicesDescConfig cloudServicesDesc,
+                                                             String originalService,
+                                                             int tenantId) throws Exception {
+
+        Map<String, CloudServiceConfig> cloudServiceConfigs =
+                                                              cloudServicesDesc.getCloudServiceConfigs();
+        if (CloudServicesUtil.isServiceNameValid(cloudServicesDesc, originalService)) {
+            if (!CloudServicesUtil.isCloudServiceActive(originalService, tenantId)) {
+                CloudServicesUtil.setCloudServiceActive(true, originalService, tenantId,
+                                                        cloudServiceConfigs.get(originalService));
+                log.info("Successfully activated the " + originalService + " for the tenant " +
+                         tenantId);
+            }
+            // register the compulsory services
+            if (!CloudServicesUtil.isCloudServiceActive(StratosConstants.CLOUD_IDENTITY_SERVICE,
+                                                        tenantId)) {
+                CloudServicesUtil.setCloudServiceActive(true,
+                                                        StratosConstants.CLOUD_IDENTITY_SERVICE,
+                                                        tenantId,
+                                                        cloudServiceConfigs.get(StratosConstants.CLOUD_IDENTITY_SERVICE));
+            }
+            if (!CloudServicesUtil.isCloudServiceActive(StratosConstants.CLOUD_GOVERNANCE_SERVICE,
+                                                        tenantId)) {
+                CloudServicesUtil.setCloudServiceActive(true,
+                                                        StratosConstants.CLOUD_GOVERNANCE_SERVICE,
+                                                        tenantId,
+                                                        cloudServiceConfigs.get(StratosConstants.CLOUD_GOVERNANCE_SERVICE));
+            }
+        } else {
+            log.warn("Unable to activate the " + originalService + " for the tenant " + tenantId);
+        }
+
+    }
+
+    public static void setCloudServiceActive(boolean active,
+                                             String cloudServiceName,
+                                             int tenantId, CloudServiceConfig cloudServiceConfig)
+                                                                                                 throws Exception {
+        if (cloudServiceConfig.getLabel() == null) {
+            // for the non-labled services, we are not setting/unsetting the
+            // service active
+            return;
+        }
+
+        UserRegistry govRegistry =
+                CloudCommonServiceComponent.getGovernanceSystemRegistry(
+                        MultitenantConstants.SUPER_TENANT_ID);
+        UserRegistry configRegistry = CloudCommonServiceComponent.getConfigSystemRegistry(tenantId);
+        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
+                                      RegistryConstants.PATH_SEPARATOR + tenantId +
+                                      RegistryConstants.PATH_SEPARATOR + cloudServiceName;
+        
+        Resource cloudServiceInfoResource;
+        if (govRegistry.resourceExists(cloudServiceInfoPath)) {
+            cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
+        } else {
+            cloudServiceInfoResource = govRegistry.newCollection();
+        }
+        cloudServiceInfoResource.setProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY,
+                                             active ? "true" : "false");
+        govRegistry.put(cloudServiceInfoPath, cloudServiceInfoResource);
+
+        // then we will copy the permissions
+        List<PermissionConfig> permissionConfigs = cloudServiceConfig.getPermissionConfigs();
+        for (PermissionConfig permissionConfig : permissionConfigs) {
+            String path = permissionConfig.getPath();
+            String name = permissionConfig.getName();
+            if (active) {
+                if (!configRegistry.resourceExists(path)) {
+                    Collection collection = configRegistry.newCollection();
+                    collection.setProperty(UserMgtConstants.DISPLAY_NAME, name);
+                    configRegistry.put(path, collection);
+                }
+            } else {
+                if (configRegistry.resourceExists(path)) {
+                    configRegistry.delete(path);
+                }
+            }
+        }
+    }
+
+    public static boolean isCloudServiceActive(String cloudServiceName,
+                                               int tenantId) throws Exception {
+        UserRegistry govRegistry = CloudCommonServiceComponent.getGovernanceSystemRegistry(
+                                                                                           MultitenantConstants.SUPER_TENANT_ID);
+        return isCloudServiceActive(cloudServiceName, tenantId, govRegistry);
+    }
+
+    public static boolean isCloudServiceActive(String cloudServiceName,
+                                               int tenantId, UserRegistry govRegistry)
+                                                                                      throws Exception {
+        // The cloud manager is always active
+        if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
+            return true;
+        }
+
+        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
+                                      RegistryConstants.PATH_SEPARATOR + tenantId +
+                                      RegistryConstants.PATH_SEPARATOR + cloudServiceName;
+        Resource cloudServiceInfoResource;
+        if (govRegistry.resourceExists(cloudServiceInfoPath)) {
+            cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
+            String isActiveStr =
+                                 cloudServiceInfoResource.getProperty(
+                                                         StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
+            return "true".equals(isActiveStr);
+        }
+        return false;
+    }
+
+    public static boolean isServiceNameValid(CloudServicesDescConfig cloudServicesDesc,
+                                               String cloudServiceName) {
+        if(cloudServiceName == null) {
+            return false;
+        }
+        java.util.Collection<CloudServiceConfig> cloudServiceConfigList =
+                cloudServicesDesc.getCloudServiceConfigs().values();
+        if (cloudServiceName.equals(StratosConstants.CLOUD_MANAGER_SERVICE)) {
+            return false;
+        }
+        for (CloudServiceConfig cloudServiceConfig : cloudServiceConfigList) {
+            if (cloudServiceConfig.getName().equals(cloudServiceName)) {
+                return true;
+            }
+        }
+        return false;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CommonUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CommonUtil.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CommonUtil.java
new file mode 100644
index 0000000..8adf1e4
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/CommonUtil.java
@@ -0,0 +1,623 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.util;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.registry.core.ActionConstants;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.registry.core.utils.AccessControlConstants;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.core.AuthorizationManager;
+import org.wso2.carbon.user.core.UserRealm;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.text.DateFormat;
+import java.text.DateFormatSymbols;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.regex.Pattern;
+
+/**
+ * Common Utility methods for Stratos.
+ * Now this class has been growing with several util methods - Should refactor accordingly.
+ */
+public class CommonUtil {
+    private static final Log log = LogFactory.getLog(CommonUtil.class);
+    private static StratosConfiguration stratosConfig;
+    private static String eula;
+
+
+    private static final String ILLEGAL_CHARACTERS_FOR_EMAIL =
+            ".*[\\(\\)\\<\\>\\,\\;\\:\\\\\\\"\\[\\]].*";
+    private static final String EMAIL_FILTER_STRING = "^[^@]+@[^@.]+\\.[^@]*\\w\\w$";
+    private static Pattern emailFilterPattern = Pattern.compile(EMAIL_FILTER_STRING);
+    private static Pattern illegalCharactersPatternForEmail = Pattern
+            .compile(ILLEGAL_CHARACTERS_FOR_EMAIL);
+
+    public static StratosConfiguration getStratosConfig() {
+        return stratosConfig;
+    }
+
+    public static void setStratosConfig(StratosConfiguration stratosConfig) {
+        CommonUtil.stratosConfig = stratosConfig;
+    }
+
+    public static String getEula() {
+        return eula;
+    }
+
+    public static void setEula(String eula) {
+        CommonUtil.eula = eula;
+    }
+
+    /**
+     * Checks whether the email validation is mandatory from the configuration file.
+     *
+     * @return true, if the email validation is mandatory to login. Default is false.
+     */
+    public static boolean isEmailValidationMandatory() {
+        boolean isEmailValidationMandatory = false; //false by default.
+        if (stratosConfig != null) {   //make sure the configuration exists.
+            isEmailValidationMandatory = stratosConfig.getEmailValidationRequired();
+        }
+        return isEmailValidationMandatory;
+    }
+
+    /**
+     * Checks whether the email sending is enabled from the configuration file.
+     *
+     * @return true, if the email sending is disabled. By default, this is disabled, and tenant
+     * activation is done without any email sending.
+     */
+    public static boolean isTenantManagementEmailsDisabled() {
+        boolean isEmailsDisabled = true; //true by default.
+        if (stratosConfig != null) {   //make sure the configuration exists.
+            isEmailsDisabled = stratosConfig.isEmailsDisabled();
+        }
+        return isEmailsDisabled;
+    }
+
+    public static String getSuperAdminEmail() {
+        return stratosConfig.getSuperAdminEmail();
+    }
+
+    public static String getAdminUserName() {
+        return stratosConfig.getAdminUserName();
+    }
+    
+    public static String getAdminPassword() {
+        return stratosConfig.getAdminPassword();
+    }
+
+    public static boolean isTenantActivationModerated() {
+        return stratosConfig.isTenantActivationModerated();
+    }
+
+    public static boolean isChargedOnRegistration() {
+        return stratosConfig.isChargeOnRegistration();
+    }
+
+    /**
+     * Checks whether it is for the public cloud setup or Mars.
+     *
+     * @return true, if it is not for the private cloud setups. Default is true.
+     */
+    public static boolean isPublicCloudSetup() {
+        boolean isPublicCloudSetup = true;  // true by default.
+        if (stratosConfig != null) { //make sure the configuration exists.
+            isPublicCloudSetup = stratosConfig.isPublicCloudSetup();
+        }
+        return isPublicCloudSetup;
+    }
+
+    /**
+     * Gets the notification email address of the admin upon the tenant creation.
+     *
+     * @return notification email address for the tenant creations.
+     */
+    public static String getNotificationEmailAddress() {
+        String notificationEmailAddress = "";
+        if (stratosConfig != null) {
+            notificationEmailAddress = stratosConfig.getNotificationEmail();
+            try {
+                validateEmail(notificationEmailAddress);
+            } catch (Exception e) {
+                if (log.isWarnEnabled()) {
+                    log.warn("Invalid Email Address provided for tenant creation notification. " +
+                             "Please check whether the parameter NotificationEmail" +
+                             " is set properly in " +
+                             StratosConstants.STRATOS_CONF_FILE, e);
+                }
+                return "";
+            }
+        }
+        return notificationEmailAddress;
+    }
+
+    public static String getMonthString(Calendar calendar) {
+        int currentMonth = calendar.get(Calendar.MONTH);
+
+        String[] monthArr = new DateFormatSymbols().getMonths();
+        String month = monthArr[currentMonth];
+        return calendar.get(Calendar.YEAR) + "-" + month;
+    }
+
+    public static String getMonthString(int relativeMonth) {
+        Calendar newCalendar = Calendar.getInstance();
+        newCalendar.add(Calendar.MONTH, relativeMonth);
+
+        return CommonUtil.getMonthString(newCalendar);
+    }
+
+    public static Date getDateFromMonthString(String yearMonth) throws ParseException {
+        DateFormat yearMonthFormat = new SimpleDateFormat("yyyy-MMM");
+        return yearMonthFormat.parse(yearMonth);
+    }
+
+    public static String getCurrentMonthString() {
+        Calendar newCalendar = Calendar.getInstance();
+
+        return CommonUtil.getMonthString(newCalendar);
+    }
+
+
+    public static void setAnonAuthorization(String path, UserRealm userRealm)
+            throws RegistryException {
+
+        if (userRealm == null) {
+            return;
+        }
+
+        try {
+            AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
+            String everyoneRole = CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME;
+
+            accessControlAdmin.authorizeRole(everyoneRole, path, ActionConstants.GET);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
+            accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);
+
+        } catch (UserStoreException e) {
+            String msg = "Could not set authorizations for the " + path + ".";
+            log.error(msg, e);
+            throw new RegistryException(msg);
+        }
+    }
+
+    public static void denyAnonAuthorization(String path, UserRealm userRealm)
+            throws RegistryException {
+        if (userRealm == null) {
+            return;
+        }
+
+        try {
+            AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
+            RealmConfiguration realmConfig;
+            try {
+                realmConfig = userRealm.getRealmConfiguration();
+            } catch (UserStoreException e) {
+                String msg = "Failed to retrieve realm configuration.";
+                log.error(msg, e);
+                throw new RegistryException(msg, e);
+            }
+
+            String everyoneRole = realmConfig.getEveryOneRoleName();
+
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.GET);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
+            accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);
+
+        } catch (UserStoreException e) {
+            String msg = "Could not clear authorizations for the " + path + ".";
+            log.error(msg, e);
+            throw new RegistryException(msg);
+        }
+    }
+
+    /**
+     * builds the OMElement from the given inputStream
+     *
+     * @param inputStream, given input - inputStream
+     * @return OMElement
+     * @throws Exception, if building OMElement from the inputStream failed.
+     */
+    public static OMElement buildOMElement(InputStream inputStream) throws Exception {
+        XMLStreamReader parser;
+        try {
+            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+        } catch (XMLStreamException e) {
+            String msg = "Error in initializing the parser to build the OMElement.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        // create the builder
+        StAXOMBuilder builder = new StAXOMBuilder(parser);
+        // get the root element (in this case the envelope)
+
+        return builder.getDocumentElement();
+    }
+
+
+    /**
+     * validates the email
+     *
+     * @param email - email address
+     * @throws Exception, if validation failed
+     */
+    public static void validateEmail(String email) throws Exception {
+        if (email == null) {
+            String msg = "Provided email value is null.";
+            log.warn(msg);
+            throw new Exception(msg);
+        }
+        email = email.trim();
+        if ("".equals(email)) {
+            String msg = "Provided email value is empty.";
+            log.warn(msg);
+            throw new Exception(msg);
+        }
+        if (illegalCharactersPatternForEmail.matcher(email).matches()) {
+            String msg = "Wrong characters in the email.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        if (!emailFilterPattern.matcher(email).matches()) {
+            String msg = "Invalid email address is provided.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+    }
+
+    /**
+     * @param name     validate the name.
+     * @param variable entry name.
+     * @throws Exception if empty
+     */
+    public static void validateName(String name, String variable) throws Exception {
+        if (name.trim().equals("")) {
+            String msg = variable + " is not provided.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+    }
+
+    /**
+     * validates domain from the successkey
+     *
+     * @param governanceSystemRegistry - The governance system registry
+     * @param domain                   - tenant domain
+     * @param successKey               - successkey
+     * @return true, if successfully validated
+     * @throws RegistryException, if validation failed
+     */
+    public static boolean validateDomainFromSuccessKey(UserRegistry governanceSystemRegistry,
+                                                       String domain, String successKey)
+            throws RegistryException {
+        String domainValidatorInfoPath =
+                StratosConstants.DOMAIN_VALIDATOR_INFO_PATH + RegistryConstants.PATH_SEPARATOR +
+                domain + RegistryConstants.PATH_SEPARATOR +
+                StratosConstants.VALIDATION_KEY_RESOURCE_NAME;
+        if (governanceSystemRegistry.resourceExists(domainValidatorInfoPath)) {
+            Resource resource = governanceSystemRegistry.get(domainValidatorInfoPath);
+            String actualSuccessKey = resource.getProperty("successKey");
+            if (actualSuccessKey != null && successKey != null &&
+                actualSuccessKey.trim().equals(successKey.trim())) {
+                // the domain is correct
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Returns the configurations from the stratos configuration file.
+     *
+     * @return stratos configurations
+     */
+    public static StratosConfiguration loadStratosConfiguration() {
+        // gets the configuration file name from the StratosConstants.
+        String StratosConfigFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + 
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                StratosConstants.STRATOS_CONF_FILE;
+        return loadStratosConfiguration(StratosConfigFileName);
+    }
+
+    /**
+     * Loads the given Stratos Configuration file.
+     *
+     * @param configFilename Name of the configuration file
+     * @return the stratos configuration data.
+     */
+    private static StratosConfiguration loadStratosConfiguration(String configFilename) {
+        StratosConfiguration config = new StratosConfiguration();
+        File configFile = new File(configFilename);
+        if (configFile.exists()) {
+            FileInputStream inputStream = null;
+            try {
+                inputStream = new FileInputStream(configFile);
+                XMLStreamReader parser =
+                        XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+                StAXOMBuilder builder = new StAXOMBuilder(parser);
+                OMElement documentElement = builder.getDocumentElement();
+                Iterator it = documentElement.getChildElements();
+                while (it.hasNext()) {
+                    OMElement element = (OMElement) it.next();
+
+                    if ("DisableTenantManagementEmails".equals(element.getLocalName())) {
+                        String disableEmails = element.getText();
+                        // by default, make the email validation mandatory.
+                        boolean isEmailsDisabled = true;
+                        if (disableEmails.trim().equalsIgnoreCase("false")) {
+                            isEmailsDisabled = false;
+                        }
+                        config.setEmailsDisabled(isEmailsDisabled);
+                    }
+                    // Checks whether Email Validation is mandatory to log in and use the registered
+                    // tenants.
+                    else if ("EmailValidationMandatoryForLogin".equals(element.getLocalName())) {
+                        String emailValidation = element.getText();
+                        //by default, make the email validation not mandatory.
+                        boolean isEmailValidationRequired = false;
+                        if (emailValidation.trim().equalsIgnoreCase("true")) {
+                            isEmailValidationRequired = true;
+                        }
+                        config.setEmailValidationRequired(isEmailValidationRequired);
+                    } else if ("ChargeOnRegistration".equals(element.getLocalName())) {
+                        String chargeOnRegistration = element.getText();
+                        boolean isChargedOnRegistration = false;
+                        if (chargeOnRegistration.trim().equalsIgnoreCase("true")) {
+                            isChargedOnRegistration = true;
+                        }
+                        config.setChargeOnRegistration(isChargedOnRegistration);
+                    } else if ("NotificationEmail".equals(element.getLocalName())) {
+                        config.setNotificationEmail(element.getText());
+                    } else if ("SuperAdminEmail".equals(element.getLocalName())) {
+                        config.setSuperAdminEmail(element.getText());
+                    } else if ("TenantActivationModerated".equals(element.getLocalName())){
+                        String isTenantActivationModerated = element.getText();
+                        boolean tenantActivationModerated = false;
+                        if (isTenantActivationModerated.trim().equalsIgnoreCase("true")) {
+                            tenantActivationModerated = true;
+                        }
+                        config.setTenantActivationModerated(tenantActivationModerated);
+                    }
+                    //Checks whether it is public cloud deployment.
+                    else if ("StratosPublicCloudSetup".equals(element.getLocalName())) {
+                        String cloudSetup = element.getText();
+                        //by default, make the email validation mandatory.
+                        boolean isStratosPublicCloudSetup = true;
+                        if (cloudSetup.trim().equalsIgnoreCase("false")) {
+                            isStratosPublicCloudSetup = false;
+                        }
+                        config.setPublicCloudSetup(isStratosPublicCloudSetup);
+                        //Setting the paypal url
+                    } else if ("PaypalUrl".equals(element.getLocalName())) {
+                        String paypalUrl = element.getText();
+                        config.setPaypalUrl(paypalUrl);
+                    } else if ("SkipSummaryGenerator".equals(element.getLocalName())) {
+                        String summaryGenerator = element.getText();
+                        boolean skipSummaryGenerator = false;
+                        if (summaryGenerator.trim().equalsIgnoreCase("true")) {
+                            skipSummaryGenerator = true;
+                        }
+                        config.setSkipSummaryGenerator(skipSummaryGenerator);
+                    }
+                    else if ("PaypalAPIUsername".equals(element.getLocalName())) {
+                        config.setPaypalAPIUsername(element.getText());
+                    } else if ("PaypalAPIPassword".equals(element.getLocalName())) {
+                        config.setPaypalAPIPassword(element.getText());
+                    } else if ("PaypalAPISignature".equals(element.getLocalName())) {
+                        config.setPaypalAPISignature(element.getText());
+                    }else if ("PaypalEnvironment".equals(element.getLocalName())){
+                        config.setPaypalEnvironment(element.getText());
+                    }else if("FinanceNotificationEmail".equals(element.getLocalName())){
+                        config.setFinanceNotificationEmail(element.getText());    
+                    }else if("UsagePlanUrl".equals(element.getLocalName())){
+                        config.setUsagePlanURL(element.getText());
+                    }else if("PaidJIRAUrl".equals(element.getLocalName())) {
+                        config.setPaidJIRAUrl(element.getText());
+                    }else if("PaidJIRAProject".equals(element.getLocalName())) {
+                        config.setPaidJIRAProject(element.getText());
+                    }else if("ForumUrl".equals(element.getLocalName())) {
+                        config.setForumUrl(element.getText());
+                    }else if("PaidUserGroup".equals(element.getLocalName())) {
+                        config.setPaidUserGroup(element.getText());
+                    }else if("NonpaidUserGroup".equals(element.getLocalName())) {
+                        config.setNonpaidUserGroup(element.getText());
+                    } else if("SupportInfoUrl".equals(element.getLocalName())) {
+                        config.setSupportInfoUrl(element.getText());
+                    }else if("IncidentCustomFieldId".equals(element.getLocalName())) {
+                        config.setIncidentCustomFieldId(element.getText());
+                    } else if("IncidentImpactCustomFieldId".equals(element.getLocalName())) {
+                        config.setIncidentImpactCustomFieldId(element.getText());
+                    } else if ("GoogleAnalyticsURL".equals(element.getLocalName())) {
+                        config.setGoogleAnalyticsURL(element.getText());
+                    } else if("StratosEventListener".equals(element.getLocalName())) {
+                        populateEventListenerProperties(config, element);
+                    } else if ("managerServiceUrl".equals(element.getLocalName())) {
+                        config.setManagerServiceUrl(element.getText());
+                    } else if ("adminUserName".equals(element.getLocalName())) {
+                        config.setAdminUserName(element.getText());
+                    } else if ("adminPassword".equals(element.getLocalName())) {
+                        config.setAdminPassword(element.getText());
+                    } else if("SSOLoadingMessage".equals(element.getLocalName())){
+                        config.setSsoLoadingMessage(element.getText());
+                    }
+                }
+                return config;
+            } catch (Exception e) {
+                String msg = "Error in loading Stratos Configurations File: " + configFilename + ".";
+                log.error(msg, e);
+                return config; //returns the default configurations, if the file could not be loaded.
+            } finally {
+                if (inputStream != null) {
+                    try {
+                        inputStream.close();
+                    } catch (IOException e) {
+                        log.error("Could not close the Configuration File " + configFilename);
+                    }
+                }
+            }
+        }
+        log.error("Unable to locate the stratos configurations file. " +
+                  "Default Settings will be used.");
+        return config; // return the default configuratiosn, if the file not found.
+    }
+    
+    
+    private static void populateEventListenerProperties(StratosConfiguration config,
+                                                        OMElement element) throws RegistryException {
+        config.setStratosEventListenerName(element.getAttributeValue(new QName("class")));
+        Iterator<?> ite =
+                          element.getChildrenWithName(new QName("Property"));
+        while (ite.hasNext()) {
+            OMElement propElem = (OMElement) ite.next();
+            String propName = propElem.getAttributeValue(new QName("name"));
+            String propValue = propElem.getText();
+            config.setStratosEventListenerProperty(propName, propValue);
+        }
+    }
+
+    /**
+     * Loading the EULA.
+     * ultimately we shall be loading the eula from the web page itself.
+     * But loading from file should be there to customize the EULA based on the private deployments,
+     * etc.
+     *
+     * @return eula
+     */
+    public static String loadTermsOfUsage() {
+        // currently loads from the file; gets the eula file name from the StratosConstants.
+        String StratosEULAFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                StratosConstants.STRATOS_EULA;
+        return loadTermsOfUsage(StratosEULAFileName);
+    }
+
+    private static String loadTermsOfUsage(String eulaFile) {
+        String eula = StratosConstants.STRATOS_EULA_DEFAULT_TEXT;
+        File configFile = new File(eulaFile);
+        if (configFile.exists()) {
+            FileInputStream inputStream = null;
+            try {
+                inputStream = new FileInputStream(configFile);
+                XMLStreamReader parser =
+                        XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+                StAXOMBuilder builder = new StAXOMBuilder(parser);
+                OMElement documentElement = builder.getDocumentElement();
+                Iterator it = documentElement.getChildElements();
+                while (it.hasNext()) {
+                    OMElement element = (OMElement) it.next();
+
+                    //Checks whether Email Validation is mandatory for tenant registration complete.
+                    if ("EULA".equalsIgnoreCase(element.getLocalName())) {
+                        eula = element.getText();
+                    }
+                }
+                return eula;
+            } catch (Exception e) {
+                String msg = "Error in loading Stratos Terms and Conditions File.";
+                log.error(msg, e);
+                return eula; //returns the default text, if the file could not be loaded.
+            } finally {
+                if (inputStream != null) {
+                    try {
+                        inputStream.close();
+                    } catch (IOException e) {
+                        log.error("Could not close the EULA File " + eulaFile);
+                    }
+                }
+            }
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Unable to locate the stratos EULA file. Default value will be used.");
+        }
+        return eula; // return the default, if the file not found.
+    }
+
+
+    /**
+     * method to check whether a domain name is available to register given a domain name
+     * @param tenantDomain, domain name
+     * @return true, if the domain is available to register
+     * @throws Exception, if checking the existence of the tenant is failed.
+     */
+    public static boolean isDomainNameAvailable(String tenantDomain) throws Exception {
+
+        TenantManager tenantManager = CloudCommonServiceComponent.getTenantManager();
+          // The registry reserved words are checked first.
+          if (tenantDomain.equals("atom") || tenantDomain.equals("registry")
+                  || tenantDomain.equals("resource")) {
+              String msg = "You can not use a registry reserved word:" + tenantDomain +
+                           ":as a tenant domain. Please choose a different one.";
+              log.error(msg);
+              throw new Exception(msg);
+          }
+
+          int tenantId;
+          try {
+              tenantId = tenantManager.getTenantId(tenantDomain);
+          } catch (UserStoreException e) {
+              String msg = "Error in getting the tenant id for the given domain  " +
+                           tenantDomain + ".";
+              log.error(msg);
+              throw new Exception(msg, e);
+          }
+
+          // check a tenant with same domain exist.
+          if ((tenantId != MultitenantConstants.INVALID_TENANT_ID && tenantId != MultitenantConstants.SUPER_TENANT_ID) ||
+                  tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
+              String msg =
+                           "A tenant with same domain already exist. " +
+                                   "Please use a different domain name. tenant domain: " +
+                                   tenantDomain + ".";
+              log.info(msg);
+              return false;
+          }
+          return true;
+      }
+}
+
+
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java
new file mode 100644
index 0000000..4dc269e
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/MeteringAccessValidationUtils.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.util;
+
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+public class MeteringAccessValidationUtils {
+
+	public static final String ERROR_MSG_PROPERTY_KEY_POST_FIX = "error_msg";
+	public static final String IS_BLOCKED_PROPERTY_KEY_POST_FIX = "is_blocked";
+
+	public static String generateIsBlockedPropertyKey(String action) {
+		return action + "_" + IS_BLOCKED_PROPERTY_KEY_POST_FIX;
+	}
+
+	public static String generateErrorMsgPropertyKey(String action) {
+		return action + "_" + ERROR_MSG_PROPERTY_KEY_POST_FIX;
+	}
+
+	public static Set<String> getAvailableActions(Properties properties) {
+		Set propertyKeys = properties.keySet();
+		Set<String> actions = new HashSet<String>();
+		for (Object propertyKeyObj : propertyKeys) {
+			String propertyKey = (String) propertyKeyObj;
+			if (propertyKey.endsWith(IS_BLOCKED_PROPERTY_KEY_POST_FIX)) {
+			    // -1 for the length of the '_'
+				String action =
+				        propertyKey.substring(0, propertyKey.length() -
+				                IS_BLOCKED_PROPERTY_KEY_POST_FIX.length() - 1);
+				actions.add(action);
+			}
+		}
+		return actions;
+	}
+}


[03/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantRegistryDataDeletionUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantRegistryDataDeletionUtil.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantRegistryDataDeletionUtil.java
deleted file mode 100644
index f640c65..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantRegistryDataDeletionUtil.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-
-package org.apache.stratos.tenant.mgt.util;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-
-public class TenantRegistryDataDeletionUtil {
-    public static final Log log = LogFactory.getLog(TenantRegistryDataDeletionUtil.class);
-    
-    /**
-     * Delete all tenant information related to tenant stored in REG tables
-     * @param tenantId id of tenant whose data should be deleted
-     * @param conn database connection object
-     * @throws SQLException thrown if an error occurs while executing the queries 
-     */
-    public static void deleteTenantRegistryData(int tenantId, Connection conn) throws Exception {
-        try {
-            conn.setAutoCommit(false);
-            String deleteClusterLockSql = "DELETE FROM REG_CLUSTER_LOCK WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteClusterLockSql, tenantId);
-
-            String deleteLogSql = "DELETE FROM REG_LOG WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteLogSql, tenantId);
-
-            String deleteAssociationSql = "DELETE FROM REG_ASSOCIATION WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteAssociationSql, tenantId);
-
-            String deleteSnapshotSql = "DELETE FROM REG_SNAPSHOT WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteSnapshotSql, tenantId);
-
-            String deleteResourceCommentSql = "DELETE FROM REG_RESOURCE_COMMENT WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteResourceCommentSql, tenantId);
-
-            String deleteCommentSql = "DELETE FROM REG_COMMENT WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteCommentSql, tenantId);
-
-            String deleteResourceRatingSql = "DELETE FROM REG_RESOURCE_RATING WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteResourceRatingSql, tenantId);
-
-            String deleteRatingSql = "DELETE FROM REG_RATING WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteRatingSql, tenantId);
-
-            String deleteResourceTagSql = "DELETE FROM REG_RESOURCE_TAG WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteResourceTagSql, tenantId);
-
-            String deleteTagSql = "DELETE FROM REG_TAG WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteTagSql, tenantId);
-
-            String deleteResourcePropertySql = "DELETE FROM REG_RESOURCE_PROPERTY WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteResourcePropertySql, tenantId);
-
-            String deletePropertySql = "DELETE FROM REG_PROPERTY WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deletePropertySql, tenantId);
-
-            String deleteResourceHistorySql = "DELETE FROM REG_RESOURCE_HISTORY WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteResourceHistorySql, tenantId);
-
-            String deleteContentHistorySql = "DELETE FROM REG_CONTENT_HISTORY WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteContentHistorySql, tenantId);
-
-            String deleteResourceSql = "DELETE FROM REG_RESOURCE WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteResourceSql, tenantId);
-
-            String deleteContentSql = "DELETE FROM REG_CONTENT WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteContentSql, tenantId);
-
-            String deletePathSql = "DELETE FROM REG_PATH WHERE REG_TENANT_ID = ?";
-            executeDeleteQuery(conn, deletePathSql, tenantId);
-
-            conn.commit();
-        } catch (SQLException e) {
-            conn.rollback();
-            String errorMsg = "An error occurred while deleting registry data for tenant: " + tenantId;
-            log.error(errorMsg, e);
-            throw new Exception(errorMsg, e);
-        } finally {
-            conn.close();
-        }
-    }
-
-    private static void executeDeleteQuery(Connection conn, String query, int tenantId)
-            throws Exception {
-        PreparedStatement ps = null;
-        try {
-            ps = conn.prepareStatement(query);
-            ps.setInt(1, tenantId);
-            ps.executeUpdate();
-        } catch (SQLException e) {
-            String errMsg = "Error executing query " + query + " for tenant: " + tenantId;
-            log.error(errMsg, e);
-            throw new Exception(errMsg, e);
-        } finally {
-            if (ps != null) {
-                ps.close();
-            }
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantUMDataDeletionUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantUMDataDeletionUtil.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantUMDataDeletionUtil.java
deleted file mode 100644
index d857e38..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/util/TenantUMDataDeletionUtil.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.tenant.mgt.util;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-
-public class TenantUMDataDeletionUtil {
-    public static final Log log = LogFactory.getLog(TenantUMDataDeletionUtil.class);
-
-    /**
-     * Delete all tenant information related to tenant stored in UM tables
-     * @param tenantId id of tenant whose data should be deleted
-     * @param conn database connection object
-     * @throws SQLException thrown if an error occurs while executing the queries
-     */
-    public static void deleteTenantUMData(int tenantId, Connection conn) throws Exception {
-        try {
-            conn.setAutoCommit(false);
-            String deleteUserPermissionSql = "DELETE FROM UM_USER_PERMISSION WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteUserPermissionSql, tenantId);
-
-            String deleteRolePermissionSql = "DELETE FROM UM_ROLE_PERMISSION WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteRolePermissionSql, tenantId);
-
-            String deletePermissionSql = "DELETE FROM UM_PERMISSION WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deletePermissionSql, tenantId);
-
-            String deleteClaimBehaviourSql = "DELETE FROM UM_CLAIM_BEHAVIOR WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteClaimBehaviourSql, tenantId);
-
-            String deleteProfileConfigSql = "DELETE FROM UM_PROFILE_CONFIG WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteProfileConfigSql, tenantId);
-
-            String deleteClaimSql = "DELETE FROM UM_CLAIM WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteClaimSql, tenantId);
-
-            String deleteDialectSql = "DELETE FROM UM_DIALECT WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteDialectSql, tenantId);
-
-            String deleteUserAttributeSql = "DELETE FROM UM_USER_ATTRIBUTE WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteUserAttributeSql, tenantId);
-
-            String deleteHybridUserRoleSql = "DELETE FROM UM_HYBRID_USER_ROLE WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteHybridUserRoleSql, tenantId);
-
-            String deleteHybridRoleSql = "DELETE FROM UM_HYBRID_ROLE WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteHybridRoleSql, tenantId);
-
-            String deleteHybridRememberMeSql = "DELETE FROM UM_HYBRID_REMEMBER_ME WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteHybridRememberMeSql, tenantId);
-
-            String deleteUserRoleSql = "DELETE FROM UM_USER_ROLE WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteUserRoleSql, tenantId);
-
-            String deleteRoleSql = "DELETE FROM UM_ROLE WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteRoleSql, tenantId);
-
-            String deleteUserSql = "DELETE FROM UM_USER WHERE UM_TENANT_ID = ?";
-            executeDeleteQuery(conn, deleteUserSql, tenantId);
-
-            String deleteTenantSql = "DELETE FROM UM_TENANT WHERE UM_ID = ?";
-            executeDeleteQuery(conn, deleteTenantSql, tenantId);
-
-            conn.commit();
-        } catch (Exception e) {
-            conn.rollback();
-            String errorMsg = "An error occurred while deleting registry data for tenant: " + tenantId;
-            log.error(errorMsg, e);
-            throw new Exception(errorMsg, e);
-        } finally {
-            conn.close();
-        }
-    }
-
-    private static void executeDeleteQuery(Connection conn, String query, int tenantId)
-            throws Exception {
-        PreparedStatement ps = null;
-        try {
-            ps = conn.prepareStatement(query);
-            ps.setInt(1, tenantId);
-            ps.executeUpdate();
-        } catch (SQLException e) {
-            String errMsg = "Error executing query " + query + " for tenant: " + tenantId;
-            log.error(errMsg, e);
-            throw new Exception(errMsg, e);
-        } finally {
-            if (ps != null) {
-                ps.close();
-            }
-        }
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/resources/META-INF/component.xml b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/resources/META-INF/component.xml
deleted file mode 100644
index 883930f..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/resources/META-INF/component.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  ~  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-  ~
-  ~  Licensed under the Apache License, Version 2.0 (the "License");
-  ~  you may not use this file except in compliance with the License.
-  ~  You may obtain a copy of the License at
-  ~
-  ~       http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~  Unless required by applicable law or agreed to in writing, software
-  ~  distributed under the License is distributed on an "AS IS" BASIS,
-  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~  See the License for the specific language governing permissions and
-  ~  limitations under the License.
-  -->
-
-<component xmlns="http://products.wso2.org/carbon">
-    <ManagementPermissions>
-        <ManagementPermission>
-            <DisplayName>Manage</DisplayName>
-            <ResourceId>/permission/protected/manage</ResourceId>
-        </ManagementPermission>
-        <ManagementPermission>
-            <DisplayName>Monitor</DisplayName>
-            <ResourceId>/permission/protected/manage/monitor</ResourceId>
-        </ManagementPermission>
-        <ManagementPermission>
-            <DisplayName>Tenants</DisplayName>
-            <ResourceId>/permission/protected/manage/monitor/tenants</ResourceId>
-        </ManagementPermission>
-        <ManagementPermission>
-            <DisplayName>Modify</DisplayName>
-            <ResourceId>/permission/protected/manage/modify</ResourceId>
-        </ManagementPermission>
-        <ManagementPermission>
-            <DisplayName>Tenants</DisplayName>
-            <ResourceId>/permission/protected/manage/modify/tenants</ResourceId>
-        </ManagementPermission>
-   </ManagementPermissions>
-</component>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/resources/META-INF/services.xml
deleted file mode 100644
index 7e87c44..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,155 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- !
- ! Copyright 2006 The Apache Software Foundation.
- !
- ! Licensed under the Apache License, Version 2.0 (the "License");
- ! you may not use this file except in compliance with the License.
- ! You may obtain a copy of the License at
- !
- !      http://www.apache.org/licenses/LICENSE-2.0
- !
- ! Unless required by applicable law or agreed to in writing, software
- ! distributed under the License is distributed on an "AS IS" BASIS,
- ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ! See the License for the specific language governing permissions and
- ! limitations under the License.
- !-->
-<serviceGroup>
-
-    <service name="TenantMgtService" scope="transportsession">
-        <transports>
-            <transport>https</transport>
-        </transports>
-        <parameter name="ServiceClass" locked="false">
-            org.apache.stratos.tenant.mgt.services.TenantSelfRegistrationService
-        </parameter>
-        <operation name="registerTenant">
-        </operation>
-        <operation name="checkDomainAvailability">
-        </operation>
-        <operation name="validateOrSuggestDomain">
-        </operation>
-        <operation name="generateRandomCaptcha">
-        </operation>
-    </service>
-
-    <service name="TenantMgtAdminService" scope="transportsession">
-        <transports>
-            <transport>https</transport>
-        </transports>
-        <parameter name="ServiceClass" locked="false">
-            org.apache.stratos.tenant.mgt.services.TenantMgtAdminService
-        </parameter>
-        <operation name="addTenant">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
-        </operation>
-        <operation name="retrieveTenants">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
-        </operation>
-        <operation name="retrievePaginatedTenants">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
-        </operation>
-         <operation name="retrievePartialSearchTenants">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
-        </operation>
-        <operation name="retrievePaginatedPartialSearchTenants">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
-        </operation>
-        <operation name="getTenant">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/monitor/tenants</parameter>
-        </operation>
-        <operation name="updateTenant">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/modify/tenants</parameter>
-        </operation>
-        <operation name="activateTenant">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/modify/tenants</parameter>
-        </operation>
-        <operation name="deactivateTenant">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/modify/tenants</parameter>
-        </operation>
-        <operation name="deleteTenant">
-            <parameter name="superTenantService" locked="true">true</parameter>
-            <parameter name="AuthorizationAction" locked="true">/permission/protected/manage/modify/tenants</parameter>
-        </operation>
-        <parameter name="adminService" locked="true">true</parameter>
-    </service>
-    
-    <service name="GAppTenantRegistrationService">
-        <transports>
-            <transport>https</transport>
-        </transports>
-        <schema schemaNamespace="http://org.apache.axis2/xsd" elementFormDefaultQualified="true"/>
-        <description>Rampart protected service that is used to setup Google Apps domain</description>
-        <parameter name="ServiceClass">org.apache.stratos.tenant.mgt.services.GAppTenantRegistrationService</parameter>
-        <parameter name="adminService" locked="true">false</parameter>
-
-        <module ref="rampart"/>
-
-        <wsp:Policy wsu:Id="SigOnly"
-                    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
-                    xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
-            <wsp:ExactlyOne>
-                <wsp:All>
-                    <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
-                        <wsp:Policy>
-                            <sp:InitiatorToken>
-                                <wsp:Policy>
-                                    <sp:X509Token
-                                            sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
-                                        <wsp:Policy>
-                                            <sp:RequireThumbprintReference/>
-                                            <sp:WssX509V3Token10/>
-                                        </wsp:Policy>
-                                    </sp:X509Token>
-                                </wsp:Policy>
-                            </sp:InitiatorToken>
-                            <sp:RecipientToken>
-                                <wsp:Policy>
-                                    <sp:X509Token
-                                            sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
-                                        <wsp:Policy>
-                                            <sp:RequireThumbprintReference/>
-                                            <sp:WssX509V3Token10/>
-                                        </wsp:Policy>
-                                    </sp:X509Token>
-                                </wsp:Policy>
-                            </sp:RecipientToken>
-                            <sp:AlgorithmSuite>
-                                <wsp:Policy>
-                                    <sp:Basic256/>
-                                </wsp:Policy>
-                            </sp:AlgorithmSuite>
-                            <sp:Layout>
-                                <wsp:Policy>
-                                    <sp:Strict/>
-                                </wsp:Policy>
-                            </sp:Layout>
-                            <sp:IncludeTimestamp/>
-                            <sp:OnlySignEntireHeadersAndBody/>
-                        </wsp:Policy>
-                    </sp:AsymmetricBinding>
-                    <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
-                        <wsp:Policy>
-                            <sp:MustSupportRefKeyIdentifier/>
-                            <sp:MustSupportRefIssuerSerial/>
-                        </wsp:Policy>
-                    </sp:Wss10>
-                    <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
-                        <sp:Body/>
-                    </sp:SignedParts>
-                </wsp:All>
-            </wsp:ExactlyOne>
-        </wsp:Policy>
-    </service>
-    <parameter name="hiddenService" locked="true">true</parameter>
-</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/pom.xml b/components/org.apache.stratos.tenant.mgt/pom.xml
new file mode 100644
index 0000000..27c9b40
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/pom.xml
@@ -0,0 +1,123 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.tenant.mgt</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Tenant Managment</name>
+
+    <build>
+
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Private-Package>
+                            org.apache.stratos.tenant.mgt.internal.*,
+                            org.apache.stratos.tenant.mgt.persistence.*,
+                        </Private-Package>
+                        <Import-Package>
+                            org.apache.stratos.common.*,
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.captcha.mgt.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <Export-Package>
+                            org.apache.stratos.tenant.mgt.beans.*,
+                            org.apache.stratos.tenant.mgt.exception.*,
+                            org.apache.stratos.tenant.mgt.realm.*,
+                            org.apache.stratos.tenant.mgt.services.*,
+                            org.apache.stratos.tenant.mgt.util.*,
+                        </Export-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.core</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+           <groupId>org.apache.stratos</groupId>
+           <artifactId>org.apache.stratos.tenant.mgt.core</artifactId>
+	   <version>${apache.stratos.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+           <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.um.ws.api</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+           <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.captcha.mgt</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+	    <version>${apache.stratos.version}</version>
+        </dependency>
+       
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.admin.mgt</artifactId>
+	    <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.rampart.wso2</groupId>
+            <artifactId>rampart-policy</artifactId>
+	    <version>${rampart.wso2.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.rampart.wso2</groupId>
+            <artifactId>rampart-core</artifactId>
+	    <version>${rampart.wso2.version}</version>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/beans/PaginatedTenantInfoBean.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/beans/PaginatedTenantInfoBean.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/beans/PaginatedTenantInfoBean.java
new file mode 100644
index 0000000..3a16cac
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/beans/PaginatedTenantInfoBean.java
@@ -0,0 +1,52 @@
+/*
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.tenant.mgt.beans;
+
+import org.apache.stratos.common.beans.TenantInfoBean;
+import org.wso2.carbon.utils.Pageable;
+
+import java.util.List;
+
+/**
+ * Bean for paginated tenant information
+ */
+public class PaginatedTenantInfoBean implements Pageable {
+    private TenantInfoBean[] tenantInfoBeans;
+    private int numberOfPages;
+
+    public TenantInfoBean[] getTenantInfoBeans() {
+        return tenantInfoBeans;
+    }
+
+    public void setTenantInfoBeans(TenantInfoBean[] tenantInfoBeans) {
+        this.tenantInfoBeans = tenantInfoBeans;
+    }
+
+    public int getNumberOfPages() {
+        return numberOfPages;
+    }
+    
+    public void setNumberOfPages(int numberOfPages) {
+        this.numberOfPages = numberOfPages;
+    }
+
+    public <T> void set(List<T> items) {
+        this.tenantInfoBeans = items.toArray(new TenantInfoBean[items.size()]);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/exception/TenantManagementException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/exception/TenantManagementException.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/exception/TenantManagementException.java
new file mode 100644
index 0000000..1207f5d
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/exception/TenantManagementException.java
@@ -0,0 +1,33 @@
+/*
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.tenant.mgt.exception;
+
+/**
+ * Tenant Management Specific Exception.
+ */
+public class TenantManagementException extends Exception {
+
+    public TenantManagementException(String msg, Exception e) {
+        super(msg, e);
+    }
+    
+    public TenantManagementException(String msg) {
+        super(msg);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/internal/TenantMgtServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/internal/TenantMgtServiceComponent.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/internal/TenantMgtServiceComponent.java
new file mode 100644
index 0000000..a65d275
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/internal/TenantMgtServiceComponent.java
@@ -0,0 +1,261 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.tenant.mgt.internal;
+
+import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.apache.stratos.common.TenantBillingService;
+import org.apache.stratos.common.listeners.TenantMgtListener;
+import org.apache.stratos.common.util.CommonUtil;
+import org.apache.stratos.common.util.StratosConfiguration;
+import org.apache.stratos.tenant.mgt.internal.util.TenantMgtRampartUtil;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.neethi.Policy;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import org.osgi.service.component.ComponentContext;
+
+/**
+ * @scr.component name="org.apache.stratos.tenant.mgt" immediate="true"
+ * @scr.reference name="registry.service"
+ *                interface="org.wso2.carbon.registry.core.service.RegistryService"
+ *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
+ *                unbind="unsetRegistryService"
+ * @scr.reference name="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1" policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ * @scr.reference name="configuration.context.service"
+ *                interface="org.wso2.carbon.utils.ConfigurationContextService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setConfigurationContextService"
+ *                unbind="unsetConfigurationContextService"
+ * @scr.reference name="org.apache.stratos.tenant.mgt.listener.service"
+ *                interface="org.apache.stratos.common.listeners.TenantMgtListener"
+ *                cardinality="0..n" policy="dynamic"
+ *                bind="setTenantMgtListenerService"
+ *                unbind="unsetTenantMgtListenerService"
+ * @scr.reference name="default.tenant.billing.service"
+ *                interface="org.apache.stratos.common.TenantBillingService"
+ *                cardinality="0..1" policy="dynamic"
+ *                bind="setTenantBillingService"
+ *                unbind="unsetTenantBillingService"
+ * @scr.reference name="default.tenant.persistor"
+ *                interface="org.wso2.carbon.core.multitenancy.persistence.TenantPersistor"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setTenantPersistor"
+ *                unbind="unsetTenantPersistor"
+ */
+public class TenantMgtServiceComponent {
+    private static Log log = LogFactory.getLog(TenantMgtServiceComponent.class);
+
+    private static final String GAPP_TENANT_REG_SERVICE_NAME = "GAppTenantRegistrationService";
+
+    private static RealmService realmService;
+    private static RegistryService registryService;
+    
+    private static ConfigurationContextService configurationContextService;
+    
+    private static List<TenantMgtListener> tenantMgtListeners = new ArrayList<TenantMgtListener>();
+    private static TenantPersistor tenantPersistor = null;
+    private static TenantBillingService billingService = null;
+
+    protected void activate(ComponentContext context) {
+        try {
+
+            // Loading the stratos configurations from Stratos.xml
+            if (CommonUtil.getStratosConfig() == null) {
+                StratosConfiguration stratosConfig = CommonUtil.loadStratosConfiguration();
+                CommonUtil.setStratosConfig(stratosConfig);
+            }
+
+            // Loading the EULA
+            if (CommonUtil.getEula() == null) {
+                String eula = CommonUtil.loadTermsOfUsage();
+                CommonUtil.setEula(eula);
+            }
+            
+            populateRampartConfig(configurationContextService.
+					              getServerConfigContext().getAxisConfiguration());
+
+            log.debug("******* Tenant Config bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("******* Tenant Config bundle failed activating ****", e);
+        }
+    }
+
+    protected void setTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        addTenantMgtListener(tenantMgtListener);
+    }
+
+    protected void unsetTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        removeTenantMgtListener(tenantMgtListener);
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Governance Tenant Config bundle is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        TenantMgtServiceComponent.registryService = registryService;
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        TenantMgtServiceComponent.realmService = realmService;
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        setRealmService(null);
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService configurationContextService) {
+        log.debug("Receiving ConfigurationContext Service");
+        TenantMgtServiceComponent.configurationContextService = configurationContextService;
+
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
+        log.debug("Unsetting ConfigurationContext Service");
+        setConfigurationContextService(null);
+    }
+
+    public static void addTenantMgtListener(TenantMgtListener tenantMgtListener) {
+        tenantMgtListeners.add(tenantMgtListener);
+        sortTenantMgtListeners();
+    }
+
+    public static void removeTenantMgtListener(TenantMgtListener tenantMgtListener) {
+        tenantMgtListeners.remove(tenantMgtListener);
+        sortTenantMgtListeners();
+    }
+
+    public static void sortTenantMgtListeners() {
+        Collections.sort(tenantMgtListeners, new Comparator<TenantMgtListener>() {
+            public int compare(TenantMgtListener o1, TenantMgtListener o2) {
+                return o1.getListenerOrder() - o2.getListenerOrder();
+            }
+        });
+    }
+
+    public static List<TenantMgtListener> getTenantMgtListeners() {
+        return tenantMgtListeners;
+    }
+
+    public static ConfigurationContextService getConfigurationContextService() {
+        return configurationContextService;
+    }
+
+    public static ConfigurationContext getConfigurationContext() {
+        if (configurationContextService.getServerConfigContext() == null) {
+            return null;
+        }
+        return configurationContextService.getServerConfigContext();
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static TenantManager getTenantManager() {
+        return realmService.getTenantManager();
+    }
+
+    public static RealmConfiguration getBootstrapRealmConfiguration() {
+        return realmService.getBootstrapRealmConfiguration();
+    }
+
+    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getGovernanceSystemRegistry(tenantId);
+    }
+
+    public static UserRegistry getConfigSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getConfigSystemRegistry(tenantId);
+    }
+
+    public static TenantPersistor getTenantPersistor() {
+        return tenantPersistor;
+    }
+
+    protected void setTenantPersistor(TenantPersistor defaultTenantPersistor) {
+        tenantPersistor = defaultTenantPersistor;
+    }
+
+    public void unsetTenantPersistor(TenantPersistor defaultTenantPersistor) {
+        tenantPersistor = null;
+    }
+
+    
+   /** Updates RelyingPartyService with Crypto information
+    *
+    * @param config AxisConfiguration
+    * @throws Exception
+    */
+   private void populateRampartConfig(AxisConfiguration config) throws Exception {
+       AxisService service;
+       // Get the RelyingParty Service to update security policy with keystore information
+       service = config.getService(GAPP_TENANT_REG_SERVICE_NAME);
+       if (service == null) {
+           String msg = GAPP_TENANT_REG_SERVICE_NAME + " is not available in the Configuration Context";
+           log.error(msg);
+           throw new Exception(msg);
+       }
+       // Create a Rampart Config with default crypto information
+       Policy rampartConfig = TenantMgtRampartUtil.getDefaultRampartConfig();
+       // Add the RampartConfig to service policy
+       service.getPolicySubject().attachPolicy(rampartConfig);
+
+   }
+   
+   protected void setTenantBillingService(TenantBillingService tenantBillingService) {
+       billingService = tenantBillingService;
+   }
+   
+   protected void unsetTenantBillingService(TenantBillingService tenantBilling) {
+       setTenantBillingService(null);
+   }
+   
+   public static TenantBillingService getBillingService() {
+       return billingService;
+   }
+   
+   
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/internal/util/TenantMgtRampartUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/internal/util/TenantMgtRampartUtil.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/internal/util/TenantMgtRampartUtil.java
new file mode 100644
index 0000000..7cc40c7
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/internal/util/TenantMgtRampartUtil.java
@@ -0,0 +1,48 @@
+package org.apache.stratos.tenant.mgt.internal.util;
+
+import java.util.Properties;
+
+import org.apache.stratos.tenant.mgt.services.InMemoryPasswordcallbackHandler;
+import org.apache.neethi.Policy;
+import org.apache.rampart.policy.model.CryptoConfig;
+import org.apache.rampart.policy.model.RampartConfig;
+import org.wso2.carbon.base.ServerConfiguration;
+
+public class TenantMgtRampartUtil {
+	
+	public static Policy getDefaultRampartConfig() {
+        //Extract the primary keystore information from server configuration
+        ServerConfiguration serverConfig = ServerConfiguration.getInstance();
+        String keyStore = serverConfig.getFirstProperty("Security.KeyStore.Location");
+        String keyStoreType = serverConfig.getFirstProperty("Security.KeyStore.Type");
+        String keyStorePassword = serverConfig.getFirstProperty("Security.KeyStore.Password");
+        String privateKeyAlias = serverConfig.getFirstProperty("Security.KeyStore.KeyAlias");
+        String privateKeyPassword = serverConfig.getFirstProperty("Security.KeyStore.KeyPassword");
+
+        //Populate Rampart Configuration
+        RampartConfig rampartConfig = new RampartConfig();
+        rampartConfig.setUser(privateKeyAlias);
+        rampartConfig.setPwCbClass("org.wso2.carbon.tenant.mgt.services.InMemoryPasswordcallbackHandler");
+
+        //Set the private key alias and private key password in the password callback handler
+        InMemoryPasswordcallbackHandler.addUser(privateKeyAlias, privateKeyPassword);
+
+        CryptoConfig sigCrypto = new CryptoConfig();
+        Properties props = new Properties();
+        sigCrypto.setProvider("org.apache.ws.security.components.crypto.Merlin");
+        props.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", keyStoreType);
+        props.setProperty("org.apache.ws.security.crypto.merlin.file", keyStore);
+        props.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", keyStorePassword);
+        sigCrypto.setProp(props);
+
+        rampartConfig.setSigCryptoConfig(sigCrypto);
+        Policy policy = new Policy();
+        policy.addAssertion(rampartConfig);
+
+        return policy;
+
+    }
+	
+	
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/realm/CloudWSRealmConfigBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/realm/CloudWSRealmConfigBuilder.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/realm/CloudWSRealmConfigBuilder.java
new file mode 100644
index 0000000..171f9a3
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/realm/CloudWSRealmConfigBuilder.java
@@ -0,0 +1,138 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.tenant.mgt.realm;
+
+import java.util.Map;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.util.UUIDGenerator;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.um.ws.api.WSRealm;
+import org.wso2.carbon.um.ws.api.WSRemoteUserMgtConstants;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.api.TenantMgtConfiguration;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.config.RealmConfigXMLProcessor;
+import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
+import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants;
+import org.wso2.carbon.user.core.tenant.Tenant;
+
+/**
+ * This class is no more used by cloud manager or elsewhere.
+ * Hence deprecated and will be removed eventually.
+ */
+@Deprecated
+public class CloudWSRealmConfigBuilder implements MultiTenantRealmConfigBuilder {
+
+    private static final Log log = LogFactory.getLog(CloudWSRealmConfigBuilder.class);
+
+
+    /**
+     * This method is called on server startup by DefaultRealmService by non-Idaas cloud services
+     * 
+     * This is not called on ws.api startup.
+     */
+    public RealmConfiguration getRealmConfigForTenantToCreateRealm(
+            RealmConfiguration bootStrapConfig, RealmConfiguration persistedConfig, int tenantId)
+            throws UserStoreException {
+        RealmConfiguration realmConfig;
+        try {
+            if (persistedConfig.getRealmClassName().equals(WSRealm.class.getName())) {
+                realmConfig = persistedConfig;
+            } else {
+                realmConfig = bootStrapConfig.cloneRealmConfiguration();
+                realmConfig.setTenantId(tenantId);
+            }
+            if (log.isDebugEnabled()) {
+                OMElement omElement = RealmConfigXMLProcessor.serialize(realmConfig);
+                log.debug("Creating realm from **** " + omElement.toString());
+            }
+        } catch (Exception e) {
+            String msg = e.getMessage();
+            log.error(msg, e);
+            throw new UserStoreException(msg);
+        }
+        return realmConfig;
+    }
+
+    public RealmConfiguration getRealmConfigForTenantToCreateRealmOnTenantCreation(
+            RealmConfiguration bootStrapConfig, RealmConfiguration persistedConfig, int tenantId)
+            throws UserStoreException{
+        RealmConfiguration realmConfig;
+        try {
+            realmConfig = bootStrapConfig.cloneRealmConfiguration();
+            realmConfig.setRealmClassName("org.wso2.carbon.um.ws.api.WSRealm");
+            
+            realmConfig.setAdminPassword(UUIDGenerator.getUUID());
+            Map<String, String> realmProps = realmConfig.getRealmProperties();
+            realmProps.remove(JDBCRealmConstants.URL);
+            realmProps.remove(JDBCRealmConstants.DRIVER_NAME);
+            realmProps.remove(JDBCRealmConstants.USER_NAME);
+            realmProps.remove(JDBCRealmConstants.PASSWORD);
+            
+            realmConfig.setTenantId(tenantId);
+
+            if (log.isDebugEnabled()) {
+                OMElement omElement = RealmConfigXMLProcessor.serialize(realmConfig);
+                log.debug("Creating realm from (On tenant creation)**** " + omElement.toString());
+            }
+
+        } catch (Exception e) {
+            String msg = e.getMessage();
+            log.error(msg, e);
+            throw new UserStoreException(msg);
+        }
+        return realmConfig;
+    }
+
+
+    public RealmConfiguration getRealmConfigForTenantToPersist(RealmConfiguration bootStrapConfig,
+                                                               TenantMgtConfiguration tenantMgtConfig,
+                                                               Tenant tenantInfo, int tenantId)
+            throws UserStoreException {
+        RealmConfiguration realmConfig;
+        try {
+            realmConfig = bootStrapConfig.cloneRealmConfiguration();
+            realmConfig.setAdminUserName(tenantInfo.getAdminName());
+            realmConfig.setAdminPassword(UUIDGenerator.getUUID());
+            Map<String, String> realmProps = realmConfig.getRealmProperties();
+            realmProps.remove(JDBCRealmConstants.URL);
+            realmProps.remove(JDBCRealmConstants.DRIVER_NAME);
+            realmProps.remove(JDBCRealmConstants.USER_NAME);
+            realmProps.remove(JDBCRealmConstants.PASSWORD);
+            realmProps.remove(WSRemoteUserMgtConstants.SERVER_URL);
+            realmProps.remove(WSRemoteUserMgtConstants.USER_NAME);
+            realmProps.remove(WSRemoteUserMgtConstants.PASSWORD);
+            realmProps.remove(WSRemoteUserMgtConstants.SINGLE_USER_AUTHENTICATION);
+            realmProps.put("MultiTenantRealmConfigBuilder", IdaasWSRealmConfigBuilder.class.getName());
+            realmConfig.setTenantId(tenantId);
+            if (log.isDebugEnabled()) {
+                OMElement omElement = RealmConfigXMLProcessor.serialize(realmConfig);
+                log.debug("Saving RealmConfiguration **** " + omElement.toString());
+            }
+
+        } catch (Exception e) {
+            String msg = e.getMessage();
+            log.error(msg, e);
+            throw new UserStoreException(msg);
+        }
+        return realmConfig;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/realm/IdaasWSRealmConfigBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/realm/IdaasWSRealmConfigBuilder.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/realm/IdaasWSRealmConfigBuilder.java
new file mode 100644
index 0000000..a213ee9
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/realm/IdaasWSRealmConfigBuilder.java
@@ -0,0 +1,87 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.tenant.mgt.realm;
+
+import java.util.Map;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.api.TenantMgtConfiguration;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.config.RealmConfigXMLProcessor;
+import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
+import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants;
+import org.wso2.carbon.user.core.tenant.Tenant;
+
+public class IdaasWSRealmConfigBuilder implements MultiTenantRealmConfigBuilder {
+    
+    private static final Log log = LogFactory.getLog(CloudWSRealmConfigBuilder.class);
+
+    /**
+     * This method is called, on server startup by DefaultRealmService by Idaas only
+     * 
+     * This is not called on ws.api startup or by any non-Idaas servers
+     */
+    public RealmConfiguration getRealmConfigForTenantToCreateRealm(
+            RealmConfiguration bootStrapConfig, RealmConfiguration persistedConfig, int tenantId)
+            throws UserStoreException {
+        RealmConfiguration realmConfig;
+        try {
+                realmConfig = persistedConfig;
+               // now this is Idaas
+                Map<String, String> realmProps = realmConfig.getRealmProperties();
+                Map<String, String> bootStrapProps = bootStrapConfig.getRealmProperties();
+                realmProps.put(JDBCRealmConstants.URL, bootStrapProps.get(JDBCRealmConstants.URL));
+                realmProps.put(JDBCRealmConstants.DRIVER_NAME, bootStrapProps.get(
+                        JDBCRealmConstants.DRIVER_NAME));
+                realmProps.put(JDBCRealmConstants.USER_NAME, bootStrapProps.get(
+                        JDBCRealmConstants.USER_NAME));
+                realmProps.put(JDBCRealmConstants.PASSWORD, bootStrapProps.get(
+                        JDBCRealmConstants.PASSWORD));
+                realmConfig.setTenantId(tenantId);
+
+                if(log.isDebugEnabled()) {
+                    OMElement omElement = RealmConfigXMLProcessor.serialize(realmConfig);
+                    log.debug("Creating realm from **** " + omElement.toString());
+                }
+                
+        } catch (Exception e) {
+            String msg = e.getMessage();
+            log.error(msg, e);
+            throw new UserStoreException(msg);
+        }
+        return realmConfig;
+    }
+    
+    public RealmConfiguration getRealmConfigForTenantToCreateRealmOnTenantCreation(
+            RealmConfiguration bootStrapConfig, RealmConfiguration persistedConfig, int tenantId)
+            throws UserStoreException{
+        //never called
+        return null;
+    }
+
+    public RealmConfiguration getRealmConfigForTenantToPersist(RealmConfiguration bootStrapConfig,
+                                                               TenantMgtConfiguration tenantMgtConfig,
+                                                               Tenant tenantInfo, int tenantId)
+            throws UserStoreException {
+        //never called
+        return null;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/GAppTenantRegistrationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/GAppTenantRegistrationService.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/GAppTenantRegistrationService.java
new file mode 100644
index 0000000..d011ec1
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/GAppTenantRegistrationService.java
@@ -0,0 +1,120 @@
+package org.apache.stratos.tenant.mgt.services;
+
+import org.apache.stratos.tenant.mgt.exception.TenantManagementException;
+import org.apache.stratos.tenant.mgt.internal.TenantMgtServiceComponent;
+import org.apache.stratos.tenant.mgt.util.TenantMgtUtil;
+import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
+import org.apache.stratos.common.beans.TenantInfoBean;
+import org.apache.stratos.common.exception.StratosException;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.api.TenantMgtConfiguration;
+import org.wso2.carbon.user.api.UserStoreException;
+import org.wso2.carbon.user.core.UserCoreConstants;
+import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ws.security.util.UUIDGenerator;
+
+public class GAppTenantRegistrationService {
+	
+    private static final String GOOGLE_APPS_IDP_NAME = "GoogleApps";
+    
+    private static final Log log = LogFactory.getLog(GAppTenantRegistrationService.class);
+    
+    
+    public boolean isRegisteredAsGoogleAppDomain(String domain) throws TenantManagementException {
+
+        TenantManager tenantManager = 
+            TenantMgtServiceComponent.getRealmService().getTenantManager();
+        try {
+            int tenantId = tenantManager.getTenantId(domain);
+
+            if (tenantId == -1) {
+                return false;
+            }
+
+            Tenant tenant = (Tenant) tenantManager.getTenant(tenantId);
+            RealmConfiguration realmConfig = tenant.getRealmConfig();
+            String value = realmConfig.getUserStoreProperties().get(
+                            UserCoreConstants.RealmConfig.PROPERTY_EXTERNAL_IDP);
+
+            if (value == null) {
+                throw new TenantManagementException(
+                        "This domain has been already registered as a non-Google App domain");
+            }
+
+            if (value.equals(GOOGLE_APPS_IDP_NAME)) {
+                return true;
+            }
+            
+            throw new TenantManagementException(
+                    "This domain has been already registered with a different External IdP");
+        } catch (UserStoreException e) {
+            log.error(e.getMessage(), e);
+            throw new TenantManagementException("System error occured while connecting user store");
+        }
+    }
+    
+    public boolean registerGoogleAppsTenant(
+                                TenantInfoBean tenantInfoBean)throws TenantManagementException {
+        try {
+            int tenantId = -1;
+            Tenant tenant = TenantMgtUtil.initializeTenant(tenantInfoBean);
+            TenantPersistor tenantPersistor = TenantMgtServiceComponent.getTenantPersistor();
+
+            MultiTenantRealmConfigBuilder builder =
+                    TenantMgtServiceComponent.getRealmService().getMultiTenantRealmConfigBuilder();
+            TenantMgtConfiguration tenantMgtConfiguration =
+                    TenantMgtServiceComponent.getRealmService().getTenantMgtConfiguration();
+            RealmConfiguration bootStrapRealmConfig =
+                    TenantMgtServiceComponent.getRealmService().getBootstrapRealmConfiguration();
+            RealmConfiguration realmConfigToPersist =
+                    builder.getRealmConfigForTenantToPersist(bootStrapRealmConfig,
+                            tenantMgtConfiguration, tenant, -1);
+            realmConfigToPersist.getUserStoreProperties().put(
+                    UserCoreConstants.RealmConfig.PROPERTY_EXTERNAL_IDP, GOOGLE_APPS_IDP_NAME);
+            tenant.setRealmConfig(realmConfigToPersist);
+            tenant.setAdminPassword(UUIDGenerator.getUUID());
+
+            tenantId = tenantPersistor.persistTenant(tenant);
+            tenantInfoBean.setTenantId(tenantId);
+
+            TenantMgtUtil.addClaimsToUserStoreManager(tenant);
+
+            // Notify tenant addition
+            try {
+                TenantMgtUtil.triggerAddTenant(tenantInfoBean);
+            } catch (StratosException e) {
+                String msg = "Error in notifying tenant addition.";
+                log.error(msg, e);
+                throw new Exception(msg, e);
+            }
+
+            // adding the subscription entry
+            try {
+                if (TenantMgtServiceComponent.getBillingService() != null) {
+                    tenantInfoBean.setTenantId(tenantId); // required for the following method
+                    TenantMgtServiceComponent.getBillingService().addUsagePlan(tenant,
+                            tenantInfoBean.getUsagePlan());
+                    if (log.isDebugEnabled()) {
+                        log.debug("Subscription added successfully for the tenant: " +
+                                  tenantInfoBean.getTenantDomain());
+                    }
+                }
+            } catch (Exception e) {
+                log.error("Error occurred while adding the subscription for tenant: " +
+                          tenantInfoBean.getTenantDomain() + " " + e.getMessage(), e);
+            }
+
+            TenantMgtServiceComponent.getRealmService().getTenantManager().activateTenant(tenantId);
+            return true;
+        } catch (Exception e) {
+            log.error("Error creating tenant for GooogleApp market place implementation", e);
+            throw new TenantManagementException(
+                    "Error creating tenant for GooogleApp market place implementation", e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/InMemoryPasswordcallbackHandler.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/InMemoryPasswordcallbackHandler.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/InMemoryPasswordcallbackHandler.java
new file mode 100644
index 0000000..fec72a1
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/InMemoryPasswordcallbackHandler.java
@@ -0,0 +1,38 @@
+package org.apache.stratos.tenant.mgt.services;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+import org.apache.ws.security.WSPasswordCallback;
+
+public class InMemoryPasswordcallbackHandler  implements CallbackHandler {
+
+    private static Map<String, String> keystorePassword = new HashMap<String, String>();
+
+    public void handle(Callback[] callbacks)
+            throws IOException, UnsupportedCallbackException {
+
+        for (int i = 0; i < callbacks.length; i++) {
+
+            if (callbacks[i] instanceof WSPasswordCallback) {
+                WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
+                String id = pc.getIdentifier();
+                if (keystorePassword.get(id) != null) {
+                    pc.setPassword(keystorePassword.get(id));
+                } else {
+                    throw new UnsupportedCallbackException(callbacks[i], "no password found for " + id);
+                }
+            }
+
+        }
+    }
+
+    public static void addUser(String username, String password) {
+        keystorePassword.put(username, password);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/TenantMgtAdminService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/TenantMgtAdminService.java b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/TenantMgtAdminService.java
new file mode 100644
index 0000000..664e31d
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt/src/main/java/org/apache/stratos/tenant/mgt/services/TenantMgtAdminService.java
@@ -0,0 +1,496 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stratos.tenant.mgt.services;
+
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.apache.stratos.common.beans.TenantInfoBean;
+import org.apache.stratos.common.exception.StratosException;
+import org.apache.stratos.common.util.ClaimsMgtUtil;
+import org.apache.stratos.common.util.CommonUtil;
+import org.apache.stratos.tenant.mgt.beans.PaginatedTenantInfoBean;
+import org.apache.stratos.tenant.mgt.core.internal.TenantMgtCoreServiceComponent;
+import org.apache.stratos.tenant.mgt.internal.TenantMgtServiceComponent;
+import org.apache.stratos.tenant.mgt.util.TenantMgtUtil;
+import org.wso2.carbon.user.core.UserRealm;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.UserStoreManager;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.DataPaginator;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * This is the admin Web service which is used for managing tenants
+ */
+public class TenantMgtAdminService extends AbstractAdmin {
+    private static final Log log = LogFactory.getLog(TenantMgtAdminService.class);
+
+    /**
+     * super admin adds a tenant
+     *
+     * @param tenantInfoBean tenant info bean
+     * @return UUID
+     * @throws Exception if error in adding new tenant.
+     */
+    public String addTenant(TenantInfoBean tenantInfoBean) throws Exception {
+        try {
+            CommonUtil.validateEmail(tenantInfoBean.getEmail());
+        } catch (Exception e) {
+            String msg = "Invalid email is provided.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        String tenantDomain = tenantInfoBean.getTenantDomain();
+        TenantMgtUtil.validateDomain(tenantDomain);
+        UserRegistry userRegistry = (UserRegistry) getGovernanceRegistry();
+        if (userRegistry == null) {
+            log.error("Security Alert! User registry is null. A user is trying create a tenant "
+                      + " without an authenticated session.");
+            throw new Exception("Invalid data."); // obscure error message.
+        }
+
+        if (userRegistry.getTenantId() != MultitenantConstants.SUPER_TENANT_ID) {
+            log.error("Security Alert! Non super tenant trying to create a tenant.");
+            throw new Exception("Invalid data."); // obscure error message.
+        }
+        Tenant tenant = TenantMgtUtil.initializeTenant(tenantInfoBean);
+        TenantPersistor persistor = TenantMgtServiceComponent.getTenantPersistor();
+        // not validating the domain ownership, since created by super tenant
+        int tenantId = persistor.persistTenant(tenant, false, tenantInfoBean.getSuccessKey(),
+                                tenantInfoBean.getOriginatedService());
+        tenantInfoBean.setTenantId(tenantId);
+        
+        TenantMgtUtil.addClaimsToUserStoreManager(tenant);
+        
+        //Notify tenant addition
+        try {
+            TenantMgtUtil.triggerAddTenant(tenantInfoBean);
+        } catch (StratosException e) {
+            String msg = "Error in notifying tenant addition.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        //adding the subscription entry
+        /*try {
+            if (TenantMgtServiceComponent.getBillingService() != null) {
+                TenantMgtServiceComponent.getBillingService().
+                        addUsagePlan(tenant, tenantInfoBean.getUsagePlan());
+                if (log.isDebugEnabled()) {
+                    log.debug("Subscription added successfully for the tenant: " +
+                            tenantInfoBean.getTenantDomain());
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while adding the subscription for tenant: " + tenantDomain;
+            log.error(msg, e);
+        }*/
+
+        // For the super tenant tenant creation, tenants are always activated as they are created.
+        TenantMgtUtil.activateTenantInitially(tenantInfoBean, tenantId);
+
+        return TenantMgtUtil.prepareStringToShowThemeMgtPage(tenant.getId());
+    }
+
+    /**
+     * Get the list of the tenants
+     *
+     * @return List<TenantInfoBean>
+     * @throws Exception UserStorException
+     */
+    private List<TenantInfoBean> getAllTenants() throws Exception {
+        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
+        Tenant[] tenants;
+        try {
+            tenants = (Tenant[]) tenantManager.getAllTenants();
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant information.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        List<TenantInfoBean> tenantList = new ArrayList<TenantInfoBean>();
+        for (Tenant tenant : tenants) {
+            TenantInfoBean bean = TenantMgtUtil.getTenantInfoBeanfromTenant(tenant.getId(), tenant);
+            tenantList.add(bean);
+        }
+        return tenantList;
+    }
+    
+    /**
+     * Get the list of the tenants
+     *
+     * @return List<TenantInfoBean>
+     * @throws Exception UserStorException
+     */
+    private List<TenantInfoBean> searchPartialTenantsDomains(String domain) throws Exception {
+        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
+        Tenant[] tenants;
+        try {
+        	domain = domain.trim();
+            tenants = (Tenant[]) tenantManager.getAllTenantsForTenantDomainStr(domain);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant information.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        List<TenantInfoBean> tenantList = new ArrayList<TenantInfoBean>();
+        for (Tenant tenant : tenants) {
+            TenantInfoBean bean = TenantMgtUtil.getTenantInfoBeanfromTenant(tenant.getId(), tenant);
+            tenantList.add(bean);
+        }
+        return tenantList;
+    }
+
+    /**
+     * Retrieve all the tenants
+     *
+     * @return tenantInfoBean[]
+     * @throws Exception if failed to get Tenant Manager
+     */
+    public TenantInfoBean[] retrieveTenants() throws Exception {
+        List<TenantInfoBean> tenantList = getAllTenants();
+        return tenantList.toArray(new TenantInfoBean[tenantList.size()]);
+    }
+    
+    /**
+     * Retrieve all the tenants which matches the partial search domain
+     *
+     * @return tenantInfoBean[]
+     * @throws Exception if failed to get Tenant Manager
+     */
+    public TenantInfoBean[] retrievePartialSearchTenants(String domain) throws Exception {
+        List<TenantInfoBean> tenantList = searchPartialTenantsDomains(domain);
+        return tenantList.toArray(new TenantInfoBean[tenantList.size()]);
+    }
+
+    /**
+     * Method to retrieve all the partial search domain tenants paginated
+     *
+     * @param pageNumber Number of the page.
+     * @return PaginatedTenantInfoBean
+     * @throws Exception if failed to getTenantManager;
+     */
+    public PaginatedTenantInfoBean retrievePaginatedPartialSearchTenants(String domain,int pageNumber) throws Exception {
+        List<TenantInfoBean> tenantList = searchPartialTenantsDomains(domain);
+
+        // Pagination
+        PaginatedTenantInfoBean paginatedTenantInfoBean = new PaginatedTenantInfoBean();
+        DataPaginator.doPaging(pageNumber, tenantList, paginatedTenantInfoBean);
+        return paginatedTenantInfoBean;
+    }
+    
+    /**
+     * Method to retrieve all the tenants paginated
+     *
+     * @param pageNumber Number of the page.
+     * @return PaginatedTenantInfoBean
+     * @throws Exception if failed to getTenantManager;
+     */
+    public PaginatedTenantInfoBean retrievePaginatedTenants(int pageNumber) throws Exception {
+        List<TenantInfoBean> tenantList = getAllTenants();
+
+        // Pagination
+        PaginatedTenantInfoBean paginatedTenantInfoBean = new PaginatedTenantInfoBean();
+        DataPaginator.doPaging(pageNumber, tenantList, paginatedTenantInfoBean);
+        return paginatedTenantInfoBean;
+    }
+
+    /**
+     * Get a specific tenant
+     *
+     * @param tenantDomain tenant domain
+     * @return tenantInfoBean
+     * @throws Exception UserStoreException
+     */
+    public TenantInfoBean getTenant(String tenantDomain) throws Exception {
+        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
+
+        int tenantId;
+        try {
+            tenantId = tenantManager.getTenantId(tenantDomain);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant id for the tenant domain: " +
+                         tenantDomain + ".";
+            log.error(msg);
+            throw new Exception(msg, e);
+        }
+        Tenant tenant;
+        try {
+            tenant = (Tenant) tenantManager.getTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant from the tenant manager.";
+            log.error(msg);
+            throw new Exception(msg, e);
+        }
+
+        TenantInfoBean bean = TenantMgtUtil.initializeTenantInfoBean(tenantId, tenant);
+
+        // retrieve first and last names from the UserStoreManager
+        bean.setFirstname(ClaimsMgtUtil.getFirstNamefromUserStoreManager(
+                TenantMgtServiceComponent.getRealmService(), tenantId));
+        bean.setLastname(ClaimsMgtUtil.getLastNamefromUserStoreManager(
+                TenantMgtServiceComponent.getRealmService(), tenantId));
+
+        //getting the subscription plan
+        String activePlan = "";
+        if(TenantMgtServiceComponent.getBillingService() != null){
+            activePlan = TenantMgtServiceComponent.getBillingService().
+                    getActiveUsagePlan(tenantDomain);
+        }
+
+        if(activePlan != null && activePlan.trim().length() > 0){
+            bean.setUsagePlan(activePlan);
+        }else{
+            bean.setUsagePlan("");
+        }
+
+        return bean;
+    }
+
+    /**
+     * Updates a given tenant
+     *
+     * @param tenantInfoBean tenant information
+     * @throws Exception UserStoreException
+     */
+    public void updateTenant(TenantInfoBean tenantInfoBean) throws Exception {
+        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
+        UserStoreManager userStoreManager;
+
+        // filling the non-set admin and admin password first
+        UserRegistry configSystemRegistry = TenantMgtServiceComponent.getConfigSystemRegistry(
+                tenantInfoBean.getTenantId());
+
+        String tenantDomain = tenantInfoBean.getTenantDomain();
+
+        int tenantId;
+        try {
+            tenantId = tenantManager.getTenantId(tenantDomain);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant id for the tenant domain: " + tenantDomain
+                         + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        Tenant tenant;
+        try {
+            tenant = (Tenant) tenantManager.getTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant id for the tenant domain: " +
+                         tenantDomain + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        // filling the first and last name values
+        if (tenantInfoBean.getFirstname() != null &&
+            !tenantInfoBean.getFirstname().trim().equals("")) {
+            try {
+                CommonUtil.validateName(tenantInfoBean.getFirstname(), "First Name");
+            } catch (Exception e) {
+                String msg = "Invalid first name is provided.";
+                log.error(msg, e);
+                throw new Exception(msg, e);
+            }
+        }
+        if (tenantInfoBean.getLastname() != null &&
+            !tenantInfoBean.getLastname().trim().equals("")) {
+            try {
+                CommonUtil.validateName(tenantInfoBean.getLastname(), "Last Name");
+            } catch (Exception e) {
+                String msg = "Invalid last name is provided.";
+                log.error(msg, e);
+                throw new Exception(msg, e);
+            }
+        }
+
+        tenant.setAdminFirstName(tenantInfoBean.getFirstname());
+        tenant.setAdminLastName(tenantInfoBean.getLastname());
+        TenantMgtUtil.addClaimsToUserStoreManager(tenant);
+
+        // filling the email value
+        if (tenantInfoBean.getEmail() != null && !tenantInfoBean.getEmail().equals("")) {
+            // validate the email
+            try {
+                CommonUtil.validateEmail(tenantInfoBean.getEmail());
+            } catch (Exception e) {
+                String msg = "Invalid email is provided.";
+                log.error(msg, e);
+                throw new Exception(msg, e);
+            }
+            tenant.setEmail(tenantInfoBean.getEmail());
+        }
+
+        UserRealm userRealm = configSystemRegistry.getUserRealm();
+        try {
+            userStoreManager = userRealm.getUserStoreManager();
+        } catch (UserStoreException e) {
+            String msg = "Error in getting the user store manager for tenant, tenant domain: " +
+                         tenantDomain + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        boolean updatePassword = false;
+        if (tenantInfoBean.getAdminPassword() != null
+            && !tenantInfoBean.getAdminPassword().equals("")) {
+            updatePassword = true;
+        }
+        if (!userStoreManager.isReadOnly() && updatePassword) {
+            // now we will update the tenant admin with the admin given
+            // password.
+            try {
+                userStoreManager.updateCredentialByAdmin(tenantInfoBean.getAdmin(),
+                                                         tenantInfoBean.getAdminPassword());
+            } catch (UserStoreException e) {
+                String msg = "Error in changing the tenant admin password, tenant domain: " +
+                             tenantInfoBean.getTenantDomain() + ". " + e.getMessage() + " for: " +
+                             tenantInfoBean.getAdmin();
+                log.error(msg, e);
+                throw new Exception(msg, e);
+            }
+        } else {
+            //Password should be empty since no password update done
+            tenantInfoBean.setAdminPassword("");
+        }
+
+        try {
+            tenantManager.updateTenant(tenant);
+        } catch (UserStoreException e) {
+            String msg = "Error in updating the tenant for tenant domain: " + tenantDomain + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        
+        //Notify tenant update to all listeners
+        try {
+            TenantMgtUtil.triggerUpdateTenant(tenantInfoBean);
+        } catch (StratosException e) {
+            String msg = "Error in notifying tenant update.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        //updating the usage plan
+        /*try{
+            if(TenantMgtServiceComponent.getBillingService() != null){
+                TenantMgtServiceComponent.getBillingService().
+                        updateUsagePlan(tenantInfoBean.getTenantDomain(), tenantInfoBean.getUsagePlan());
+            }
+        }catch(Exception e){
+            String msg = "Error when updating the usage plan: " + e.getMessage();
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }*/
+    }
+
+    /**
+     * Activate a deactivated tenant, by the super tenant.
+     *
+     * @param tenantDomain tenant domain
+     * @throws Exception UserStoreException.
+     */
+    public void activateTenant(String tenantDomain) throws Exception {
+        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
+        int tenantId;
+        try {
+            tenantId = tenantManager.getTenantId(tenantDomain);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant id for the tenant domain: " + tenantDomain
+                         + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        TenantMgtUtil.activateTenant(tenantDomain, tenantManager, tenantId);
+
+        //Notify tenant activation all listeners
+        try {
+            TenantMgtUtil.triggerTenantActivation(tenantId);
+        } catch (StratosException e) {
+            String msg = "Error in notifying tenant activate.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+    }
+
+    /**
+     * Deactivate the given tenant
+     *
+     * @param tenantDomain tenant domain
+     * @throws Exception UserStoreException
+     */
+    public void deactivateTenant(String tenantDomain) throws Exception {
+        TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager();
+        int tenantId;
+        try {
+            tenantId = tenantManager.getTenantId(tenantDomain);
+        } catch (UserStoreException e) {
+            String msg =
+                    "Error in retrieving the tenant id for the tenant domain: " +
+                    tenantDomain + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        TenantMgtUtil.deactivateTenant(tenantDomain, tenantManager, tenantId);
+
+        //Notify tenant deactivation all listeners
+        try {
+            TenantMgtUtil.triggerTenantDeactivation(tenantId);
+        } catch (StratosException e) {
+            String msg = "Error in notifying tenant deactivate.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+    }
+
+    /**
+     * Delete a specific tenant
+     *
+     * @param tenantDomain The domain name of the tennat that needs to be deleted
+     */
+    public void deleteTenant(String tenantDomain) throws Exception {
+        TenantManager tenantManager = TenantMgtCoreServiceComponent.getTenantManager();
+        int tenantId = tenantManager.getTenantId(tenantDomain);
+        try {
+            TenantMgtServiceComponent.getBillingService().deleteBillingData(tenantId);
+            TenantMgtUtil.deleteTenantRegistryData(tenantId);
+            TenantMgtUtil.deleteTenantUMData(tenantId);
+            tenantManager.deleteTenant(tenantId);
+            log.info("Deleted tenant with domain: " + tenantDomain + " and tenant id: " + tenantId + 
+                     " from the system.");
+        } catch (Exception e) {
+            String msg = "Error deleting tenant with domain: " + tenantDomain + " and tenant id: " +
+                    tenantId + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+    }
+}


[39/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java
deleted file mode 100644
index e4274f5..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.lb.endpoint;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axis2.context.ConfigurationContext;
-import org.wso2.carbon.mediation.initializer.ServiceBusConstants;
-import org.wso2.carbon.mediation.initializer.ServiceBusUtils;
-import org.wso2.carbon.mediation.initializer.persistence.MediationPersistenceManager;
-
-import java.util.Properties;
-
-/**
- * Responsible for deploying Synapse artifacts.
- */
-public class EndpointDeployer extends org.apache.synapse.deployers.EndpointDeployer {
-
-    MediationPersistenceManager mpm;
-
-    @Override
-    public void init(ConfigurationContext configCtx) {
-        super.init(configCtx);
-        this.mpm = ServiceBusUtils.getMediationPersistenceManager(configCtx.getAxisConfiguration());
-    }
-
-    @Override
-    public String deploySynapseArtifact(OMElement artifactConfig, String fileName,
-                                        Properties properties) {
-        String epName = super.deploySynapseArtifact(artifactConfig, fileName, properties);
-        mpm.saveItemToRegistry(epName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
-        return epName;
-    }
-
-    @Override
-    public String updateSynapseArtifact(OMElement artifactConfig, String fileName,
-                                        String existingArtifactName, Properties properties) {
-        String epName = super.updateSynapseArtifact(
-                artifactConfig, fileName, existingArtifactName, properties);
-        mpm.saveItemToRegistry(epName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
-        return epName;
-    }
-
-    @Override
-    public void undeploySynapseArtifact(String artifactName) {
-        super.undeploySynapseArtifact(artifactName);
-        mpm.deleteItemFromRegistry(artifactName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
-    }
-
-    @Override
-    public void restoreSynapseArtifact(String artifactName) {
-        super.restoreSynapseArtifact(artifactName);
-        mpm.saveItemToRegistry(artifactName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
deleted file mode 100644
index ac78fdd..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint;
-
-/**
- * Exception to be thrown from this component.
- */
-public class TenantAwareLoadBalanceEndpointException extends RuntimeException {
-
-    private static final long serialVersionUID = -663839410798538370L;
-
-    public TenantAwareLoadBalanceEndpointException(String msg) {
-        super(msg);
-    }
-
-    public TenantAwareLoadBalanceEndpointException(String msg, Throwable cause) {
-        super(msg, cause);
-    }
-
-    public TenantAwareLoadBalanceEndpointException(Throwable cause) {
-        super(cause);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java
deleted file mode 100644
index 07208cb..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint;
-
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.Member;
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.stratos.lb.endpoint.util.ConfigHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.apache.synapse.core.LoadBalanceMembershipHandler;
-import org.apache.synapse.endpoints.algorithms.AlgorithmContext;
-import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
-import org.apache.stratos.lb.common.conf.util.HostContext;
-import org.wso2.carbon.user.api.UserStoreException;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * Bridge between Axis2 membership notification and Synapse load balancing
- */
-public class TenantLoadBalanceMembershipHandler implements LoadBalanceMembershipHandler {
-    private static final Log log = LogFactory.getLog(TenantLoadBalanceMembershipHandler.class);
-
-    private ConfigurationContext configCtx;
-
-    private LoadbalanceAlgorithm lbAlgo;
-    
-    /**
-     * Key - Host, Value - HostContext
-     */
-    private static Map<String, HostContext> hostContextsMap =
-            new HashMap<String, HostContext>();
-    
-    private ClusteringAgent clusteringAgent;
-    
-    private boolean isClusteringEnabled;
-    private String endpointName;
-
-    public TenantLoadBalanceMembershipHandler(Map<String, HostContext> hostContexts,
-                                              LoadbalanceAlgorithm algorithm,
-                                              ConfigurationContext configCtx,
-                                              boolean isClusteringEnabled,
-                                              String endpointName) {
-
-        lbAlgo = algorithm;
-        this.isClusteringEnabled = isClusteringEnabled;
-        this.endpointName = endpointName;
-        this.configCtx = configCtx;
-        
-        for (HostContext host : hostContexts.values()) {
-            
-            addHostContext(host);
-
-        }
-    }
-    
-    /**
-     * This will be used to add new {@link HostContext}s.
-     * @param host {@link HostContext}
-     */
-    public void addHostContext(HostContext host){
-        
-        String hostName = host.getHostName();
-
-        AlgorithmContext algorithmContext =
-                                            new AlgorithmContext(isClusteringEnabled,
-                                                                 configCtx, endpointName + "." +
-                                                                            hostName);
-
-        host.setAlgorithm(lbAlgo.clone());
-        host.setAlgorithmContext(algorithmContext);
-
-        hostContextsMap.put(hostName, host);
-        
-    }
-    
-    /**
-     * This will be used to remove an existing {@link HostContext}s.
-     * @param host {@link HostContext}
-     */
-    public void removeHostContext(String host){
-
-        hostContextsMap.remove(host);
-        
-    }
-
-    public void init(Properties props, LoadbalanceAlgorithm algorithm) {
-        // Nothing to do
-    }
-
-    public void setConfigurationContext(ConfigurationContext configCtx) {
-        this.configCtx = configCtx;
-
-        // The following code does the bridging between Axis2 and Synapse load balancing
-        clusteringAgent = configCtx.getAxisConfiguration().getClusteringAgent();
-        if (clusteringAgent == null) {
-            String msg = "In order to enable load balancing across an Axis2 cluster, " +
-                         "the cluster entry should be enabled in the axis2.xml file";
-            log.error(msg);
-            throw new SynapseException(msg);
-        }
-    }
-
-    public ConfigurationContext getConfigurationContext() {
-        return configCtx;
-    }
-
-    /**
-     * Getting the next member to which the request has to be sent in a round-robin fashion
-     *
-     * @param context The AlgorithmContext
-     * @return The current member
-     * @deprecated Use {@link #getNextApplicationMember(String, int)}
-     */
-    public Member getNextApplicationMember(AlgorithmContext context) {
-        throw new UnsupportedOperationException("This operation is invalid. " +
-                                                "Call getNextApplicationMember(String host)");
-    }
-
-    public boolean isAValidHostName(String host){
-        if(getHostContext(host) != null){
-            return true;
-        }
-        return false;
-    }
-
-    public Member getNextApplicationMember(String host, int tenantId) {
-        HostContext hostContext = getHostContext(host);
-
-        if(hostContext == null){
-            String msg = "Invalid host name : " + host;
-            log.error(msg);
-            throw new SynapseException(msg);
-        }
-
-        // here we have to pass tenant id to get domain from hostContext
-        String domain = hostContext.getDomainFromTenantId(tenantId);
-        String subDomain = hostContext.getSubDomainFromTenantId(tenantId);
-
-        LoadbalanceAlgorithm algorithm = hostContext.getAlgorithm();
-        GroupManagementAgent groupMgtAgent = clusteringAgent.getGroupManagementAgent(domain, subDomain);
-        
-        if (groupMgtAgent == null) {
-        	String tenantDomain;
-            try {
-	            tenantDomain = ConfigHolder.getInstance().getRealmService().getTenantManager().getDomain(tenantId);
-            } catch (UserStoreException ignore) {
-            	tenantDomain = ""+tenantId;
-            }
-        	
-            String msg =
-                    "No Group Management Agent found for the domain: " + domain + ", subDomain: "
-                    		+ subDomain + ", host: " + host+ " and for tenant: "
-                    		+  tenantDomain;
-            log.error(msg); 
-            throw new SynapseException(msg);
-        }
-        algorithm.setApplicationMembers(groupMgtAgent.getMembers());
-        AlgorithmContext context = hostContext.getAlgorithmContext();
-        return algorithm.getNextApplicationMember(context);
-    }
-
-    public HostContext getHostContext(String host) {
-        HostContext hostContext = hostContextsMap.get(host);
-        if (hostContext == null) {
-            int indexOfDot;
-            if ((indexOfDot = host.indexOf(".")) != -1) {
-                hostContext = getHostContext(host.substring(indexOfDot + 1));
-            } 
-        }
-        return hostContext;
-    }
-
-    public LoadbalanceAlgorithm getLoadbalanceAlgorithm() {
-        return lbAlgo;
-    }
-
-    public Properties getProperties() {
-        return null;
-    }
-    
-    public ClusteringAgent getClusteringAgent() {
-        return clusteringAgent;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java
deleted file mode 100644
index 478790e..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint.builder;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-
-import org.apache.stratos.lb.endpoint.util.ConfigHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.apache.stratos.lb.common.conf.structure.Node;
-import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
-import org.apache.stratos.lb.common.conf.util.HostContext;
-import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
-import org.apache.stratos.lb.endpoint.TenantLoadBalanceMembershipHandler;
-import org.apache.stratos.lb.endpoint.group.mgt.GroupMgtAgentBuilder;
-
-/**
- * A Thread, which is responsible for making a sense out of a message received for
- * ELB via topology synchronization.
- */
-public class TopologySyncher implements Runnable {
-
-    private static final Log log = LogFactory.getLog(TopologySyncher.class);
-
-    /*
-     * This is a reference to sharedTopologyQueue ConfigHolder.
-     */
-    private BlockingQueue<String> sharedQueue;
-
-    public TopologySyncher(BlockingQueue<String> queue) {
-
-        sharedQueue = queue;
-
-    }
-
-    @Override
-    public void run() {
-        // grab the lb configuration instance
-        LoadBalancerConfiguration lbconfig = LoadBalancerConfiguration.getInstance();
-
-        // FIXME Currently there has to be at least one dummy cluster defined in the loadbalancer
-        // conf
-        // in order to proper initialization of TribesClusteringAgent.
-        generateGroupMgtAgents(lbconfig);
-
-        // this thread should run for ever, untill terminated.
-        while (true) {
-            try {
-
-                // grabs a message or waits till the queue is non-empty
-                String message = sharedQueue.take();
-//                ConfigHolder data = ConfigHolder.getInstance();
-
-                // this message needs attention only if it's not same as the previous message and
-                // not null of course.
-//                if (data.getPreviousMsg() == null || !data.getPreviousMsg().equals(message)) {
-
-                    // reset the previous message
-//                    data.setPreviousMsg(message);
-
-                    // build the nginx format of this message, and get the Node object
-                    Node topologyNode = NodeBuilder.buildNode(message);
-
-                    // reset service configurations
-//                    lbconfig.resetData();
-                    // create new service configurations
-                    List<ServiceConfiguration> currentServiceConfigs = lbconfig.createServicesConfig(topologyNode);
-                    
-                    generateGroupMgtAgents(lbconfig);
-                    
-                    removeGroupMgtAgents(lbconfig, currentServiceConfigs);
-
-//                }
-
-            } catch (InterruptedException ignore) {
-            }
-        }
-
-    }
-
-    private void removeGroupMgtAgents(LoadBalancerConfiguration lbConfig, List<ServiceConfiguration> currentServiceConfigs) {
-
-        for (Iterator iterator = lbConfig.getServiceConfigurations().values().iterator(); iterator.hasNext();) {
-            Map<String, ServiceConfiguration> valuesMap = (Map<String, ServiceConfiguration>) iterator.next();
-            
-            for (Iterator iterator2 = valuesMap.values().iterator(); iterator2.hasNext();) {
-                ServiceConfiguration oldServiceConfig = (ServiceConfiguration) iterator2.next();
-                
-                if(!currentServiceConfigs.contains(oldServiceConfig)){
-                    // if the ServiceConfiguration is not there any more in the latest topology
-                    lbConfig.removeServiceConfiguration(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
-                    GroupMgtAgentBuilder.resetGroupMgtAgent(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
-                }
-            }
-        }
-    }
-
-    /**
-     * @param lbconfig
-     */
-    private void generateGroupMgtAgents(LoadBalancerConfiguration lbconfig) {
-        TenantLoadBalanceMembershipHandler handler =
-            ConfigHolder.getInstance()
-                .getTenantLoadBalanceMembershipHandler();
-
-        if (handler == null) {
-            String msg =
-                "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
-            log.error(msg);
-            throw new SynapseException(msg);
-        }
-
-        Map<String, HostContext> hostContexts = lbconfig.getHostContextMap();
-
-        // Add the Axis2 GroupManagement agents
-        if (hostContexts != null) {
-            // iterate through each host context
-            for (HostContext hostCtxt : hostContexts.values()) {
-                // each host can has multiple Tenant Contexts, iterate through them
-                for (TenantDomainContext tenantCtxt : hostCtxt
-                    .getTenantDomainContexts()) {
-
-                    String domain = tenantCtxt.getDomain();
-                    String subDomain = tenantCtxt.getSubDomain();
-
-                    // creates the group management agent
-                    GroupMgtAgentBuilder.createGroupMgtAgent(domain,
-                        subDomain);
-                }
-
-                // add to the handler
-                handler.addHostContext(hostCtxt);
-            }
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
deleted file mode 100644
index c7e1a1d..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint.cluster.manager;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.stratos.lb.endpoint.util.ConfigHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.wso2.carbon.cartridge.messages.ClusterDomainManager;
-import org.wso2.carbon.cartridge.messages.ClusterDomain;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.apache.stratos.lb.common.conf.util.Constants;
-import org.apache.stratos.lb.common.conf.util.HostContext;
-import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
-import org.apache.stratos.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
-import org.apache.stratos.lb.endpoint.TenantLoadBalanceMembershipHandler;
-
-/**
- * Bridge between the ELB and the Stratos2 Agent.
- */
-public class ClusterDomainManagerImpl implements ClusterDomainManager {
-
-    private static final Log log = LogFactory.getLog(ClusterDomainManagerImpl.class);
-
-    @Override
-    public void addClusterDomain(ClusterDomain cluster) {
-
-        // create group management agent, if one doesn't exist already.
-        HostContext hostCtxt = createGroupMgtAgentIfNotExists(cluster);
-
-        // we should only update if the above step is successful.
-        if (hostCtxt != null) {
-            // create / update Service Configuration
-            createOrUpdateServiceConfig(cluster, hostCtxt);
-        }
-        
-    }
-
-    @Override
-	public void removeClusterDomain(String domain, String subDomain, String hostName) {
-
-		TenantLoadBalanceMembershipHandler handler =
-		                                             ConfigHolder.getInstance()
-		                                                         .getTenantLoadBalanceMembershipHandler();
-
-		if (handler == null) {
-			String msg = "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
-			log.error(msg);
-			throw new SynapseException(msg);
-		}
-
-		handler.removeHostContext(hostName);
-		
-		LoadBalancerConfiguration lbConfig = ConfigHolder.getInstance().getLbConfig();
-		
-		lbConfig.removeServiceConfiguration(domain, subDomain);
-		
-	}
-    
-    private void createOrUpdateServiceConfig(ClusterDomain cluster, HostContext ctxt) {
-        LoadBalancerConfiguration lbConfig = ConfigHolder.getInstance().getLbConfig();
-        
-        String domain = cluster.getDomain();
-        String subDomain = cluster.getSubDomain();
-        
-        if (subDomain == null || subDomain.isEmpty()) {
-            // uses default sub domain
-            subDomain = Constants.DEFAULT_SUB_DOMAIN;
-        }
-        
-        String hostName = cluster.getHostName();
-        String tenantRange = cluster.getTenantRange();
-        int minInstances = cluster.getMinInstances();
-        int maxInstances = cluster.getMaxInstances();
-        String service = cluster.getServiceName();
-        int maxRequestsPerSecond = cluster.getMaxRequestsPerSecond();
-    	int roundsToAverage = cluster.getRoundsToAverage(); 
-    	double alarmingUpperRate = cluster.getAlarmingUpperRate();
-    	double alarmingLowerRate = cluster.getAlarmingLowerRate();
-    	double scaleDownFactor = cluster.getScaleDownFactor();
-        
-        ServiceConfiguration serviceConfig ;
-        
-        if((serviceConfig = lbConfig.getServiceConfig(domain, subDomain)) == null){
-            serviceConfig = lbConfig.new ServiceConfiguration();
-        }
-        
-        // we simply override the attributes with new values
-        serviceConfig.setDomain(domain);
-        serviceConfig.setSub_domain(subDomain);
-        serviceConfig.setTenant_range(tenantRange);
-        serviceConfig.setHosts(hostName);
-        serviceConfig.setMin_app_instances(minInstances);
-        serviceConfig.setMax_app_instances(maxInstances);
-        serviceConfig.setMax_requests_per_second(maxRequestsPerSecond);
-        serviceConfig.setRounds_to_average(roundsToAverage);
-        serviceConfig.setAlarming_upper_rate(alarmingUpperRate);
-        serviceConfig.setAlarming_lower_rate(alarmingLowerRate);
-        serviceConfig.setScale_down_factor(scaleDownFactor);
-        
-        // add to host name tracker
-        lbConfig.addToHostNameTrackerMap(service, serviceConfig.getHosts());
-        
-        // add to host contexts
-        lbConfig.addToHostContextMap(hostName, ctxt);
-        
-        // finally add this service config
-        lbConfig.addServiceConfiguration(serviceConfig);
-    }
-
-    protected HostContext createGroupMgtAgentIfNotExists(ClusterDomain cluster) {
-        
-        String domain = cluster.getDomain();
-        String subDomain = cluster.getSubDomain();
-        String hostName = cluster.getHostName();
-        String tenantRange = cluster.getTenantRange();
-
-        // sub domain can be null, but others can't
-        if (domain == null || hostName == null || tenantRange == null) {
-            String msg =
-                         "Invalid value/s detected - domain: " + domain + "\n host name: " +
-                                 hostName + "\n tenant range: " + tenantRange;
-            log.error(msg);
-            throw new SynapseException(msg);
-        }
-
-        if (subDomain == null || subDomain.isEmpty()) {
-            // uses default sub domain
-            subDomain = Constants.DEFAULT_SUB_DOMAIN;
-        }
-
-        ClusteringAgent clusteringAgent = null;
-
-        try {
-            clusteringAgent =
-                              ConfigHolder.getInstance().getAxisConfiguration()
-                                          .getClusteringAgent();
-
-        } catch (Exception e) {
-            String msg = "Failed to retrieve Clustering Agent.";
-            log.error(msg, e);
-            throw new SynapseException(msg, e);
-
-        }
-
-        if (clusteringAgent == null) {
-            String msg = "Clustering Agent is null.";
-            log.error(msg);
-            throw new SynapseException(msg);
-        }
-
-        /*
-         * Add Group Management Agent if one is not already present for this domain and sub
-         * domain
-         */
-
-        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
-            clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(subDomain),
-                                                    domain, subDomain,-1);
-
-            if (log.isDebugEnabled()) {
-                log.debug("Group management agent added to cluster domain: " + domain +
-                          " and sub domain: " + subDomain);
-            }
-
-        } else {
-            if (log.isDebugEnabled()) {
-                log.debug("Group management agent is already available for cluster domain: " +
-                          domain + " and sub domain: " + subDomain);
-            }
-        }
-
-        TenantLoadBalanceMembershipHandler handler =
-                                                     ConfigHolder.getInstance()
-                                                                 .getTenantLoadBalanceMembershipHandler();
-
-        if (handler == null) {
-            String msg = "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
-            log.error(msg);
-            throw new SynapseException(msg);
-        }
-
-        HostContext hostCtxt;
-
-        // if there's an already registered HostContext use it
-        if((hostCtxt = handler.getHostContext(hostName)) == null){
-            hostCtxt = new HostContext(hostName);
-        }
-        
-        List<TenantDomainContext> ctxts;
-        ctxts = new ArrayList<TenantDomainContext>(hostCtxt.getTenantDomainContexts());
-
-        // default value is super tenant mode - which is defined by tenant id 0, in this context
-        int tenantId = 0;
-        if(!"*".equals(tenantRange)){
-        	tenantId = Integer.parseInt(tenantRange);
-        }
-                
-        ctxts.add(new TenantDomainContext(tenantId, domain, subDomain));
-
-        hostCtxt.addTenantDomainContexts(ctxts);
-
-        handler.addHostContext(hostCtxt);
-
-        return hostCtxt;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
deleted file mode 100644
index 2945265..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
+++ /dev/null
@@ -1,531 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint.endpoint;
-
-import java.io.Serializable;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.util.AXIOMUtil;
-import org.apache.axis2.addressing.EndpointReference;
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.Member;
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.stratos.lb.endpoint.TenantAwareLoadBalanceEndpointException;
-import org.apache.stratos.lb.endpoint.internal.RegistryManager;
-import org.apache.stratos.lb.endpoint.util.ConfigHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.http.protocol.HTTP;
-import org.apache.synapse.MessageContext;
-import org.apache.synapse.SynapseConstants;
-import org.apache.synapse.SynapseException;
-import org.apache.synapse.config.xml.endpoints.utils.LoadbalanceAlgorithmFactory;
-import org.apache.synapse.core.LoadBalanceMembershipHandler;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.core.axis2.Axis2MessageContext;
-import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
-import org.apache.synapse.endpoints.DynamicLoadbalanceFaultHandler;
-import org.apache.synapse.endpoints.Endpoint;
-import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
-import org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher;
-import org.apache.synapse.endpoints.dispatch.SALSessions;
-import org.apache.synapse.endpoints.dispatch.SessionInformation;
-import org.apache.synapse.transport.nhttp.NhttpConstants;
-import org.wso2.carbon.base.MultitenantConstants;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.util.HostContext;
-import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
-import org.apache.stratos.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
-import org.apache.stratos.lb.common.util.DomainMapping;
-import org.apache.stratos.lb.common.cache.URLMappingCache;
-import org.apache.stratos.lb.endpoint.TenantLoadBalanceMembershipHandler;
-
-public class TenantAwareLoadBalanceEndpoint extends org.apache.synapse.endpoints.DynamicLoadbalanceEndpoint implements Serializable {
-
-    private static final long serialVersionUID = 1577351815951789938L;
-    private static final Log log = LogFactory.getLog(TenantAwareLoadBalanceEndpoint.class);
-    /**
-     * Axis2 based membership handler which handles members in multiple clustering domains
-     */
-    private TenantLoadBalanceMembershipHandler tlbMembershipHandler;
-
-    /**
-     * Key - host name
-     * Value - {@link HostContext}
-     */
-    private Map<String, HostContext> hostContexts = new HashMap<String, HostContext>();
-
-    private LoadBalancerConfiguration lbConfig;
-
-    /**
-     * keep the size of cache which used to keep hostNames of url mapping.
-     */
-    private URLMappingCache mappingCache;
-    private RegistryManager registryManager;
-    private int sizeOfCache;
-
-    private boolean initialized;
-
-    private String algorithm;
-        private String configuration;
-        private String failOver;
-
-    @Override
-    public void init(SynapseEnvironment synapseEnvironment) {
-        try {
-
-            lbConfig = ConfigHolder.getInstance().getLbConfig();
-            hostContexts = lbConfig.getHostContextMap();
-            sizeOfCache = lbConfig.getLoadBalancerConfig().getSizeOfCache();
-            mappingCache = URLMappingCache.getInstance(sizeOfCache);
-            setSessionTimeout(lbConfig.getLoadBalancerConfig().getSessionTimeOut());
-            setFailover(lbConfig.getLoadBalancerConfig().getFailOver());
-
-        } catch (Exception e) {
-            String msg = "Failed while reading Load Balancer configuration";
-            log.error(msg, e);
-            throw new TenantAwareLoadBalanceEndpointException(msg, e);
-        }
-
-
-        LoadbalanceAlgorithm algorithm = null;
-        try {
-            OMElement payload = AXIOMUtil.stringToOM(generatePayLoad());
-            algorithm =
-                    LoadbalanceAlgorithmFactory.
-                            createLoadbalanceAlgorithm(payload, null);
-
-        } catch (Exception e) {
-            String msg = "Error While creating Load balance algorithm";
-            log.error(msg, e);
-            throw new SynapseException(msg, e);
-        }
-
-        if (!initialized) {
-            super.init(synapseEnvironment);
-            ConfigurationContext cfgCtx =
-                                          ((Axis2SynapseEnvironment) synapseEnvironment).getAxis2ConfigurationContext();
-            ClusteringAgent clusteringAgent = cfgCtx.getAxisConfiguration().getClusteringAgent();
-            if (clusteringAgent == null) {
-                throw new SynapseException("Axis2 ClusteringAgent not defined in axis2.xml");
-            }
-
-            // Add the Axis2 GroupManagement agents
-            if (hostContexts != null) {
-                // iterate through each host context
-                for (HostContext hostCtxt : hostContexts.values()) {
-                    // each host can has multiple Tenant Contexts, iterate through them
-                    for (TenantDomainContext tenantCtxt : hostCtxt.getTenantDomainContexts()) {
-
-                        String domain = tenantCtxt.getDomain();
-                        String subDomain = tenantCtxt.getSubDomain();
-
-                        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
-                            String gmAgentClass = lbConfig.getLoadBalancerConfig().getGroupManagementAgentClass();
-                            GroupManagementAgent groupManagementAgent;
-                            if (gmAgentClass != null) {
-                                try {
-                                    groupManagementAgent = (GroupManagementAgent) Class.forName(gmAgentClass).newInstance();
-                                } catch (Exception e) {
-                                    String msg = "Cannot instantiate GroupManagementAgent. Class: " + gmAgentClass;
-                                    log.error(msg, e);
-                                    throw new TenantAwareLoadBalanceEndpointException(msg, e);
-                                }
-                            } else {
-                                groupManagementAgent = new SubDomainAwareGroupManagementAgent(subDomain);
-                            }
-                            clusteringAgent.addGroupManagementAgent(groupManagementAgent,
-                                                                    domain, subDomain,-1);
-                            if (log.isDebugEnabled()) {
-                                log.debug("Group management agent added to cluster domain: " +
-                                          domain + " and sub domain: " + subDomain);
-                            }
-                        }
-                    }
-                }
-
-                tlbMembershipHandler =
-                                       new TenantLoadBalanceMembershipHandler(hostContexts,
-                                                                              algorithm, cfgCtx,
-                                                                              isClusteringEnabled,
-                                                                              getName());
-
-                // set TenantLoadBalanceMembershipHandler for future reference
-                ConfigHolder.getInstance().setTenantLoadBalanceMembershipHandler(tlbMembershipHandler);
-            }
-
-            // Initialize the SAL Sessions if already has not been initialized.
-            SALSessions salSessions = SALSessions.getInstance();
-            if (!salSessions.isInitialized()) {
-                salSessions.initialize(isClusteringEnabled, cfgCtx);
-            }
-            setSessionAffinity(true);
-            setDispatcher(new HttpSessionDispatcher());
-            initialized = true;
-            log.info("Tenant Aware Load Balance Endpoint is initialized.");
-        }
-
-    }
-
-    	public void setConfiguration(String paramEle) {
-    	        configuration = paramEle;
-    	}
-
-    	    public void setAlgorithm(String paramEle) {
-    	        this.algorithm = paramEle;
-    	    }
-
-    	    public void setFailOver(String paramEle) {
-    	        this.failOver = paramEle;
-    	    }
-
-
-    public String getName() {
-		return "tlbEndpoint";
-	}
-
-    //TODO remove following hard coded element
-    private String generatePayLoad() {
-        return " <serviceDynamicLoadbalance failover=\"true\"\n" +
-                "                                           algorithm=\"org.apache.synapse.endpoints.algorithms.RoundRobin\"" +
-                //"                                           configuration=\"$system:loadbalancer.xml\"" +
-                "/>";
-    }
-
-    public LoadBalanceMembershipHandler getLbMembershipHandler() {
-        return tlbMembershipHandler;
-    }
-
-
-    public void send(MessageContext synCtx) {
-        /*   setCookieHeader(synCtx);     */
-        Member currentMember = null;
-        SessionInformation sessionInformation = null;
-        String actualHost = null;
-
-        //Gathering required information for domain mapping
-        org.apache.axis2.context.MessageContext axis2MessageContext =
-                                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
-        Map<String, String> transportHeaders = (Map<String, String>) axis2MessageContext.
-                getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
-        String targetHost = transportHeaders.get(HTTP.TARGET_HOST);
-
-        String port = "";
-        boolean containsPort = false;
-        if (targetHost.contains(":")) {
-            containsPort = true;
-            port = targetHost.substring(targetHost.indexOf(':') + 1, targetHost.length());
-            targetHost = targetHost.substring(0, targetHost.indexOf(':'));
-        }
-        //Gathering required information for domain mapping done
-
-        boolean isValidHost = tlbMembershipHandler.isAValidHostName(targetHost);
-        DomainMapping domainMapping = null;
-        if(!isValidHost){
-            //check if the host is valid, if not valid, execute following code to check whether it is a mapped domain
-            domainMapping = mappingCache.getMapping(targetHost);
-            if(domainMapping == null){
-                registryManager = new RegistryManager();
-                domainMapping = registryManager.getMapping(targetHost);
-                mappingCache.addValidMapping(targetHost, domainMapping);
-            }
-            if (domainMapping != null) {
-                actualHost = domainMapping.getActualHost();
-
-                if(containsPort){
-                    transportHeaders.put(HTTP.TARGET_HOST, actualHost + ":" + port);
-                } else {
-                    transportHeaders.put(HTTP.TARGET_HOST, actualHost);
-                }
-                ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty("TRANSPORT_HEADERS" , transportHeaders);
-
-            } else {
-                String msg = "Invalid host name : " + targetHost;
-                log.error(msg);
-                throw new SynapseException(msg);
-            }
-        }
-
-        if (isSessionAffinityBasedLB()) {
-            // first check if this session is associated with a session. if so, get the endpoint
-            // associated for that session.
-            sessionInformation =
-                    (SessionInformation) synCtx.getProperty(
-                            SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
-
-            currentMember = (Member) synCtx.getProperty(
-                    SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER);
-
-            if (sessionInformation == null && currentMember == null) {
-                sessionInformation = dispatcher.getSession(synCtx);
-                if (sessionInformation != null) {
-
-                    if (log.isDebugEnabled()) {
-                        log.debug("Current session id : " + sessionInformation.getId());
-                    }
-
-                    currentMember = sessionInformation.getMember();
-                    synCtx.setProperty(
-                            SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
-                    // This is for reliably recovery any session information if while response is getting ,
-                    // session information has been removed by cleaner.
-                    // This will not be a cost as  session information a not heavy data structure
-                    synCtx.setProperty(
-                            SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION, sessionInformation);
-                }
-            }
-
-        }
-
-        // Dispatch request the relevant member
-//        String targetHost = getTargetHost(synCtx);
-        ConfigurationContext configCtx =
-                ((Axis2MessageContext) synCtx).getAxis2MessageContext().getConfigurationContext();
-
-        if (tlbMembershipHandler.getConfigurationContext() == null) {
-            tlbMembershipHandler.setConfigurationContext(configCtx);
-        }
-
-        if(tlbMembershipHandler.getClusteringAgent() == null) {
-            tlbMembershipHandler.setConfigurationContext(configCtx);
-        }
-
-        TenantDynamicLoadBalanceFaultHandlerImpl faultHandler = new TenantDynamicLoadBalanceFaultHandlerImpl();
-        log.debug("************* Actual Host: "+actualHost +" ****** Target Host: "+targetHost);
-        faultHandler.setHost(actualHost != null ? actualHost : targetHost);
-
-        if (sessionInformation != null && currentMember != null) {
-            //send message on current session
-            sessionInformation.updateExpiryTime();
-            sendToApplicationMember(synCtx, currentMember, faultHandler, false);
-        } else {
-//            prepare for a new session
-            int tenantId = getTenantId(synCtx);
-            //check if this is a valid host name registered in ELB
-            if(tlbMembershipHandler.isAValidHostName(targetHost)){
-                currentMember = tlbMembershipHandler.getNextApplicationMember(targetHost, tenantId);
-                if (currentMember == null) {
-                    String msg = "No application members available";
-                    log.error(msg);
-                    throw new SynapseException(msg);
-                }
-                sendToApplicationMember(synCtx, currentMember, faultHandler, true);
-            } else {
-                if(domainMapping == null){
-                    registryManager = new RegistryManager();
-                    domainMapping = registryManager.getMapping(targetHost);
-                    mappingCache.addValidMapping(targetHost, domainMapping);
-                }
-                if(domainMapping != null) {
-
-                    actualHost = domainMapping.getActualHost();
-                    
-                    log.debug("************* Actual Host: "+actualHost +" ****** Target Host: "+targetHost);
-                    faultHandler.setHost(actualHost != null ? actualHost : targetHost);
-
-                    if(containsPort){
-                        transportHeaders.put(HTTP.TARGET_HOST, actualHost + ":" + port);
-                    } else {
-                        transportHeaders.put(HTTP.TARGET_HOST, actualHost);
-                    }
-                    ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty("TRANSPORT_HEADERS" , transportHeaders);
-
-                    currentMember = tlbMembershipHandler.getNextApplicationMember(actualHost,tenantId);
-                    sendToApplicationMember(synCtx,currentMember,faultHandler,true);
-                }else {
-                    String msg = "Invalid host name : " + targetHost;
-                    log.error(msg);
-                    throw new SynapseException(msg);
-                }
-            }
-        }
-    }
-
-
-//    public List<HostContext> getHostContexts() {
-//        return Collections.unmodifiableList(hostContexts);
-//    }
-
-    /**
-     * This FaultHandler will try to resend the message to another member if an error occurs
-     * while sending to some member. This is a failover mechanism
-     */
-
-    /**
-     * @param url to url for target
-     * @return tenantID if tenant id available else 0
-     */
-    private int getTenantId(String url) {
-        String servicesPrefix = "/t/";
-        if (url != null && url.contains(servicesPrefix)) {
-            int domainNameStartIndex =
-                    url.indexOf(servicesPrefix) + servicesPrefix.length();
-            int domainNameEndIndex = url.indexOf('/', domainNameStartIndex);
-            String domainName = url.substring(domainNameStartIndex,
-                    domainNameEndIndex == -1 ? url.length() : domainNameEndIndex);
-
-            // return tenant id if domain name is not null
-            if (domainName != null) {
-                try {
-                    return ConfigHolder.getInstance().getRealmService().getTenantManager().getTenantId(domainName);
-                } catch (org.wso2.carbon.user.api.UserStoreException e) {
-                    log.error("An error occurred while obtaining the tenant id.", e);
-                }
-            }
-        }
-        // return 0 if the domain name is null
-        return 0;
-    }
-
-    private int getTenantId(MessageContext synCtx){
-    	String url = synCtx.getTo().toString();
-    	int tenantId = getTenantId(url);
-    	// tenantId = 0 because domain name was null. May be this is the SSO response
-    	if(tenantId == 0 && url.contains(MultitenantConstants.TENANT_DOMAIN+"=")){
-    		// OK,this is the SAML SSO response from the IS
-    		// e.g url = https://localhost:9444/acs?teantDomain=domain
-    		String domainName = url.split("=").clone()[1];
-    		// return tenant id if domain name is not null
-            if (domainName != null) {
-                try {
-                    return ConfigHolder.getInstance().getRealmService().getTenantManager().getTenantId(domainName);
-                } catch (org.wso2.carbon.user.api.UserStoreException e) {
-                    log.error("An error occurred while obtaining the tenant id.", e);
-                }
-            }
-    	}
-    	return tenantId;
-    }
-
-
-    /**
-     * This FaultHandler will try to resend the message to another member if an error occurs
-     * while sending to some member. This is a failover mechanism
-     */
-    private class TenantDynamicLoadBalanceFaultHandlerImpl extends DynamicLoadbalanceFaultHandler {
-
-        private EndpointReference to;
-        private Member currentMember;
-        private Endpoint currentEp;
-        private String host;
-
-        private static final int MAX_RETRY_COUNT = 5;
-
-        // ThreadLocal variable to keep track of how many times this fault handler has been
-        // called
-        private ThreadLocal<Integer> callCount = new ThreadLocal<Integer>() {
-            protected Integer initialValue() {
-                return 0;
-            }
-        };
-
-        public void setHost(String host) {
-            log.debug("Setting host name: "+host);
-            this.host = host;
-        }
-
-        public void setCurrentMember(Member currentMember) {
-            this.currentMember = currentMember;
-        }
-
-        public void setTo(EndpointReference to) {
-            this.to = to;
-        }
-
-        private TenantDynamicLoadBalanceFaultHandlerImpl() {
-        }
-
-        public void onFault(MessageContext synCtx) {
-            if (currentMember == null || to == null) {
-                return;
-            }
-
-            // Prevent infinite retrying to failed members
-            callCount.set(callCount.get() + 1);
-            if (callCount.get() >= MAX_RETRY_COUNT) {
-                log.debug("Retrying to a failed member has stopped.");
-                return;
-            }
-
-            //cleanup endpoint if exists
-            if (currentEp != null) {
-                currentEp.destroy();
-            }
-            Integer errorCode = (Integer) synCtx.getProperty(SynapseConstants.ERROR_CODE);
-            if (errorCode != null) {
-                if (errorCode.equals(NhttpConstants.CONNECTION_FAILED)) {
-                    currentMember.suspend(10000);     // TODO: Make this configurable.
-                    log.info("Suspended member " + currentMember + " for 10s due to connection failure to that member");
-                }
-                if (errorCode.equals(NhttpConstants.CONNECTION_FAILED) ||
-                        errorCode.equals(NhttpConstants.CONNECT_CANCEL) ||
-                        errorCode.equals(NhttpConstants.CONNECT_TIMEOUT)) {
-                    
-                    if (!synCtx.getFaultStack().isEmpty()) {
-                        synCtx.getFaultStack().pop();
-                    }
-                    // Try to resend to another member
-                    Member newMember = tlbMembershipHandler.getNextApplicationMember(host, getTenantId(synCtx.toString()));
-                    if (newMember == null || newMember.isSuspended()) {
-                        String msg = "No application members available having host name : "+host+
-                                " and tenant id : "+getTenantId(synCtx.toString()+" and which is not suspended.");
-                        log.error(msg);
-                        throw new SynapseException(msg);
-                    }
-                    synCtx.setTo(to);
-                    if (isSessionAffinityBasedLB()) {
-                        // We are sending this message on a new session,
-                        // hence we need to remove previous session information
-                        Set pros = synCtx.getPropertyKeySet();
-                        if (pros != null) {
-                            pros.remove(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
-                        }
-                    }
-                    try {
-                        Thread.sleep(1000);  // Sleep for sometime before retrying
-                    } catch (InterruptedException ignored) {
-                    }
-                    
-                    if(synCtx == null || to == null) {
-                        return;
-                    }
-                    log.info("Failed over to " + newMember);
-                    sendToApplicationMember(synCtx, newMember, this, true);
-                } else if (errorCode.equals(NhttpConstants.SND_IO_ERROR_SENDING) ||
-                        errorCode.equals(NhttpConstants.CONNECTION_CLOSED)) {
-                    // TODO: Envelope is consumed
-                    String msg = "Error sending request! Connection to host "+host+
-                            " might be closed. Error code: "+errorCode;
-                    log.error(msg);
-                    throw new SynapseException(msg);
-                }
-            }
-            // We cannot failover since we are using binary relay
-        }
-
-        public void setCurrentEp(Endpoint currentEp) {
-            this.currentEp = currentEp;
-        }
-    }
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
deleted file mode 100644
index cfd2bf8..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint.group.mgt;
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.stratos.lb.endpoint.util.ConfigHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.apache.stratos.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
-
-/**
- * Responsible for building {@link GroupManagementAgent}s.
- */
-public class GroupMgtAgentBuilder {
-    
-    private static final Log log = LogFactory.getLog(GroupMgtAgentBuilder.class);
-	
-    /**
-     * Creates a {@link SubDomainAwareGroupManagementAgent} corresponds to the given 
-     * parameters, if and only if there's no existing agent.
-     * @param domain clustering domain.
-     * @param subDomain clustering sub domain.
-     */
-    public static void createGroupMgtAgent(String domain, String subDomain) {
-
-        ClusteringAgent clusteringAgent =
-            ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
-        
-        if (clusteringAgent == null) {
-            throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
-        }
-
-        // checks the existence. 
-        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
-            
-            clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(subDomain),
-                domain, subDomain,-1);
-            
-            log.info("Group management agent added to cluster domain: " +
-                domain + " and sub domain: " + subDomain);
-        }
-    }
-    
-    public static void resetGroupMgtAgent(String domain, String subDomain) {
-
-        ClusteringAgent clusteringAgent =
-            ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
-        
-        if (clusteringAgent == null) {
-            throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
-        }
-
-        // checks the existence. 
-        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) != null) {
-            
-            clusteringAgent.resetGroupManagementAgent(domain, subDomain);
-            
-            log.info("Group management agent of cluster domain: " +
-                domain + " and sub domain: " + subDomain+" is removed.");
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
deleted file mode 100644
index 2763dab..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
+++ /dev/null
@@ -1,397 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.lb.endpoint.internal;
-
-import org.apache.axis2.deployment.DeploymentEngine;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.stratos.lb.endpoint.TenantAwareLoadBalanceEndpointException;
-import org.apache.stratos.lb.endpoint.builder.TopologySyncher;
-import org.apache.stratos.lb.endpoint.cluster.manager.ClusterDomainManagerImpl;
-import org.apache.stratos.lb.endpoint.endpoint.TenantAwareLoadBalanceEndpoint;
-import org.apache.stratos.lb.endpoint.subscriber.TopologySubscriber;
-import org.apache.stratos.lb.endpoint.util.ConfigHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.Mediator;
-import org.apache.synapse.config.SynapseConfiguration;
-import org.apache.synapse.config.xml.MultiXMLConfigurationBuilder;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.deployers.SynapseArtifactDeploymentStore;
-import org.apache.synapse.endpoints.Endpoint;
-import org.apache.synapse.mediators.base.SequenceMediator;
-import org.apache.synapse.mediators.builtin.SendMediator;
-import org.apache.synapse.mediators.filters.InMediator;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.cartridge.messages.CreateClusterDomainMessage;
-import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
-import org.wso2.carbon.mediation.initializer.ServiceBusConstants;
-import org.wso2.carbon.mediation.initializer.ServiceBusUtils;
-import org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService;
-import org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService;
-import org.wso2.carbon.mediation.initializer.services.SynapseRegistrationsService;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.utils.ConfigurationContextService;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
-import org.apache.stratos.lb.endpoint.EndpointDeployer;
-import org.apache.stratos.lb.endpoint.util.TopologyConstants;
-
-import java.io.File;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @scr.component name="org.apache.stratos.load.balancer.endpoint" immediate="true"
- * @scr.reference name="configuration.context.service"
- * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
- * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
- * @scr.reference name="synapse.config.service"
- * interface="org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService"
- * cardinality="1..1" policy="dynamic" bind="setSynapseConfigurationService"
- * unbind="unsetSynapseConfigurationService"
- * @scr.reference name="synapse.env.service"
- * interface="org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService"
- * cardinality="1..n" policy="dynamic" bind="setSynapseEnvironmentService"
- * unbind="unsetSynapseEnvironmentService"
- * @scr.reference name="registry.service"
- * interface="org.wso2.carbon.registry.core.service.RegistryService"
- * cardinality="1..1" policy="dynamic"
- * bind="setRegistryService" unbind="unsetRegistryService"
- * @scr.reference name="dependency.mgt.service"
- * interface="org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService"
- * cardinality="0..1" policy="dynamic"
- * bind="setDependencyManager" unbind="unsetDependencyManager"
- * @scr.reference name="synapse.registrations.service"
- * interface="org.wso2.carbon.mediation.initializer.services.SynapseRegistrationsService"
- * cardinality="1..n" policy="dynamic" bind="setSynapseRegistrationsService"
- * unbind="unsetSynapseRegistrationsService"
- * @scr.reference name="user.realmservice.default"
- * interface="org.wso2.carbon.user.core.service.RealmService"
- * cardinality="1..1" policy="dynamic" bind="setRealmService"
- * unbind="unsetRealmService"
- * @scr.reference name="org.apache.stratos.lb.common"
- * interface="org.apache.stratos.lb.common.service.LoadBalancerConfigurationService"
- * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
- * unbind="unsetLoadBalancerConfigurationService"
- */
-@SuppressWarnings({"UnusedDeclaration", "JavaDoc"})
-public class LoadBalanceEndpointServiceComponent {
-
-    private static final Log log = LogFactory.getLog(LoadBalanceEndpointServiceComponent.class);
-
-    private boolean activated = false;
-
-    protected void activate(ComponentContext ctxt) {
-        try {
-            SynapseEnvironmentService synEnvService =
-                                                      ConfigHolder.getInstance()
-                                                                  .getSynapseEnvironmentService(MultitenantConstants.SUPER_TENANT_ID);
-
-            registerDeployer(ConfigHolder.getInstance().getAxisConfiguration(),
-                             synEnvService.getSynapseEnvironment());
-
-			      if (ConfigHolder.getInstance().getConfigCtxt() != null) {
-				      ConfigHolder
-						    .getInstance()
-						    .getConfigCtxt()
-						    .setNonReplicableProperty(
-								CreateClusterDomainMessage.CLUSTER_DOMAIN_MANAGER,
-								new ClusterDomainManagerImpl());
-				        log.debug("Setting property Cluster Domain MANAGER ... ");
-
-		  	    }
-			
-            SynapseEnvironment synapseEnv = synEnvService.getSynapseEnvironment();
-
-            /* Registering Tenant Aware Load Balance Endpoint */
-
-            // get the main sequence mediator
-            SequenceMediator mainSequence =
-                                            (SequenceMediator) synapseEnv.getSynapseConfiguration()
-                                                                         .getSequence("main");
-
-            boolean successfullyRegistered = false;
-            
-            // iterate through its child mediators
-            for (Mediator child : mainSequence.getList()) {
-
-                // find the InMediator
-                if (child instanceof InMediator) {
-                    
-                    for(Mediator inChild : ((InMediator)child).getList()){
-                        
-                        // find the SendMediator
-                        if (inChild instanceof SendMediator) {
-                            
-                            SendMediator sendMediator = (SendMediator) inChild;
-                            
-                            /* add Tenant Aware LB endpoint */
-                            
-                            TenantAwareLoadBalanceEndpoint tenantAwareEp = new TenantAwareLoadBalanceEndpoint();
-
-                            tenantAwareEp.init(synapseEnv);
-                            
-                            sendMediator.setEndpoint(tenantAwareEp);
-                            
-                            successfullyRegistered = true;
-
-                            if (log.isDebugEnabled()) {
-                                log.debug("Added Tenant Aware Endpoint: " +
-                                          sendMediator.getEndpoint().getName() + "" +
-                                          " to Send Mediator.");
-                            }
-                        }
-                    }
-                }
-            }
-            
-            if(!successfullyRegistered){
-                String msg = "Failed to register Tenant Aware Load Balance Endpoint in Send Mediator.";
-                log.fatal(msg);
-                throw new TenantAwareLoadBalanceEndpointException(msg);
-            }
-
-            if (log.isDebugEnabled()) {
-                log.debug("Endpoint Admin bundle is activated ");
-            }
-            
-            if (ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl() != null) {
-
-                // start consumer
-                // initialize TopologyBuilder Consumer
-                Thread topologyConsumer =
-                    new Thread(new TopologySyncher(ConfigHolder.getInstance().getSharedTopologyDiffQueue()));
-                // start consumer
-                topologyConsumer.start();
-
-                TopologySubscriber.subscribe(TopologyConstants.TOPIC_NAME);
-
-            }
-            activated = true;
-        } catch (Throwable e) {
-            log.error("Failed to activate Endpoint Admin bundle ", e);
-        }
-    }
-
-    protected void deactivate(ComponentContext context) {
-        try {
-            Set<Map.Entry<Integer, SynapseEnvironmentService>> entrySet =
-                    ConfigHolder.getInstance().getSynapseEnvironmentServices().entrySet();
-            for (Map.Entry<Integer, SynapseEnvironmentService> entry : entrySet) {
-                unregisterDeployer(
-                        entry.getValue().getConfigurationContext().getAxisConfiguration(),
-                        entry.getValue().getSynapseEnvironment());
-            }
-        } catch (Exception e) {
-            log.warn("Couldn't remove the EndpointDeployer");
-        }
-    }
-
-    /**
-     * Un-registers the Endpoint deployer.
-     *
-     * @param axisConfig         AxisConfiguration to which this deployer belongs
-     * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
-     */
-    private void unregisterDeployer(AxisConfiguration axisConfig, SynapseEnvironment synapseEnvironment)
-            throws TenantAwareLoadBalanceEndpointException {
-        if (axisConfig != null) {
-            DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig.getConfigurator();
-            String synapseConfigPath = ServiceBusUtils.getSynapseConfigAbsPath(
-                    synapseEnvironment.getServerContextInformation());
-            String endpointDirPath = synapseConfigPath
-                    + File.separator + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
-            deploymentEngine.removeDeployer(
-                    endpointDirPath, ServiceBusConstants.ARTIFACT_EXTENSION);
-        }
-    }
-
-    /**
-     * Registers the Endpoint deployer.
-     *
-     * @param axisConfig         AxisConfiguration to which this deployer belongs
-     * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
-     */
-    private void registerDeployer(AxisConfiguration axisConfig, SynapseEnvironment synapseEnvironment)
-            throws TenantAwareLoadBalanceEndpointException {
-        SynapseConfiguration synCfg = synapseEnvironment.getSynapseConfiguration();
-        DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig.getConfigurator();
-        SynapseArtifactDeploymentStore deploymentStore = synCfg.getArtifactDeploymentStore();
-
-        String synapseConfigPath = ServiceBusUtils.getSynapseConfigAbsPath(
-                synapseEnvironment.getServerContextInformation());
-        String endpointDirPath = synapseConfigPath
-                + File.separator + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
-
-        for (Endpoint ep : synCfg.getDefinedEndpoints().values()) {
-            if (ep.getFileName() != null) {
-                deploymentStore.addRestoredArtifact(
-                        endpointDirPath + File.separator + ep.getFileName());
-            }
-        }
-        deploymentEngine.addDeployer(
-                new EndpointDeployer(), endpointDirPath, ServiceBusConstants.ARTIFACT_EXTENSION);
-    }
-
-    protected void setConfigurationContextService(ConfigurationContextService cfgCtxService) {
-        ConfigHolder.getInstance().setAxisConfiguration(
-                cfgCtxService.getServerConfigContext().getAxisConfiguration());
-        ConfigHolder.getInstance().setConfigCtxt(cfgCtxService.getServerConfigContext());
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService cfgCtxService) {
-        ConfigHolder.getInstance().setAxisConfiguration(null);
-        ConfigHolder.getInstance().setConfigCtxt(null);
-    }
-
-    protected void setSynapseConfigurationService(
-            SynapseConfigurationService synapseConfigurationService) {
-
-        ConfigHolder.getInstance().setSynapseConfiguration(
-                synapseConfigurationService.getSynapseConfiguration());
-    }
-
-    protected void unsetSynapseConfigurationService(
-            SynapseConfigurationService synapseConfigurationService) {
-
-        ConfigHolder.getInstance().setSynapseConfiguration(null);
-    }
-
-    /**
-     * Here we receive an event about the creation of a SynapseEnvironment. If this is
-     * SuperTenant we have to wait until all the other constraints are met and actual
-     * initialization is done in the activate method. Otherwise we have to do the activation here.
-     *
-     * @param synapseEnvironmentService SynapseEnvironmentService which contains information
-     *                                  about the new Synapse Instance
-     */
-    protected void setSynapseEnvironmentService(
-            SynapseEnvironmentService synapseEnvironmentService) {
-        boolean alreadyCreated = ConfigHolder.getInstance().getSynapseEnvironmentServices().
-                containsKey(synapseEnvironmentService.getTenantId());
-
-        ConfigHolder.getInstance().addSynapseEnvironmentService(
-                synapseEnvironmentService.getTenantId(),
-                synapseEnvironmentService);
-        if (activated) {
-            if (!alreadyCreated) {
-                try {
-                    registerDeployer(synapseEnvironmentService.getConfigurationContext().getAxisConfiguration(),
-                            synapseEnvironmentService.getSynapseEnvironment());
-                    if (log.isDebugEnabled()) {
-                        log.debug("Endpoint Admin bundle is activated ");
-                    }
-                } catch (Throwable e) {
-                    log.error("Failed to activate Endpoint Admin bundle ", e);
-                }
-            }
-        }
-    }
-
-    /**
-     * Here we receive an event about Destroying a SynapseEnvironment. This can be the super tenant
-     * destruction or a tenant destruction.
-     *
-     * @param synapseEnvironmentService synapseEnvironment
-     */
-    protected void unsetSynapseEnvironmentService(
-            SynapseEnvironmentService synapseEnvironmentService) {
-        ConfigHolder.getInstance().removeSynapseEnvironmentService(
-                synapseEnvironmentService.getTenantId());
-    }
-
-    protected void setRegistryService(RegistryService regService) {
-        if (log.isDebugEnabled()) {
-            log.debug("RegistryService bound to the endpoint component");
-        }
-        try {
-            ConfigHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
-            ConfigHolder.getInstance().setGovernanceRegistry(regService.getGovernanceSystemRegistry());
-        } catch (RegistryException e) {
-            log.error("Couldn't retrieve the registry from the registry service");
-        }
-    }
-
-    protected void unsetRegistryService(RegistryService regService) {
-        if (log.isDebugEnabled()) {
-            log.debug("RegistryService unbound from the endpoint component");
-        }
-        ConfigHolder.getInstance().setConfigRegistry(null);
-    }
-
-    protected void setDependencyManager(DependencyManagementService dependencyMgr) {
-        if (log.isDebugEnabled()) {
-            log.debug("Dependency management service bound to the endpoint component");
-        }
-        ConfigHolder.getInstance().setDependencyManager(dependencyMgr);
-    }
-
-    protected void unsetDependencyManager(DependencyManagementService dependencyMgr) {
-        if (log.isDebugEnabled()) {
-            log.debug("Dependency management service unbound from the endpoint component");
-        }
-        ConfigHolder.getInstance().setDependencyManager(null);
-    }
-
-    protected void setSynapseRegistrationsService(
-            SynapseRegistrationsService synapseRegistrationsService) {
-
-    }
-
-    protected void unsetSynapseRegistrationsService(
-            SynapseRegistrationsService synapseRegistrationsService) {
-        int tenantId = synapseRegistrationsService.getTenantId();
-        if (ConfigHolder.getInstance().getSynapseEnvironmentServices().containsKey(tenantId)) {
-            SynapseEnvironment env = ConfigHolder.getInstance().
-                    getSynapseEnvironmentService(tenantId).getSynapseEnvironment();
-
-            ConfigHolder.getInstance().removeSynapseEnvironmentService(
-                    synapseRegistrationsService.getTenantId());
-
-            AxisConfiguration axisConfig = synapseRegistrationsService.getConfigurationContext().
-                    getAxisConfiguration();
-            if (axisConfig != null) {
-                try {
-                    unregisterDeployer(axisConfig, env);
-                } catch (Exception e) {
-                    log.warn("Couldn't remove the EndpointDeployer");
-                }
-            }
-        }
-    }
-
-    protected void setRealmService(RealmService realmService) {
-        ConfigHolder.getInstance().setRealmService(realmService);
-    }
-
-    protected void unsetRealmService(RealmService realmService) {
-        ConfigHolder.getInstance().setRealmService(null);
-    }
-    
-    protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
-        ConfigHolder.getInstance().setLbConfigService(lbConfigSer);
-    }
-    
-    protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
-        ConfigHolder.getInstance().setLbConfigService(null);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/internal/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/internal/RegistryManager.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/internal/RegistryManager.java
deleted file mode 100644
index 2f91002..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/internal/RegistryManager.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.endpoint.util.ConfigHolder;
-import org.apache.stratos.lb.common.util.DomainMapping;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-
-public class RegistryManager {
-    UserRegistry governanceRegistry = ConfigHolder.getInstance().getGovernanceRegistry();
-    private static final Log log = LogFactory.getLog(RegistryManager.class);
-    /**
-     *
-     */
-    private Resource resource = null;
-    public static final String HOST_INFO = "hostinfo/";
-    public static final String ACTUAL_HOST = "actual.host";
-
-    public DomainMapping getMapping(String hostName) {
-        DomainMapping domainMapping;
-        try {
-            if (governanceRegistry.resourceExists(HOST_INFO + hostName)) {
-                resource = governanceRegistry.get(HOST_INFO + hostName);
-                domainMapping = new DomainMapping(hostName);
-                domainMapping.setActualHost(resource.getProperty(ACTUAL_HOST));
-                return domainMapping;
-            }
-        } catch (RegistryException e) {
-            log.info("Error while getting registry resource");
-            throw new RuntimeException(e);
-        }
-        return null;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopicHealthChecker.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopicHealthChecker.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopicHealthChecker.java
deleted file mode 100644
index e9da865..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopicHealthChecker.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint.subscriber;
-
-import javax.jms.TopicSubscriber;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * This health checker runs forever, and is responsible for re-establishing a connection
- * between ELB and CC.
- */
-public class TopicHealthChecker implements Runnable{
-    
-    private static final Log log = LogFactory.getLog(TopicHealthChecker.class);
-    private String topicName;
-    private TopicSubscriber subscriber;
-
-    public TopicHealthChecker(String topicName, TopicSubscriber subscriber) {
-        this.topicName = topicName;
-        this.subscriber = subscriber;
-    }
-    
-    @Override
-    public void run() {
-        log.info("Topic Health Checker is running... ");
-
-        while (true) {
-            try {
-                subscriber.getTopic();
-                
-                // health checker runs in every 30s
-                Thread.sleep(30000);
-
-            } catch (Exception e) {
-                // implies connection is not established
-                // sleep for 5s and retry
-                try {
-                    log.info("Health checker failed and will retry to establish a connection after a 5s.");
-                    Thread.sleep(5000);
-                    break;
-                } catch (InterruptedException ignore) {
-                }
-            }
-
-        }
-
-        TopologySubscriber.subscribe(topicName);
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologyListener.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologyListener.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologyListener.java
deleted file mode 100644
index ee7a3ca..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologyListener.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint.subscriber;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.TextMessage;
-
-import org.apache.stratos.lb.endpoint.util.ConfigHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class TopologyListener implements MessageListener {
-
-	private static final Log log = LogFactory.getLog(TopologyListener.class);
-
-	@Override
-    public void onMessage(Message message) {
-		TextMessage receivedMessage = (TextMessage) message;
-        try {
-            
-            ConfigHolder.getInstance().getSharedTopologyDiffQueue().add(receivedMessage.getText());
-
-        } catch (JMSException e) {
-        	log.error(e.getMessage(), e);
-        }
-
-    }
-
-}


[29/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/conf/cartridge-config.properties
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/conf/cartridge-config.properties b/components/org.apache.stratos.adc.mgt/src/conf/cartridge-config.properties
new file mode 100644
index 0000000..b495014
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/conf/cartridge-config.properties
@@ -0,0 +1,38 @@
+# Configuration properties
+
+sc.ip=s2_ip
+autoscalerService.url=https://cc.wso2.com:9444/services/CloudControllerService/
+autoscaler.time.out=190000
+cartridge.agent.epr=https://s2_ip:9447/services/CartridgeAgentService
+git.host.name=s2_hostname
+git.host.ip=s2_ip
+git.repo.notification.url=https://sc.wso2.com:9445/services/RepoNotificationService/
+identity.server.url=https://sc.wso2.com:9447/services/RepoNotificationService/
+
+adc.jdbc.url=jdbc:h2:repository/database/WSO2S2_DB
+adc.jdbc.username=wso2carbon
+adc.jdbc.password=wso2carbon
+adc.jdbc.driver=org.h2.Driver
+
+mb.server.ip=cc.wso2.com:5673
+
+feature.externalrepo.validation.enabled=true
+feature.internalrepo.enabled=false
+feature.multitenant.multiplesubscription.enabled=false
+
+internal.repo.username=admin
+internal.repo.password=admin
+
+append.script=SCRIPT_PATH/add_entry_zone_file.sh
+remove.script=SCRIPT_PATH/remove_entry_zone_file.sh
+bind.file.path=/etc/bind/db.STRATOS_DOMAIN
+elb.ip=s2_ip
+
+bam.ip=s2_ip
+bam.port=7714
+
+max.attempts=1000
+
+cartridge.key=KEYPATH
+
+repository.info.epr=https://s2_ip:9445/services/RepositoryInformationService

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/conf/tenant-resource-policy.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/conf/tenant-resource-policy.xml b/components/org.apache.stratos.adc.mgt/src/conf/tenant-resource-policy.xml
new file mode 100644
index 0000000..12bbf74
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/conf/tenant-resource-policy.xml
@@ -0,0 +1 @@
+<?xml version="1.0" encoding="UTF-8"?>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CartridgeAgentClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CartridgeAgentClient.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CartridgeAgentClient.java
new file mode 100644
index 0000000..3731107
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CartridgeAgentClient.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.client;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.internal.DataHolder;
+import org.wso2.carbon.cartridge.agent.stub.CartridgeAgentServiceStub;
+
+public class CartridgeAgentClient {
+
+	private static final Log log = LogFactory.getLog(CartridgeAgentClient.class);
+	CartridgeAgentServiceStub stub = null;
+	public CartridgeAgentClient(String epr) throws AxisFault {
+	  ConfigurationContext clientConfigContext = DataHolder.getClientConfigContext();
+	  stub = new CartridgeAgentServiceStub(clientConfigContext, epr);
+    }
+	
+	public void unregister(String domain, String subDomain, String hostName) throws Exception {
+		log.info(" ** Unregistering -- ");
+		stub.unregister(domain, subDomain, hostName);
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java
new file mode 100644
index 0000000..6dbba78
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/CloudControllerServiceClient.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.client;
+
+import java.rmi.RemoteException;
+
+import javax.activation.DataHandler;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.exception.UnregisteredCartridgeException;
+import org.apache.stratos.adc.mgt.internal.DataHolder;
+import org.apache.stratos.cloud.controller.stub.CloudControllerServiceStub;
+import org.apache.stratos.cloud.controller.stub.CloudControllerServiceUnregisteredCartridgeExceptionException;
+import org.apache.stratos.cloud.controller.util.xsd.CartridgeInfo;
+import org.apache.stratos.cloud.controller.util.xsd.Properties;
+
+public class CloudControllerServiceClient {
+
+	private CloudControllerServiceStub stub;
+
+	private static final Log log = LogFactory.getLog(CloudControllerServiceClient.class);
+
+	public CloudControllerServiceClient(String epr) throws AxisFault {
+
+		ConfigurationContext clientConfigContext = DataHolder.getClientConfigContext();
+		try {
+			stub = new CloudControllerServiceStub(clientConfigContext, epr);
+			stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);
+
+		} catch (AxisFault axisFault) {
+			String msg = "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
+			log.error(msg, axisFault);
+			throw new AxisFault(msg, axisFault);
+		}
+
+	}
+
+	public boolean register(String domainName, String subDomain, String cartridgeType,
+	                        DataHandler payload, String tenantRange, String hostName, Properties properties) throws RemoteException, CloudControllerServiceUnregisteredCartridgeExceptionException
+	                                                                                  {		
+		return stub.registerService(domainName, subDomain, tenantRange, cartridgeType, hostName,
+		                            properties, payload);
+
+	}
+
+	public String startInstance(String domain, String subDomain) throws Exception {
+		return stub.startInstance(domain, subDomain);
+	}
+
+	public boolean terminateAllInstances(String domain, String subDomain) throws Exception {
+		return stub.terminateAllInstances(domain, subDomain);
+	}
+
+	public String[] getRegisteredCartridges() throws Exception {
+		return stub.getRegisteredCartridges();
+	}
+
+	public boolean createKeyPair(String cartridge, String keyPairName, String publicKey)
+	                                                                                    throws Exception {
+		return stub.createKeyPairFromPublicKey(cartridge, keyPairName, publicKey);
+	}
+
+	public CartridgeInfo getCartridgeInfo(String cartridgeType) throws UnregisteredCartridgeException, Exception {
+		try {
+			return stub.getCartridgeInfo(cartridgeType);
+		} catch (RemoteException e) {
+			throw e;
+		} catch (CloudControllerServiceUnregisteredCartridgeExceptionException e) {
+			throw new UnregisteredCartridgeException("Not a registered cartridge " + cartridgeType, cartridgeType, e);
+		}
+	}
+	
+	public boolean unregisterService(String domain, String subDomain) throws Exception {
+	    return stub.unregisterService(domain, subDomain);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/RegistryClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/RegistryClient.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/RegistryClient.java
new file mode 100644
index 0000000..c1d6cd3
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/client/RegistryClient.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.client;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.UUID;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.apache.commons.io.IOUtils;
+import org.wso2.carbon.registry.core.Association;
+import org.wso2.carbon.registry.core.Collection;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
+
+public class RegistryClient {
+
+	// url where the repository is running its services interface
+	private static String backendURL = "http://localhost:9763/services/";
+	private static ConfigurationContext configContext = null;
+
+	// configuration locations used to bootstrap axis2
+	private static String axis2Repo =
+	                                  "/home/wso2/Desktop/HP-demo-packs-with-video/cartridge/wso2stratos-cartridge-1.0.0-SNAPSHOT/repository/conf/axis2";
+	private static String axis2Conf =
+	                                  "/home/wso2/Desktop/HP-demo-packs-with-video/cartridge/wso2stratos-cartridge-1.0.0-SNAPSHOT/repository/conf/axis2/axis2_client.xml";
+	private static String serverURL = "https://localhost:9443/services/";
+
+	public RegistryClient() {
+		// TODO Auto-generated constructor stub
+	}
+
+	private static WSRegistryServiceClient initialize() throws Exception {
+		// set these properties, this is used for authentication over https to
+		// the registry
+		// if you have a newer version, you can update the keystore by copying
+		// it from
+		// the security directory of the repository
+		System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
+		System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
+		System.setProperty("javax.net.ssl.trustStoreType", "JKS");
+
+		configContext =
+		                ConfigurationContextFactory.createConfigurationContextFromFileSystem(axis2Repo,
+		                                                                                     axis2Conf);
+		return new WSRegistryServiceClient(serverURL, "admin", "admin", backendURL, configContext);
+	}
+
+	public static void addKey(String keyName, String content) throws Exception {
+		Registry registry = initialize();
+
+		// get the governance folder
+		Resource governanceFolder = registry.get("/_system/governance");
+		System.out.println("Folder description: " + governanceFolder.getDescription());
+		Resource r1 = registry.newResource();
+		String path = "/_system/governance/" + keyName;
+		r1.setContent(content);
+		registry.put(path, r1);
+
+		/*
+		 * List<Resource> paths = getServicePath(registry,
+		 * "/_system/governance/trunk/services");
+		 * 
+		 * for (Resource service : paths) { // we've got all the services here
+		 * 
+		 * Properties props = service.getProperties(); for (Object prop :
+		 * props.keySet()) { System.out.println(prop + " - " + props.get(prop));
+		 * }
+		 * 
+		 * Association[] associations =
+		 * registry.getAssociations(service.getPath(), "Documentation"); for
+		 * (Association association : associations) {
+		 * System.out.println(association.getAssociationType()); } }
+		 */
+	}
+
+	private static List<Resource> getServicePath(Registry registry, String servicesResource)
+	                                                                                        throws RegistryException {
+		List<Resource> result = new ArrayList<Resource>();
+		Resource resource = registry.get(servicesResource);
+
+		if (resource instanceof Collection) {
+			Object content = resource.getContent();
+			for (Object path : (Object[]) content) {
+				result.addAll(getServicePath(registry, (String) path));
+			}
+		} else if (resource instanceof Resource) {
+			result.add(resource);
+		}
+		return result;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/custom/domain/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/custom/domain/RegistryManager.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/custom/domain/RegistryManager.java
new file mode 100644
index 0000000..d53fcc0
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/custom/domain/RegistryManager.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.custom.domain;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.exception.ADCException;
+import org.apache.stratos.adc.mgt.exception.DomainMappingExistsException;
+import org.apache.stratos.adc.mgt.internal.DataHolder;
+import org.apache.stratos.adc.mgt.utils.CartridgeConstants;
+import org.wso2.carbon.registry.core.Collection;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+
+public class RegistryManager {
+	private static Log log = LogFactory.getLog(RegistryManager.class);
+	private static Registry registry = DataHolder.getRegistry();
+
+	public RegistryManager() {
+		try {
+			if (!registry.resourceExists(CartridgeConstants.DomainMappingInfo.HOSTINFO)) {
+				registry.put(CartridgeConstants.DomainMappingInfo.HOSTINFO,
+				                    registry.newCollection());
+			}
+		} catch (RegistryException e) {
+			String msg =
+			             "Error while accessing registry or initializing domain mapping registry path\n";
+			log.error(msg + e.getMessage());
+		}
+	}
+
+	/**
+    *
+    */
+    public void addDomainMappingToRegistry(String hostName, String actualHost)
+            throws ADCException, RegistryException, DomainMappingExistsException {
+        try {
+            registry.beginTransaction();
+            Resource hostResource = registry.newResource();
+            hostResource.addProperty(CartridgeConstants.DomainMappingInfo.ACTUAL_HOST, actualHost);
+            if (!registry.resourceExists(CartridgeConstants.DomainMappingInfo.HOSTINFO +
+                                                hostName)) {
+                registry.put(CartridgeConstants.DomainMappingInfo.HOSTINFO + hostName,
+                                    hostResource);
+            } else {
+                registry.rollbackTransaction();
+                String msg = "Requested domain is already taken!";
+                log.error(msg);
+                throw new DomainMappingExistsException(msg, hostName);
+            }
+            registry.commitTransaction();
+        } catch (RegistryException e) {
+            registry.rollbackTransaction();
+            throw e; 
+        }
+    }
+
+
+    /**
+        *
+        */
+   	public void removeDomainMappingFromRegistry(String actualHost) throws Exception {
+   		try {
+               registry.beginTransaction();
+                String hostResourcePath = CartridgeConstants.DomainMappingInfo.HOSTINFO;
+                if (registry.resourceExists(hostResourcePath)) {
+                    Resource hostResource = registry.get(hostResourcePath);
+                    Collection hostInfoCollection;
+                    if(hostResource instanceof Collection){
+                        hostInfoCollection = (Collection) hostResource;
+                    } else {
+                        throw new Exception("Resource is not a collection " + hostResourcePath );
+                    }
+                    String[] paths = hostInfoCollection.getChildren();
+                    for (String path: paths){
+                        Resource domainMapping = registry.get(path);
+                        String actualHostInRegistry = domainMapping.getProperty(CartridgeConstants.DomainMappingInfo.ACTUAL_HOST);
+                        if(actualHostInRegistry != null && actualHost.equalsIgnoreCase(actualHostInRegistry)){
+                            registry.delete(path);
+                        }
+                    }
+                }
+                registry.commitTransaction();
+   		} catch (RegistryException e) {
+   			registry.rollbackTransaction();
+   			log.error("Unable to remove the mapping", e);
+   			throw e;
+   		}
+   	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/CartridgeSubscription.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/CartridgeSubscription.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/CartridgeSubscription.java
new file mode 100644
index 0000000..9d48b0f
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/CartridgeSubscription.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.dao;
+
+import java.util.List;
+
+public class CartridgeSubscription {
+
+	private int subscriptionId;
+	private int tenantId;
+	private String cartridge;
+	private String provider;
+	private String hostName;
+	private String policy;
+	private List<PortMapping> portMappings;
+	private String clusterDomain;
+	private String clusterSubdomain;
+	private Repository repository;
+	private String state;
+	private String alias;
+	private String tenantDomain;
+	private DataCartridge dataCartridge;
+	private String baseDirectory;
+	private String mappedDomain;
+	private String mgtClusterDomain;
+	private String mgtClusterSubDomain;
+
+	public int getSubscriptionId() {
+		return subscriptionId;
+	}
+
+	public void setSubscriptionId(int subscriptionId) {
+		this.subscriptionId = subscriptionId;
+	}
+
+	public int getTenantId() {
+		return tenantId;
+	}
+
+	public void setTenantId(int tenantId) {
+		this.tenantId = tenantId;
+	}
+
+	public String getCartridge() {
+		return cartridge;
+	}
+
+	public void setCartridge(String cartridge) {
+		this.cartridge = cartridge;
+	}
+
+	public String getProvider() {
+		return provider;
+	}
+
+	public void setProvider(String provider) {
+		this.provider = provider;
+	}
+
+	public String getHostName() {
+		return hostName;
+	}
+
+	public void setHostName(String hostName) {
+		this.hostName = hostName;
+	}
+
+	public String getPolicy() {
+		return policy;
+	}
+
+	public void setPolicy(String policy) {
+		this.policy = policy;
+	}
+
+	public List<PortMapping> getPortMappings() {
+		return portMappings;
+	}
+
+	public void setPortMappings(List<PortMapping> portMappings) {
+		this.portMappings = portMappings;
+	}
+
+	public String getClusterDomain() {
+		return clusterDomain;
+	}
+
+	public void setClusterDomain(String clusterDomain) {
+		this.clusterDomain = clusterDomain;
+	}
+
+	public String getClusterSubdomain() {
+		return clusterSubdomain;
+	}
+
+	public void setClusterSubdomain(String clusterSubdomain) {
+		this.clusterSubdomain = clusterSubdomain;
+	}
+
+	public Repository getRepository() {
+		return repository;
+	}
+
+	public void setRepository(Repository repository) {
+		this.repository = repository;
+	}
+
+	public String getState() {
+		return state;
+	}
+
+	public void setState(String state) {
+		this.state = state;
+	}
+
+	public String getAlias() {
+		return alias;
+	}
+
+	public void setAlias(String alias) {
+		this.alias = alias;
+	}
+
+	public String getTenantDomain() {
+		return tenantDomain;
+	}
+
+	public void setTenantDomain(String tenantDomain) {
+		this.tenantDomain = tenantDomain;
+	}
+
+	public DataCartridge getDataCartridge() {
+		return dataCartridge;
+	}
+
+	public void setDataCartridge(DataCartridge dataCartridge) {
+		this.dataCartridge = dataCartridge;
+	}
+
+	public String getBaseDirectory() {
+		return baseDirectory;
+	}
+
+	public void setBaseDirectory(String baseDirectory) {
+		this.baseDirectory = baseDirectory;
+	}
+
+	public String getMappedDomain() {
+		return mappedDomain;
+	}
+
+	public void setMappedDomain(String mappedDomain) {
+		this.mappedDomain = mappedDomain;
+	}
+
+	public String getMgtClusterDomain() {
+		return mgtClusterDomain;
+	}
+
+	public void setMgtClusterDomain(String mgtClusterDomain) {
+		this.mgtClusterDomain = mgtClusterDomain;
+	}
+
+	public String getMgtClusterSubDomain() {
+		return mgtClusterSubDomain;
+	}
+
+	public void setMgtClusterSubDomain(String mgtClusterSubDomain) {
+		this.mgtClusterSubDomain = mgtClusterSubDomain;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/DataCartridge.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/DataCartridge.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/DataCartridge.java
new file mode 100644
index 0000000..8e43079
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/DataCartridge.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.dao;
+
+public class DataCartridge {
+
+	private int id;
+	private String dataCartridgeType;
+	private String userName;
+	private String password;
+	public int getId() {
+    	return id;
+    }
+	public void setId(int id) {
+    	this.id = id;
+    }
+	public String getDataCartridgeType() {
+    	return dataCartridgeType;
+    }
+	public void setDataCartridgeType(String dataCartridgeType) {
+    	this.dataCartridgeType = dataCartridgeType;
+    }
+	public String getUserName() {
+    	return userName;
+    }
+	public void setUserName(String userName) {
+    	this.userName = userName;
+    }
+	public String getPassword() {
+    	return password;
+    }
+	public void setPassword(String password) {
+    	this.password = password;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/PortMapping.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/PortMapping.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/PortMapping.java
new file mode 100644
index 0000000..5916847
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/PortMapping.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.dao;
+
+public class PortMapping {
+	private int id;
+	private String type;
+	private String primaryPort;
+	private String proxyPort;
+
+	public int getId() {
+		return id;
+	}
+
+	public void setId(int id) {
+		this.id = id;
+	}
+
+	public String getType() {
+		return type;
+	}
+
+	public void setType(String type) {
+		this.type = type;
+	}
+
+	public String getPrimaryPort() {
+		return primaryPort;
+	}
+
+	public void setPrimaryPort(String primaryPort) {
+		this.primaryPort = primaryPort;
+	}
+
+	public String getProxyPort() {
+		return proxyPort;
+	}
+
+	public void setProxyPort(String proxyPort) {
+		this.proxyPort = proxyPort;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/Repository.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/Repository.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/Repository.java
new file mode 100644
index 0000000..a951e78
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/Repository.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.dao;
+
+public class Repository {
+	private int repoId;
+	private String repoName;
+    private String repoUserName;
+    private String repoUserPassword;
+
+	public int getRepoId() {
+		return repoId;
+	}
+
+	public void setRepoId(int repoId) {
+		this.repoId = repoId;
+	}
+
+	public String getRepoName() {
+		return repoName;
+	}
+
+	public void setRepoName(String repoName) {
+		this.repoName = repoName;
+	}
+
+    public String getRepoUserName() {
+        return repoUserName;
+    }
+
+    public void setRepoUserName(String repoUserName) {
+        this.repoUserName=repoUserName;
+    }
+
+    public String getRepoUserPassword() {
+        return repoUserPassword;
+    }
+
+    public void setRepoUserPassword(String repoUserPassword) {
+        this.repoUserPassword=repoUserPassword;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/RepositoryCredentials.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/RepositoryCredentials.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/RepositoryCredentials.java
new file mode 100644
index 0000000..90670e7
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dao/RepositoryCredentials.java
@@ -0,0 +1,27 @@
+package org.apache.stratos.adc.mgt.dao;
+
+public class RepositoryCredentials {
+
+	private String url;
+	private String userName;
+	private String password;
+	public String getUrl() {
+    	return url;
+    }
+	public void setUrl(String url) {
+    	this.url = url;
+    }
+	public String getUserName() {
+    	return userName;
+    }
+	public void setUserName(String userName) {
+    	this.userName = userName;
+    }
+	public String getPassword() {
+    	return password;
+    }
+	public void setPassword(String password) {
+    	this.password = password;
+    }
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dns/DNSManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dns/DNSManager.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dns/DNSManager.java
new file mode 100644
index 0000000..ceb77fb
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dns/DNSManager.java
@@ -0,0 +1,86 @@
+ /*
+  * Copyright WSO2, Inc. (http://wso2.com)
+  *
+  * Licensed under the Apache License, Version 2.0 (the "License");
+  * you may not use this file except in compliance with the License.
+  * You may obtain a copy of the License at
+  *
+  * http://www.apache.org/licenses/LICENSE-2.0
+  *
+  * Unless required by applicable law or agreed to in writing, software
+  * distributed under the License is distributed on an "AS IS" BASIS,
+  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  * See the License for the specific language governing permissions and
+  * limitations under the License.
+  */
+
+package org.apache.stratos.adc.mgt.dns;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.utils.CartridgeConstants;
+
+/**
+ * This class is for handling dns entries.
+ */
+public class DNSManager {
+	private static final Log log = LogFactory.getLog(DNSManager.class);
+
+    /**
+   	 * This is get called when there is a need of adding new sub domain to
+   	 * exciting domain.
+   	 * It will append required text to bind9 zone file and reload bind9 server.
+   	 * Note: make sure the user who run ADC has got rights to run sudo scripts
+   	 * without password
+   	 *
+   	 * @param subDomain
+   	 *            will be added in front of domain
+   	 */
+   	public void addNewSubDomain(String subDomain, String ip) {
+   		try {
+   			Runtime.getRuntime()
+   			       .exec(CartridgeConstants.SUDO_SH + " " +
+             // script script file that will be used to edit
+             // required files
+             System.getProperty(CartridgeConstants.APPEND_SCRIPT) + " " +
+             subDomain + " " +
+             // machineIp ip of the machine DNS bind service
+             // is running
+             ip + " " +
+             // bindFile the file which we edit to append
+             // the DNS entry
+             System.getProperty(CartridgeConstants.BIND_FILE_PATH));
+   			log.info("New sub domain is added to zone file");
+   		} catch (Exception e) {
+   			log.error(e.getMessage());
+   			throw new RuntimeException(e);
+   		}
+   	}
+    /**
+   	 * This is get called when there is a need of remove a sub domain.
+   	 * It will remove required text from bind9 zone file and reload bind9 server.
+   	 * Note: make sure the user who run ADC has got rights to run sudo scripts
+   	 * without password
+   	 *
+   	 * @param subDomain
+   	 *            will be used to delete the entry related to this
+   	 */
+   	public void removeSubDomain(String subDomain) {
+   		try {
+   			Runtime.getRuntime()
+   			       .exec(CartridgeConstants.SUDO_SH + " " +
+             // script script file that will be used to edit
+             // required files
+             System.getProperty(CartridgeConstants.REMOVE_SCRIPT) + " " +
+             subDomain + " " +
+             // bindFile the file which we edit to remove
+             // the DNS entry
+             System.getProperty(CartridgeConstants.BIND_FILE_PATH));
+   			log.info("Sub domain is removed from zone file");
+   		} catch (Exception e) {
+   			log.error(e.getMessage());
+   			throw new RuntimeException(e);
+   		}
+   	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/AppRepo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/AppRepo.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/AppRepo.java
new file mode 100644
index 0000000..facfbe3
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/AppRepo.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.dto;
+
+public class AppRepo {
+
+	private int tenantId;
+	private String repoName;
+	private String cartridge;
+	private String appName;
+	private boolean isWebRoot;
+	private String tenantPubKey;
+	private String tenantCartridgePubKey;
+
+	public int getTenantId() {
+		return tenantId;
+	}
+
+	public void setTenantId(int tenantId) {
+		this.tenantId = tenantId;
+	}
+
+	public String getRepoName() {
+		return repoName;
+	}
+
+	public void setRepoName(String repoName) {
+		this.repoName = repoName;
+	}
+
+	public String getCartridge() {
+		return cartridge;
+	}
+
+	public void setCartridge(String cartridge) {
+		this.cartridge = cartridge;
+	}
+
+	public String getAppName() {
+		return appName;
+	}
+
+	public void setAppName(String appName) {
+		this.appName = appName;
+	}
+
+	public boolean isWebRoot() {
+		return isWebRoot;
+	}
+
+	public void setWebRoot(boolean isWebRoot) {
+		this.isWebRoot = isWebRoot;
+	}
+
+	public String getTenantPubKey() {
+		return tenantPubKey;
+	}
+
+	public void setTenantPubKey(String tenantPubKey) {
+		this.tenantPubKey = tenantPubKey;
+	}
+
+	public String getTenantCartridgePubKey() {
+		return tenantCartridgePubKey;
+	}
+
+	public void setTenantCartridgePubKey(String tenantCartridgePubKey) {
+		this.tenantCartridgePubKey = tenantCartridgePubKey;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/Cartridge.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/Cartridge.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/Cartridge.java
new file mode 100644
index 0000000..4d990ce
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/Cartridge.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.dto;
+
+public class Cartridge implements Comparable<Cartridge> {
+
+    private String displayName;
+    private String description;
+	private String cartridgeAlias;
+	private String cartridgeType;
+	private int activeInstances;
+	private String status;
+	private String ip;
+	private String password;
+	private String provider;
+	private String version;
+	private boolean multiTenant;
+	private String hostName;
+	private String policy;
+	private String policyDescription;
+	private String repoURL;
+	private String dbUserName;
+	private String mappedDomain;
+
+	private String[] accessURLs;
+
+	public String getDisplayName() {
+		return displayName;
+	}
+
+	public void setDisplayName(String displayName) {
+		this.displayName = displayName;
+	}
+
+	public String getDescription() {
+		return description;
+	}
+
+	public void setDescription(String description) {
+		this.description = description;
+	}
+
+	public String getCartridgeAlias() {
+		return cartridgeAlias;
+	}
+
+	public void setCartridgeAlias(String cartridgeAlias) {
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+
+	public void setCartridgeType(String cartridgeType) {
+		this.cartridgeType = cartridgeType;
+	}
+
+	public int getActiveInstances() {
+		return activeInstances;
+	}
+
+	public void setActiveInstances(int activeInstances) {
+		this.activeInstances = activeInstances;
+	}
+
+	public String getStatus() {
+		return status;
+	}
+
+	public void setStatus(String status) {
+		this.status = status;
+	}
+
+	public String getIp() {
+		return ip;
+	}
+
+	public void setIp(String ip) {
+		this.ip = ip;
+	}
+
+	public String getPassword() {
+		return password;
+	}
+
+	public void setPassword(String password) {
+		this.password = password;
+	}
+
+	public String getProvider() {
+    	return provider;
+    }
+
+	public void setProvider(String provider) {
+    	this.provider = provider;
+    }
+
+	public String getVersion() {
+    	return version;
+    }
+
+	public void setVersion(String version) {
+    	this.version = version;
+    }
+
+	public boolean isMultiTenant() {
+		return multiTenant;
+	}
+
+	public void setMultiTenant(boolean multiTenant) {
+		this.multiTenant = multiTenant;
+	}
+
+	public String getHostName() {
+    	return hostName;
+    }
+
+	public void setHostName(String hostName) {
+    	this.hostName = hostName;
+    }
+
+	public String getPolicy() {
+		return policy;
+	}
+
+	public void setPolicy(String policy) {
+		this.policy = policy;
+	}
+
+	public String getPolicyDescription() {
+		return policyDescription;
+	}
+
+	public void setPolicyDescription(String policyDescription) {
+		this.policyDescription = policyDescription;
+	}
+
+	public String getRepoURL() {
+    	return repoURL;
+    }
+
+	public void setRepoURL(String repoURL) {
+    	this.repoURL = repoURL;
+    }
+
+	public String getDbUserName() {
+    	return dbUserName;
+    }
+
+	public String[] getAccessURLs() {
+		return accessURLs;
+	}
+
+	public void setAccessURLs(String[] accessURLs) {
+		this.accessURLs = accessURLs;
+	}
+
+	public void setDbUserName(String dbUserName) {
+    	this.dbUserName = dbUserName;
+    }
+
+	public String getMappedDomain() {
+		return mappedDomain;
+	}
+
+	public void setMappedDomain(String mappedDomain) {
+		this.mappedDomain = mappedDomain;
+	}
+
+	@Override
+	public int compareTo(Cartridge o) {
+		int compare = 0;
+		if (cartridgeAlias != null && o.cartridgeAlias != null) {
+			compare = cartridgeAlias.compareTo(o.cartridgeAlias);
+		}
+		if (compare == 0 && cartridgeType != null && o.cartridgeType != null) {
+			compare = cartridgeType.compareTo(o.cartridgeType);
+		}
+		return compare;
+	}
+	
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeDetail.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeDetail.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeDetail.java
new file mode 100644
index 0000000..48a0086
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeDetail.java
@@ -0,0 +1 @@
+package org.apache.stratos.adc.mgt.dto;

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeInformation.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeInformation.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeInformation.java
new file mode 100644
index 0000000..48a0086
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeInformation.java
@@ -0,0 +1 @@
+package org.apache.stratos.adc.mgt.dto;

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeWrapper.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeWrapper.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeWrapper.java
new file mode 100644
index 0000000..1339a16
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeWrapper.java
@@ -0,0 +1,49 @@
+/*                                                                             
+ * Copyright 2004,2005 The Apache Software Foundation.                         
+ *                                                                             
+ * Licensed under the Apache License, Version 2.0 (the "License");             
+ * you may not use this file except in compliance with the License.            
+ * You may obtain a copy of the License at                                     
+ *                                                                             
+ *      http://www.apache.org/licenses/LICENSE-2.0                             
+ *                                                                             
+ * Unless required by applicable law or agreed to in writing, software         
+ * distributed under the License is distributed on an "AS IS" BASIS,           
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.    
+ * See the License for the specific language governing permissions and         
+ * limitations under the License.                                              
+ */
+package org.apache.stratos.adc.mgt.dto;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.wso2.carbon.utils.Pageable;
+
+/**
+ * This class holds paginated information about cartridges
+ */
+public final class CartridgeWrapper implements Pageable {
+
+	private Cartridge[] cartridges;
+	private int numberOfPages;
+
+	public CartridgeWrapper() {
+	}
+
+	public int getNumberOfPages() {
+		return numberOfPages;
+	}
+
+	public void setNumberOfPages(int numberOfPages) {
+		this.numberOfPages = numberOfPages;
+	}
+
+	public <T> void set(List<T> items) {
+		this.cartridges = items.toArray(new Cartridge[items.size()]);
+	}
+
+	public Cartridge[] getCartridges() {
+		return cartridges != null ? Arrays.copyOf(cartridges, cartridges.length) : null;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/Policy.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/Policy.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/Policy.java
new file mode 100644
index 0000000..451618d
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/Policy.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.dto;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+
+public class Policy implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+
+	private String name;
+	private String description;
+	private boolean defaultPolicy;
+
+	private Integer minAppInstances;
+	private Integer maxAppInstances;
+	private Integer maxRequestsPerSecond;
+	private BigDecimal alarmingUpperRate;
+	private BigDecimal alarmingLowerRate;
+	private BigDecimal scaleDownFactor;
+	private Integer roundsToAverage;
+
+	public Policy() {
+	}
+
+	public String getName() {
+		return name;
+	}
+
+	public void setName(String name) {
+		this.name = name;
+	}
+
+	public String getDescription() {
+		return description;
+	}
+
+	public void setDescription(String description) {
+		this.description = description;
+	}
+
+	public boolean isDefaultPolicy() {
+		return defaultPolicy;
+	}
+
+	public void setDefaultPolicy(boolean defaultPolicy) {
+		this.defaultPolicy = defaultPolicy;
+	}
+
+	public Integer getMinAppInstances() {
+		return minAppInstances;
+	}
+
+	public void setMinAppInstances(Integer minAppInstances) {
+		this.minAppInstances = minAppInstances;
+	}
+
+	public Integer getMaxAppInstances() {
+		return maxAppInstances;
+	}
+
+	public void setMaxAppInstances(Integer maxAppInstances) {
+		this.maxAppInstances = maxAppInstances;
+	}
+
+	public Integer getMaxRequestsPerSecond() {
+		return maxRequestsPerSecond;
+	}
+
+	public void setMaxRequestsPerSecond(Integer maxRequestsPerSecond) {
+		this.maxRequestsPerSecond = maxRequestsPerSecond;
+	}
+
+	public BigDecimal getAlarmingUpperRate() {
+		return alarmingUpperRate;
+	}
+
+	public void setAlarmingUpperRate(BigDecimal alarmingUpperRate) {
+		this.alarmingUpperRate = alarmingUpperRate;
+	}
+
+	public BigDecimal getAlarmingLowerRate() {
+		return alarmingLowerRate;
+	}
+
+	public void setAlarmingLowerRate(BigDecimal alarmingLowerRate) {
+		this.alarmingLowerRate = alarmingLowerRate;
+	}
+
+	public BigDecimal getScaleDownFactor() {
+		return scaleDownFactor;
+	}
+
+	public void setScaleDownFactor(BigDecimal scaleDownFactor) {
+		this.scaleDownFactor = scaleDownFactor;
+	}
+
+	public Integer getRoundsToAverage() {
+		return roundsToAverage;
+	}
+
+	public void setRoundsToAverage(Integer roundsToAverage) {
+		this.roundsToAverage = roundsToAverage;
+	}
+
+	@Override
+	public int hashCode() {
+		final int prime = 31;
+		int result = 1;
+		result = prime * result + ((name == null) ? 0 : name.hashCode());
+		return result;
+	}
+
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj)
+			return true;
+		if (obj == null)
+			return false;
+		if (!(obj instanceof Policy))
+			return false;
+		Policy other = (Policy) obj;
+		if (name == null) {
+			if (other.name != null)
+				return false;
+		} else if (!name.equals(other.name))
+			return false;
+		return true;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/PolicyDefinition.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/PolicyDefinition.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/PolicyDefinition.java
new file mode 100644
index 0000000..b21df4f
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/PolicyDefinition.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.dto;
+
+import java.io.Serializable;
+
+public class PolicyDefinition implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+
+	private String name;
+	private String description;
+	private boolean defaultPolicy;
+
+	public PolicyDefinition() {
+	}
+
+	public String getName() {
+		return name;
+	}
+
+	public void setName(String name) {
+		this.name = name;
+	}
+
+	public String getDescription() {
+		return description;
+	}
+
+	public void setDescription(String description) {
+		this.description = description;
+	}
+
+	public boolean isDefaultPolicy() {
+		return defaultPolicy;
+	}
+
+	public void setDefaultPolicy(boolean defaultPolicy) {
+		this.defaultPolicy = defaultPolicy;
+	}
+
+	@Override
+	public int hashCode() {
+		final int prime = 31;
+		int result = 1;
+		result = prime * result + ((name == null) ? 0 : name.hashCode());
+		return result;
+	}
+
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj)
+			return true;
+		if (obj == null)
+			return false;
+		if (!(obj instanceof PolicyDefinition))
+			return false;
+		PolicyDefinition other = (PolicyDefinition) obj;
+		if (name == null) {
+			if (other.name != null)
+				return false;
+		} else if (!name.equals(other.name))
+			return false;
+		return true;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/RepositoryInformation.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/RepositoryInformation.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/RepositoryInformation.java
new file mode 100644
index 0000000..3a88700
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/RepositoryInformation.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.dto;
+
+import java.io.Serializable;
+
+public class RepositoryInformation implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+
+	private String repoURL;
+	private String[] refName;
+
+	public String getRepoURL() {
+		return repoURL;
+	}
+
+	public void setRepoURL(String repoURL) {
+		this.repoURL = repoURL;
+	}
+
+	public String[] getRefName() {
+		return refName;
+	}
+
+	public void setRefName(String[] refName) {
+		this.refName = refName;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/SubscriptionInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/SubscriptionInfo.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/SubscriptionInfo.java
new file mode 100644
index 0000000..39e3ae2
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/dto/SubscriptionInfo.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.dto;
+
+import java.io.Serializable;
+
+public class SubscriptionInfo implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+
+	private String hostname;
+	private String repositoryURL;
+
+	public String getHostname() {
+		return hostname;
+	}
+
+	public void setHostname(String hostname) {
+		this.hostname = hostname;
+	}
+
+	public String getRepositoryURL() {
+		return repositoryURL;
+	}
+
+	public void setRepositoryURL(String repositoryURL) {
+		this.repositoryURL = repositoryURL;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/ADCException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/ADCException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/ADCException.java
new file mode 100644
index 0000000..d9dbfdf
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/ADCException.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class ADCException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private String message;
+
+	public ADCException() {
+		super();
+	}
+
+	public ADCException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public ADCException(String message) {
+		super(message);
+		this.message = message;
+	}
+
+	public ADCException(Throwable cause) {
+		super(cause);
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/AlreadySubscribedException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/AlreadySubscribedException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/AlreadySubscribedException.java
new file mode 100644
index 0000000..954a71b
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/AlreadySubscribedException.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class AlreadySubscribedException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String cartridgeType;
+
+	public AlreadySubscribedException(String message, String cartridgeType, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+	}
+
+	public AlreadySubscribedException(String message, String cartridgeType) {
+		super(message);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/DomainMappingExistsException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/DomainMappingExistsException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/DomainMappingExistsException.java
new file mode 100644
index 0000000..9287a86
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/DomainMappingExistsException.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class DomainMappingExistsException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String domain;
+
+	public DomainMappingExistsException(String message, String domain, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.domain = domain;
+	}
+
+	public DomainMappingExistsException(String message, String domain) {
+		super(message);
+		this.message = message;
+		this.domain = domain;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getDomain() {
+		return domain;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/DuplicateCartridgeAliasException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/DuplicateCartridgeAliasException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/DuplicateCartridgeAliasException.java
new file mode 100644
index 0000000..94aa14c
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/DuplicateCartridgeAliasException.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class DuplicateCartridgeAliasException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String cartridgeType;
+
+	private final String cartridgeAlias;
+
+	public DuplicateCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public DuplicateCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias) {
+		super(message);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+
+	public String getCartridgeAlias() {
+		return cartridgeAlias;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidCartridgeAliasException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidCartridgeAliasException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidCartridgeAliasException.java
new file mode 100644
index 0000000..0fed41b
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidCartridgeAliasException.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class InvalidCartridgeAliasException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String cartridgeType;
+
+	private final String cartridgeAlias;
+
+	public InvalidCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public InvalidCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias) {
+		super(message);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+
+	public String getCartridgeAlias() {
+		return cartridgeAlias;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidRepositoryException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidRepositoryException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidRepositoryException.java
new file mode 100644
index 0000000..c545b9e
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidRepositoryException.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class InvalidRepositoryException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private String message;
+
+	public InvalidRepositoryException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/NotSubscribedException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/NotSubscribedException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/NotSubscribedException.java
new file mode 100644
index 0000000..74aef20
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/NotSubscribedException.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class NotSubscribedException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String cartridgeAlias;
+
+	public NotSubscribedException(String message, String cartridgeAlias, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public NotSubscribedException(String message, String cartridgeAlias) {
+		super(message);
+		this.message = message;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getCartridgeAlias() {
+		return cartridgeAlias;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/PolicyException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/PolicyException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/PolicyException.java
new file mode 100644
index 0000000..2ad3117
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/PolicyException.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class PolicyException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	public PolicyException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public PolicyException(String message) {
+		super(message);
+		this.message = message;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryCredentialsRequiredException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryCredentialsRequiredException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryCredentialsRequiredException.java
new file mode 100644
index 0000000..2de1899
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryCredentialsRequiredException.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class RepositoryCredentialsRequiredException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private String message;
+
+	public RepositoryCredentialsRequiredException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public RepositoryCredentialsRequiredException(String message) {
+		super(message);
+		this.message = message;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryRequiredException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryRequiredException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryRequiredException.java
new file mode 100644
index 0000000..553dfc2
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryRequiredException.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class RepositoryRequiredException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private String message;
+
+	public RepositoryRequiredException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public RepositoryRequiredException(String message) {
+		super(message);
+		this.message = message;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryTransportException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryTransportException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryTransportException.java
new file mode 100644
index 0000000..5b5036a
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryTransportException.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class RepositoryTransportException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	public RepositoryTransportException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public RepositoryTransportException(String message) {
+		super(message);
+		this.message = message;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/UnregisteredCartridgeException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/UnregisteredCartridgeException.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/UnregisteredCartridgeException.java
new file mode 100644
index 0000000..fb1f656
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/exception/UnregisteredCartridgeException.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.exception;
+
+public class UnregisteredCartridgeException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String cartridgeType;
+
+	public UnregisteredCartridgeException(String message, String cartridgeType, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+	}
+
+	public UnregisteredCartridgeException(String message, String cartridgeType) {
+		super(message);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java
new file mode 100644
index 0000000..48cfc2a
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java
@@ -0,0 +1,106 @@
+/*
+        * Copyright WSO2, Inc. (http://wso2.com)
+        *
+        * Licensed under the Apache License, Version 2.0 (the "License");
+        * you may not use this file except in compliance with the License.
+        * You may obtain a copy of the License at
+        *
+        * http://www.apache.org/licenses/LICENSE-2.0
+        *
+        * Unless required by applicable law or agreed to in writing, software
+        * distributed under the License is distributed on an "AS IS" BASIS,
+        * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+        * See the License for the specific language governing permissions and
+        * limitations under the License.
+        */
+package org.apache.stratos.adc.mgt.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.utils.CartridgeConfigFileReader;
+import org.apache.stratos.adc.mgt.utils.StratosDBUtils;
+import org.osgi.service.component.ComponentContext;
+import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * @scr.component name=
+ *                "org.wso2.carbon.hosting.mgt.internal.ADCManagementServerComponent"
+ *                immediate="true"
+ * @scr.reference name="config.context.service"
+ *                interface="org.wso2.carbon.utils.ConfigurationContextService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setConfigurationContextService"
+ *                unbind="unsetConfigurationContextService"
+ * @scr.reference name="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1" policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ * @scr.reference name="registry.service"
+ *                interface=
+ *                "org.wso2.carbon.registry.core.service.RegistryService"
+ *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
+ *                unbind="unsetRegistryService"
+ * @scr.reference name="topology.mgt.service"
+ *                interface=
+ *                "org.apache.stratos.adc.topology.mgt.service.TopologyManagementService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setTopologyManagementService"
+ *                unbind="unsetTopologyManagementService"
+ */
+
+public class ADCManagementServerComponent {
+    private static final Log log = LogFactory.getLog(ADCManagementServerComponent.class);
+
+	protected void activate(ComponentContext componentContext) throws Exception {
+		if (log.isInfoEnabled()) {
+			log.info("ADC Management Server Component activated");
+		}
+
+		try {
+			CartridgeConfigFileReader.readProperties();
+			StratosDBUtils.initialize();
+		} catch (Exception e) {
+			log.fatal("Error while initializing the ADC Management Server Component", e);
+		}
+	}
+
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        DataHolder.setClientConfigContext(contextService.getClientConfigContext());
+        DataHolder.setServerConfigContext(contextService.getServerConfigContext());
+
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+        DataHolder.setClientConfigContext(null);
+        DataHolder.setServerConfigContext(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        // keeping the realm service in the DataHolder class
+        DataHolder.setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        try {
+            DataHolder.setRegistry(registryService.getGovernanceSystemRegistry());
+        } catch (Exception e) {
+            log.error("Cannot  retrieve governance Registry", e);
+        }
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+    }
+
+    protected void setTopologyManagementService(TopologyManagementService topologyMgtService) {
+        DataHolder.setTopologyMgtService(topologyMgtService);
+    }
+
+    protected void unsetTopologyManagementService(TopologyManagementService topologyMgtService) {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java
new file mode 100644
index 0000000..392489b
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.internal;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.wso2.carbon.registry.core.Registry;
+import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * Holds the some of the data required by the webapps component
+ */
+public class DataHolder {
+	private static ConfigurationContext clientConfigContext;
+	private static ConfigurationContext serverConfigContext;
+
+	private static RealmService realmService;
+	private static Registry registry;
+	private static TopologyManagementService topologyMgtService;
+
+	public static RealmService getRealmService() {
+		return realmService;
+	}
+
+	public static void setRealmService(RealmService realmService) {
+		DataHolder.realmService = realmService;
+	}
+
+	public static Registry getRegistry() {
+		return registry;
+	}
+
+	public static ConfigurationContext getClientConfigContext() {
+		CarbonUtils.checkSecurity();
+		return clientConfigContext;
+	}
+
+	public static void setClientConfigContext(ConfigurationContext clientConfigContext) {
+		DataHolder.clientConfigContext = clientConfigContext;
+	}
+
+	public static ConfigurationContext getServerConfigContext() {
+		CarbonUtils.checkSecurity();
+		return serverConfigContext;
+	}
+
+	public static void setServerConfigContext(ConfigurationContext serverConfigContext) {
+		DataHolder.serverConfigContext = serverConfigContext;
+	}
+
+	public static void setRegistry(Registry registry) {
+		DataHolder.registry = registry;
+	}
+
+	public static TopologyManagementService getTopologyMgtService() {
+		return topologyMgtService;
+	}
+
+	public static void setTopologyMgtService(TopologyManagementService topologyMgtService) {
+		DataHolder.topologyMgtService = topologyMgtService;
+	}
+}


[16/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/StratosConfiguration.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/StratosConfiguration.java b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/StratosConfiguration.java
new file mode 100644
index 0000000..2226593
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/java/org/apache/stratos/common/util/StratosConfiguration.java
@@ -0,0 +1,319 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.util;
+
+import java.lang.String;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Class for the stratos specific parameters configuration
+ */
+public class StratosConfiguration {
+
+    // By default email sending is disabled. Changed according to the configuration file.
+    private boolean emailsDisabled = true;
+
+    private boolean emailValidationRequired = false;
+    private boolean isPublicCloudSetup = true;
+    private boolean isTenantActivationModerated = false;
+    private boolean chargeOnRegistration = false;
+    private String SuperAdminEmail = "";
+    private String paypalUrl = "";
+    private String paypalAPIUsername = "";
+    private String paypalAPIPassword = "";
+    private String paypalAPISignature = "";
+    private String paypalEnvironment="";
+    private String usagePlanURL = "";
+    private String paidJIRAUrl = "";
+    private String paidJIRAProject = "";
+    private String forumUrl = "";
+    private String paidUserGroup = "";
+    private String nonpaidUserGroup = "";
+    private String supportInfoUrl = "";
+    private String incidentCustomFieldId = ""; // todo this is a custom field id of JIRA, this need to be dynamically get in jira reporting component
+    private String incidentImpactCustomFieldId = "";
+    private String stratosEventListenerName ="";
+    private Map<String, String> stratosEventProperties = new HashMap<String, String>();
+    private String googleAnalyticsURL;
+    private String managerServiceUrl = "";
+    private String adminUserName = "";
+    private String adminPassword = "";
+    private String ssoLoadingMessage="";
+
+    /**
+     * @return Stratos Manager service url
+     */
+    public String getManagerServiceUrl() {
+        return managerServiceUrl;
+    }
+
+    public void setManagerServiceUrl(String managerServiceUrl) {
+        this.managerServiceUrl = managerServiceUrl;
+    }
+
+    /**
+     * @return Super admin User name
+     */
+    public String getAdminUserName() {
+        return adminUserName;
+    }
+
+    public void setAdminUserName(String adminUserName) {
+        this.adminUserName = adminUserName;
+    }
+
+    /**
+     * @return super admin password
+     */
+    public String getAdminPassword() {
+        return adminPassword;
+    }
+
+    public void setAdminPassword(String adminPassword) {
+        this.adminPassword = adminPassword;
+    }
+
+    //This parameter used to skip usage summary generator
+     private boolean skipSummaryGenerator = false;
+
+    public boolean isSkipSummaryGenerator() {
+        return skipSummaryGenerator;
+    }
+
+    public void setSkipSummaryGenerator(boolean skipSummaryGenerator) {
+        this.skipSummaryGenerator = skipSummaryGenerator;
+    }
+    //This is the url that we pointed users when they need to aware about usage plans
+
+    public String getUsagePlanURL() {
+        return usagePlanURL;
+    }
+
+    public void setUsagePlanURL(String usagePlanURL) {
+        this.usagePlanURL = usagePlanURL;
+    }
+
+    //Email address for general notifications
+    private String notificationEmail = "";
+    //Email address for finance related notifications
+    private String financeNotificationEmail = "";
+
+    public boolean isTenantActivationModerated() {
+        return isTenantActivationModerated;
+    }
+
+    public void setTenantActivationModerated(boolean tenantActivationModerated) {
+        isTenantActivationModerated = tenantActivationModerated;
+    }
+
+    public String getSuperAdminEmail() {
+        return SuperAdminEmail;
+    }
+
+    public void setSuperAdminEmail(String superAdminEmail) {
+        SuperAdminEmail = superAdminEmail;
+    }
+
+    public boolean getEmailValidationRequired() {
+        return emailValidationRequired;
+    }
+
+    public String getPaypalUrl() {
+        return paypalUrl;
+    }
+
+    public void setPaypalUrl(String paypalUrl) {
+        this.paypalUrl = paypalUrl;
+    }
+
+    public void setEmailValidationRequired(boolean emailValidationRequired) {
+        this.emailValidationRequired = emailValidationRequired;
+    }
+
+    public boolean isPublicCloudSetup() {
+        return isPublicCloudSetup;
+    }
+
+    public void setPublicCloudSetup(boolean publicCloudSetup) {
+        isPublicCloudSetup = publicCloudSetup;
+    }
+
+    public String getNotificationEmail() {
+        return notificationEmail;
+    }
+
+    public void setNotificationEmail(String notificationEmail) {
+        this.notificationEmail = notificationEmail;
+    }
+
+    public String getPaypalAPIUsername() {
+        return paypalAPIUsername;
+    }
+
+    public void setPaypalAPIUsername(String paypalAPIUsername) {
+        this.paypalAPIUsername = paypalAPIUsername;
+    }
+
+    public String getPaypalAPIPassword() {
+        return paypalAPIPassword;
+    }
+
+    public void setPaypalAPIPassword(String paypalAPIPassword) {
+        this.paypalAPIPassword = paypalAPIPassword;
+    }
+
+    public String getPaypalAPISignature() {
+        return paypalAPISignature;
+    }
+
+    public void setPaypalAPISignature(String paypalAPISignature) {
+        this.paypalAPISignature = paypalAPISignature;
+    }
+
+    public String getFinanceNotificationEmail() {
+        return financeNotificationEmail;
+    }
+
+    public void setFinanceNotificationEmail(String financeNotificationEmail) {
+        this.financeNotificationEmail = financeNotificationEmail;
+    }
+
+    public String getPaidJIRAUrl() {
+        return paidJIRAUrl;
+    }
+
+    public void setPaidJIRAUrl(String paidJIRAUrl) {
+        this.paidJIRAUrl = paidJIRAUrl;
+    }
+
+    public String getPaidJIRAProject() {
+        return paidJIRAProject;
+    }
+
+    public void setPaidJIRAProject(String paidJIRAProject) {
+        this.paidJIRAProject = paidJIRAProject;
+    }
+
+    public String getForumUrl() {
+        return forumUrl;
+    }
+
+    public void setForumUrl(String forumUrl) {
+        this.forumUrl = forumUrl;
+    }
+
+    public String getPaidUserGroup() {
+        return paidUserGroup;
+    }
+
+    public void setPaidUserGroup(String paidUserGroup) {
+        this.paidUserGroup = paidUserGroup;
+    }
+
+    public String getNonpaidUserGroup() {
+        return nonpaidUserGroup;
+    }
+
+    public void setNonpaidUserGroup(String nonpaidUserGroup) {
+        this.nonpaidUserGroup = nonpaidUserGroup;
+    }
+
+    public String getSupportInfoUrl() {
+        return supportInfoUrl;
+    }
+
+    public void setSupportInfoUrl(String supportInfoUrl) {
+        this.supportInfoUrl = supportInfoUrl;
+    }
+
+    public String getIncidentCustomFieldId() {
+        return incidentCustomFieldId;
+    }
+
+    public void setIncidentCustomFieldId(String incidentCustomFieldId) {
+        this.incidentCustomFieldId = incidentCustomFieldId;
+    }
+
+    public String getIncidentImpactCustomFieldId() {
+        return incidentImpactCustomFieldId;
+    }
+
+    public void setIncidentImpactCustomFieldId(String incidentImpactCustomFieldId) {
+        this.incidentImpactCustomFieldId = incidentImpactCustomFieldId;
+    }
+    
+    public String getStratosEventListenerName() {
+        return stratosEventListenerName;
+    }
+
+    public void setStratosEventListenerName(String stratosEventListenerName) {
+        this.stratosEventListenerName = stratosEventListenerName;
+    }
+
+    public String getStratosEventListenerPropertyValue(String key) {
+        return stratosEventProperties.get(key);
+    }
+
+    public void setStratosEventListenerProperty(String key, String value) {
+        stratosEventProperties.put(key, value);
+    }
+
+    public String getPaypalEnvironment() {
+        return paypalEnvironment;
+    }
+
+    public void setPaypalEnvironment(String paypalEnvironment) {
+        this.paypalEnvironment = paypalEnvironment;
+    }
+
+    public String getGoogleAnalyticsURL() {
+        return googleAnalyticsURL;
+    }
+
+    public void setGoogleAnalyticsURL(String googleAnalyticsURL) {
+        this.googleAnalyticsURL = googleAnalyticsURL;
+    }
+
+    public boolean isEmailsDisabled() {
+        return emailsDisabled;
+    }
+
+    public void setEmailsDisabled(boolean emailsDisabled) {
+        this.emailsDisabled = emailsDisabled;
+    }
+
+    public boolean isChargeOnRegistration() {
+        return chargeOnRegistration;
+    }
+
+    public void setChargeOnRegistration(boolean chargeOnRegistration) {
+        this.chargeOnRegistration = chargeOnRegistration;
+    }
+
+    public String getSsoLoadingMessage() {
+        return ssoLoadingMessage;
+    }
+
+    public void setSsoLoadingMessage(String ssoLoadingMessage) {
+        this.ssoLoadingMessage = ssoLoadingMessage;
+    }
+    
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.common/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..7f0bcf3
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/resources/META-INF/services.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one
+  ~ or more contributor license agreements. See the NOTICE file
+  ~ distributed with this work for additional information
+  ~ regarding copyright ownership. The ASF licenses this file
+  ~ to you under the Apache License, Version 2.0 (the
+  ~ "License"); you may not use this file except in compliance
+  ~ with the License. You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing,
+  ~ software distributed under the License is distributed on an
+  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~ KIND, either express or implied. See the License for the
+  ~ specific language governing permissions and limitations
+  ~ under the License.
+  -->
+<serviceGroup>
+
+    <service name="PackageInfoService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.apache.stratos.common.services.PackageInfoService
+        </parameter>
+        <parameter name="adminService" locked="ture">false</parameter>
+    </service>
+
+    <parameter name="hiddenService" locked="ture">true</parameter>
+    
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/main/resources/cloud-services-desc.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/main/resources/cloud-services-desc.xml b/components/org.apache.stratos.common/src/main/resources/cloud-services-desc.xml
new file mode 100644
index 0000000..15fb4b9
--- /dev/null
+++ b/components/org.apache.stratos.common/src/main/resources/cloud-services-desc.xml
@@ -0,0 +1,109 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<cloudServices xmlns="http://wso2.com/carbon/cloud/mgt/services">
+    <cloudService name="WSO2 Stratos Manager">
+    </cloudService>
+    <cloudService name="WSO2 Enterprise Service Bus" default="true">
+      <label>Enterprise Service Bus</label>
+      <link>https://esb.stratoslive.wso2.com</link>
+      <icon>
+        https://localhost:9443/cloud-services-icons/esb.gif
+      </icon>
+      <description>Enterprise Service Bus in the cloud.</description>
+    </cloudService>
+    <cloudService name="WSO2 Application Server" default="true">
+        <label>Application Server</label>
+        <link>https://appserver.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/appserver.gif
+        </icon>
+        <description>Application Server in the cloud.</description>
+    </cloudService>
+    <cloudService name="WSO2 Data Services Server" default="true">
+      <label>Data Services Server</label>
+      <link>https://dss.stratoslive.wso2.com</link>
+      <icon>
+        https://localhost:9443/cloud-services-icons/ds.gif
+      </icon>
+      <description>Data Services Server in the cloud.</description>
+    </cloudService>
+    <cloudService name="WSO2 Governance" default="true">
+        <label>Governance</label>
+        <link>https://governance.stratoslive.wso2.com</link>
+        <description>Governance in the cloud.</description>
+        <icon>
+            https://localhost:9443/cloud-services-icons/governance.gif
+        </icon>
+    </cloudService>
+    <cloudService name="WSO2 Identity" default="true">
+        <label>Identity</label>
+        <link>https://identity.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/identity.gif
+        </icon>
+        <description>Identity in the cloud.</description>
+    </cloudService>
+	<cloudService name="WSO2 Business Activity Monitor" default="true">
+        <label>Business Activity Monitor</label>
+        <link>https://bam.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/bam.gif
+        </icon>
+        <description>Business Activity Monitor in the cloud.</description>
+	</cloudService>
+    <cloudService name="WSO2 Business Process Server" default="true">
+      <label>Business Process Server</label>
+      <link>https://bps.stratoslive.wso2.com</link>
+      <icon>
+        https://localhost:9443/cloud-services-icons/bps.gif
+      </icon>
+      <description>Business Process Server in the cloud.</description>
+    </cloudService>
+	<cloudService name="WSO2 Business Rule Server" default="true">
+        <label>Business Rule Server</label>
+        <link>https://brs.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/brs.gif
+        </icon>
+        <description>Business Rule Server in the cloud.</description>
+	</cloudService>
+	<cloudService name="WSO2 Mashup Server" default="true">
+        <label>Mashup Server</label>
+        <link>https://mashup.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/mashup.gif
+        </icon>
+        <description>Mashup Server in the cloud.</description>
+    </cloudService>
+    <cloudService name="WSO2 Gadgets" default="true">
+        <label>Gadgets</label>
+        <link>https://gadget.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/gadget.gif
+        </icon>
+        <description>Gadgets in the cloud.</description>
+    </cloudService>
+    <cloudService name="WSO2 Cloud Services Gateway" default="true">
+        <label>Cloud Gateway</label>
+	<link>https://csg.stratoslive.wso2.com</link>
+	<icon>
+            https://localhost:9443/cloud-services-icons/csg.gif
+	</icon>
+	<description>WSO2 Cloud Services Gateway in the cloud.</description>
+    </cloudService>
+</cloudServices>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/src/test/java/org/apache/stratos/common/test/CommonTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/src/test/java/org/apache/stratos/common/test/CommonTest.java b/components/org.apache.stratos.common/src/test/java/org/apache/stratos/common/test/CommonTest.java
new file mode 100644
index 0000000..dc61fc4
--- /dev/null
+++ b/components/org.apache.stratos.common/src/test/java/org/apache/stratos/common/test/CommonTest.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.common.test;
+
+import junit.framework.TestCase;
+import org.apache.stratos.common.util.CommonUtil;
+
+public class CommonTest extends TestCase {
+    public void testEmailValidation() throws Exception {
+        try {
+            CommonUtil.validateEmail("damn@right.com");
+            assertTrue(true);
+        } catch (Exception e) {
+            assertTrue(false);
+        }
+
+        try {
+            CommonUtil.validateEmail("damn@right].com");
+            assertTrue(false);
+        } catch (Exception e) {
+            assertTrue(true);
+            assertEquals("Wrong characters in the email.", e.getMessage());
+        }
+
+        try {
+            CommonUtil.validateEmail("damn@right@wrong.com");
+            assertTrue(false);
+        } catch (Exception e) {
+            assertTrue(true);
+            assertEquals("Invalid email address is provided.", e.getMessage());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.deployment/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.deployment/2.1.0/pom.xml b/components/org.apache.stratos.deployment/2.1.0/pom.xml
deleted file mode 100644
index 25caef9..0000000
--- a/components/org.apache.stratos.deployment/2.1.0/pom.xml
+++ /dev/null
@@ -1,106 +0,0 @@
-<!--
-       Licensed to the Apache Software Foundation (ASF) under one
-       or more contributor license agreements.  See the NOTICE file
-       distributed with this work for additional information
-       regarding copyright ownership.  The ASF licenses this file
-       to you under the Apache License, Version 2.0 (the
-       "License"); you may not use this file except in compliance
-       with the License.  You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing,
-       software distributed under the License is distributed on an
-       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-       KIND, either express or implied.  See the License for the
-       specific language governing permissions and limitations
-       under the License.
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-       <groupId>org.apache.stratos</groupId>
-       <artifactId>stratos-components-parent</artifactId>
-       <version>3.0.0-SNAPSHOT</version>
-       <relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.deployment</artifactId>
-    <version>2.1.0</version>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Deployment</name>
-
-    <build>
-
-        <plugins>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-compiler-plugin</artifactId>
-                <version>2.0</version>
-                <configuration>
-                    <source>1.5</source>
-                    <target>1.5</target>
-                </configuration>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Private-Package>
-                            org.apache.stratos.deployment.internal.*
-                        </Private-Package>
-                        <Export-Package>
-                            !org.apache.stratos.deployment.internal.*,
-                            org.apache.stratos.deployment.*
-                        </Export-Package>
-                        <Import-Package>
-                            !javax.xml.namespace,
-                            org.apache.axis2.*; version="${axis2.osgi.version.range}",
-                            javax.xml.namespace; version=0.0.0,
-                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
-                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
-                            *;resolution:=optional
-                        </Import-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.stratos.common</artifactId>
-            <version>2.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>log4j</groupId>
-            <artifactId>log4j</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.registry.core</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>commons-logging</groupId>
-            <artifactId>commons-logging</artifactId>
-        </dependency>
-    </dependencies>
-</project>
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/CloudDeploymentInterceptor.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/CloudDeploymentInterceptor.java b/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/CloudDeploymentInterceptor.java
deleted file mode 100644
index 469c459..0000000
--- a/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/CloudDeploymentInterceptor.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-
-package org.apache.stratos.deployment;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.description.AxisModule;
-import org.apache.axis2.description.AxisOperation;
-import org.apache.axis2.description.AxisService;
-import org.apache.axis2.description.AxisServiceGroup;
-import org.apache.axis2.description.Parameter;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.axis2.engine.AxisEvent;
-import org.apache.axis2.engine.AxisObserver;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import javax.xml.namespace.QName;
-import java.util.ArrayList;
-
-/**
- * Deployment interceptor for handling modification of ServiceAdmin so that the service list is not
- * displayed when the user has not logged in.
- */
-public class CloudDeploymentInterceptor implements AxisObserver {
-    private static final Log log = LogFactory.getLog(CloudDeploymentInterceptor.class);
-
-    public void init(AxisConfiguration axisConfiguration) {
-    }
-
-    public void serviceUpdate(AxisEvent axisEvent, AxisService axisService) {
-        try {
-            if (axisEvent.getEventType() == AxisEvent.SERVICE_DEPLOY &&
-                    axisService.getName().equals("ServiceAdmin")){
-                AxisOperation operation = axisService.getOperation(new QName("listServiceGroups"));
-                ArrayList<Parameter> params = operation.getParameters();
-                for(Parameter param: params) {
-                    operation.removeParameter(param);
-                }
-                Parameter authAction = new Parameter("AuthorizationAction",
-                        "/permission/admin/manage/monitor/service");
-                operation.addParameter(authAction);
-            }
-        } catch (AxisFault e) {
-            log.error("Cannot add AuthorizationAction parameter to ServiceAdmin", e);
-        }
-    }
-
-    public void serviceGroupUpdate(AxisEvent axisEvent, AxisServiceGroup axisServiceGroup) {
-    }
-
-    public void moduleUpdate(AxisEvent axisEvent, AxisModule axisModule) {
-    }
-
-    public void addParameter(Parameter parameter) throws AxisFault {
-    }
-
-    public void removeParameter(Parameter parameter) throws AxisFault {
-    }
-
-    public void deserializeParameters(OMElement omElement) throws AxisFault {
-    }
-
-    public Parameter getParameter(String s) {
-        return null;
-    }
-
-    public ArrayList<Parameter> getParameters() {
-        return null;
-    }
-
-    public boolean isParameterLocked(String s) {
-        return false;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/SuperTenantRolePlayer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/SuperTenantRolePlayer.java b/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/SuperTenantRolePlayer.java
deleted file mode 100644
index efd37d9..0000000
--- a/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/SuperTenantRolePlayer.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-
-package org.apache.stratos.deployment;
-
-import org.apache.axiom.soap.RolePlayer;
-import org.wso2.carbon.base.MultitenantConstants;
-import org.wso2.carbon.context.CarbonContext;
-
-import java.util.List;
-import java.util.ArrayList;
-
-public class SuperTenantRolePlayer implements RolePlayer{
-
-    private List<String> roles;
-
-    public SuperTenantRolePlayer() {
-        this.roles = new ArrayList<String>();
-        this.roles.add("supertenant");
-    }
-
-    public List getRoles() {
-        return this.roles;
-    }
-
-    public boolean isUltimateDestination() {
-        return (CarbonContext.getCurrentContext().getTenantId() ==
-                MultitenantConstants.SUPER_TENANT_ID);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/internal/CloudDeploymentServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/internal/CloudDeploymentServiceComponent.java b/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/internal/CloudDeploymentServiceComponent.java
deleted file mode 100644
index 926264f..0000000
--- a/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/internal/CloudDeploymentServiceComponent.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-
-package org.apache.stratos.deployment.internal;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.description.Parameter;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.axis2.engine.AxisObserver;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.deployment.CloudDeploymentInterceptor;
-import org.apache.stratos.deployment.SuperTenantRolePlayer;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.CarbonConstants;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-import java.util.Dictionary;
-import java.util.Hashtable;
-
-/**
- * @scr.component name="org.apache.stratos.deployment.internal.CloudDeploymentServiceComponent" immediate="true"
- * @scr.reference name="config.context.service"
- * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
- * policy="dynamic" bind="setConfigurationContextService"
- * unbind="unsetConfigurationContextService"
- */
-public class CloudDeploymentServiceComponent {
-    private static final Log log = LogFactory.getLog(CloudDeploymentServiceComponent.class);
-
-    protected void activate(ComponentContext ctxt) {
-        //TODO: Modify the permission in the UI
-        try {
-            ConfigurationContext configContext = DataHolder.getInstance().getServerConfigContext();
-            Dictionary props = new Hashtable();
-            props.put(CarbonConstants.AXIS2_CONFIG_SERVICE, AxisObserver.class.getName());
-            ctxt.getBundleContext().registerService(AxisObserver.class.getName(), new CloudDeploymentInterceptor(),props);
-
-            // register the role player for this configuration
-            AxisConfiguration axisConfiguration = configContext.getAxisConfiguration();
-            axisConfiguration.addParameter(new Parameter("rolePlayer", new SuperTenantRolePlayer()));
-        } catch (Exception e) {
-            log.error("CloudDeploymentServiceComponent activation failed", e);
-        }
-    }
-
-    protected void deactivate(ComponentContext ctxt) {
-
-    }
-
-    protected void setConfigurationContextService(ConfigurationContextService contextService) {
-        DataHolder.getInstance().setServerConfigContext(contextService.getServerConfigContext());
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
-        DataHolder.getInstance().setServerConfigContext(null);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/internal/DataHolder.java b/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/internal/DataHolder.java
deleted file mode 100644
index 585ac1e..0000000
--- a/components/org.apache.stratos.deployment/2.1.0/src/main/java/org/apache/stratos/deployment/internal/DataHolder.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
-*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-
-package org.apache.stratos.deployment.internal;
-
-import org.apache.axis2.context.ConfigurationContext;
-
-/**
- * DataHolder for Service deployment component
- */
-public class DataHolder {
-    private static DataHolder instance = new DataHolder();
-
-    private ConfigurationContext serverConfigContext;
-
-    public static DataHolder getInstance() {
-        return instance;
-    }
-
-    private DataHolder() {
-    }
-
-    public ConfigurationContext getServerConfigContext() {
-        return serverConfigContext;
-    }
-
-    public void setServerConfigContext(ConfigurationContext serverConfigContext) {
-        this.serverConfigContext = serverConfigContext;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.deployment/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.deployment/pom.xml b/components/org.apache.stratos.deployment/pom.xml
new file mode 100644
index 0000000..7a7399d
--- /dev/null
+++ b/components/org.apache.stratos.deployment/pom.xml
@@ -0,0 +1,104 @@
+<!--
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+       <groupId>org.apache.stratos</groupId>
+       <artifactId>stratos-components-parent</artifactId>
+       <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.deployment</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Deployment</name>
+
+    <build>
+
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <version>2.0</version>
+                <configuration>
+                    <source>1.5</source>
+                    <target>1.5</target>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Private-Package>
+                            org.apache.stratos.deployment.internal.*
+                        </Private-Package>
+                        <Export-Package>
+                            !org.apache.stratos.deployment.internal.*,
+                            org.apache.stratos.deployment.*
+                        </Export-Package>
+                        <Import-Package>
+                            !javax.xml.namespace,
+                            org.apache.axis2.*; version="${axis2.osgi.version.range}",
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+            <version>${apache.stratos.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+    </dependencies>
+</project>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/CloudDeploymentInterceptor.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/CloudDeploymentInterceptor.java b/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/CloudDeploymentInterceptor.java
new file mode 100644
index 0000000..469c459
--- /dev/null
+++ b/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/CloudDeploymentInterceptor.java
@@ -0,0 +1,91 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.stratos.deployment;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.description.AxisModule;
+import org.apache.axis2.description.AxisOperation;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.AxisServiceGroup;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.axis2.engine.AxisEvent;
+import org.apache.axis2.engine.AxisObserver;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.xml.namespace.QName;
+import java.util.ArrayList;
+
+/**
+ * Deployment interceptor for handling modification of ServiceAdmin so that the service list is not
+ * displayed when the user has not logged in.
+ */
+public class CloudDeploymentInterceptor implements AxisObserver {
+    private static final Log log = LogFactory.getLog(CloudDeploymentInterceptor.class);
+
+    public void init(AxisConfiguration axisConfiguration) {
+    }
+
+    public void serviceUpdate(AxisEvent axisEvent, AxisService axisService) {
+        try {
+            if (axisEvent.getEventType() == AxisEvent.SERVICE_DEPLOY &&
+                    axisService.getName().equals("ServiceAdmin")){
+                AxisOperation operation = axisService.getOperation(new QName("listServiceGroups"));
+                ArrayList<Parameter> params = operation.getParameters();
+                for(Parameter param: params) {
+                    operation.removeParameter(param);
+                }
+                Parameter authAction = new Parameter("AuthorizationAction",
+                        "/permission/admin/manage/monitor/service");
+                operation.addParameter(authAction);
+            }
+        } catch (AxisFault e) {
+            log.error("Cannot add AuthorizationAction parameter to ServiceAdmin", e);
+        }
+    }
+
+    public void serviceGroupUpdate(AxisEvent axisEvent, AxisServiceGroup axisServiceGroup) {
+    }
+
+    public void moduleUpdate(AxisEvent axisEvent, AxisModule axisModule) {
+    }
+
+    public void addParameter(Parameter parameter) throws AxisFault {
+    }
+
+    public void removeParameter(Parameter parameter) throws AxisFault {
+    }
+
+    public void deserializeParameters(OMElement omElement) throws AxisFault {
+    }
+
+    public Parameter getParameter(String s) {
+        return null;
+    }
+
+    public ArrayList<Parameter> getParameters() {
+        return null;
+    }
+
+    public boolean isParameterLocked(String s) {
+        return false;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/SuperTenantRolePlayer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/SuperTenantRolePlayer.java b/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/SuperTenantRolePlayer.java
new file mode 100644
index 0000000..efd37d9
--- /dev/null
+++ b/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/SuperTenantRolePlayer.java
@@ -0,0 +1,45 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.stratos.deployment;
+
+import org.apache.axiom.soap.RolePlayer;
+import org.wso2.carbon.base.MultitenantConstants;
+import org.wso2.carbon.context.CarbonContext;
+
+import java.util.List;
+import java.util.ArrayList;
+
+public class SuperTenantRolePlayer implements RolePlayer{
+
+    private List<String> roles;
+
+    public SuperTenantRolePlayer() {
+        this.roles = new ArrayList<String>();
+        this.roles.add("supertenant");
+    }
+
+    public List getRoles() {
+        return this.roles;
+    }
+
+    public boolean isUltimateDestination() {
+        return (CarbonContext.getCurrentContext().getTenantId() ==
+                MultitenantConstants.SUPER_TENANT_ID);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/internal/CloudDeploymentServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/internal/CloudDeploymentServiceComponent.java b/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/internal/CloudDeploymentServiceComponent.java
new file mode 100644
index 0000000..926264f
--- /dev/null
+++ b/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/internal/CloudDeploymentServiceComponent.java
@@ -0,0 +1,73 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.stratos.deployment.internal;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.axis2.engine.AxisObserver;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.deployment.CloudDeploymentInterceptor;
+import org.apache.stratos.deployment.SuperTenantRolePlayer;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import java.util.Dictionary;
+import java.util.Hashtable;
+
+/**
+ * @scr.component name="org.apache.stratos.deployment.internal.CloudDeploymentServiceComponent" immediate="true"
+ * @scr.reference name="config.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
+ * policy="dynamic" bind="setConfigurationContextService"
+ * unbind="unsetConfigurationContextService"
+ */
+public class CloudDeploymentServiceComponent {
+    private static final Log log = LogFactory.getLog(CloudDeploymentServiceComponent.class);
+
+    protected void activate(ComponentContext ctxt) {
+        //TODO: Modify the permission in the UI
+        try {
+            ConfigurationContext configContext = DataHolder.getInstance().getServerConfigContext();
+            Dictionary props = new Hashtable();
+            props.put(CarbonConstants.AXIS2_CONFIG_SERVICE, AxisObserver.class.getName());
+            ctxt.getBundleContext().registerService(AxisObserver.class.getName(), new CloudDeploymentInterceptor(),props);
+
+            // register the role player for this configuration
+            AxisConfiguration axisConfiguration = configContext.getAxisConfiguration();
+            axisConfiguration.addParameter(new Parameter("rolePlayer", new SuperTenantRolePlayer()));
+        } catch (Exception e) {
+            log.error("CloudDeploymentServiceComponent activation failed", e);
+        }
+    }
+
+    protected void deactivate(ComponentContext ctxt) {
+
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        DataHolder.getInstance().setServerConfigContext(contextService.getServerConfigContext());
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+        DataHolder.getInstance().setServerConfigContext(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/internal/DataHolder.java b/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/internal/DataHolder.java
new file mode 100644
index 0000000..585ac1e
--- /dev/null
+++ b/components/org.apache.stratos.deployment/src/main/java/org/apache/stratos/deployment/internal/DataHolder.java
@@ -0,0 +1,45 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.stratos.deployment.internal;
+
+import org.apache.axis2.context.ConfigurationContext;
+
+/**
+ * DataHolder for Service deployment component
+ */
+public class DataHolder {
+    private static DataHolder instance = new DataHolder();
+
+    private ConfigurationContext serverConfigContext;
+
+    public static DataHolder getInstance() {
+        return instance;
+    }
+
+    private DataHolder() {
+    }
+
+    public ConfigurationContext getServerConfigContext() {
+        return serverConfigContext;
+    }
+
+    public void setServerConfigContext(ConfigurationContext serverConfigContext) {
+        this.serverConfigContext = serverConfigContext;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/2.1.0/pom.xml b/components/org.apache.stratos.keystore.mgt/2.1.0/pom.xml
deleted file mode 100644
index c482ee2..0000000
--- a/components/org.apache.stratos.keystore.mgt/2.1.0/pom.xml
+++ /dev/null
@@ -1,127 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-  -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-<relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.keystore.mgt</artifactId>
-    <version>2.1.0</version>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Keystore Generation and Management</name>
-
-    <build>
-        <plugins>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Private-Package>
-                            org.apache.stratos.keystore.mgt.internal
-                        </Private-Package>
-                        <Export-Package>
-                            !org.apache.stratos.keystore.mgt.internal,
-                            org.apache.stratos.keystore.mgt.*,
-                        </Export-Package>
-                        <Import-Package>
-                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
-                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
-                            org.wso2.carbon.security.*,
-                            org.apache.lucene.*,
-                            *;resolution:=optional
-                        </Import-Package>
-                        <Embed-Dependency>
-                            bcprov-jdk15|naming-factory|naming-resources|commons-collections;scope=compile|runtime;inline=false
-                        </Embed-Dependency>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-
-        </plugins>
-    </build>
-
-    <dependencies>
-
-        <dependency>
-            <groupId>log4j</groupId>
-            <artifactId>log4j</artifactId>
-        </dependency>
-	<dependency>
-            <groupId>commons-codec.wso2</groupId>
-            <artifactId>commons-codec</artifactId>
-		<version>1.4.0.wso2v1</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.registry.core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>commons-logging</groupId>
-            <artifactId>commons-logging</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.eclipse.equinox</groupId>
-            <artifactId>javax.servlet</artifactId>
-	    <version>${version.javax.servlet}</version>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.ws.commons.axiom.wso2</groupId>
-            <artifactId>axiom</artifactId>
-            <version>1.2.11.wso2v3</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.stratos</groupId>
-            <artifactId>org.apache.stratos.common</artifactId>
-	    <version>2.1.2</version>
-        </dependency>
-        <dependency>
-            <groupId>bouncycastle</groupId>
-            <artifactId>bcprov-jdk15</artifactId>
-            <version>132</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.security.mgt</artifactId>
-	    <version>${wso2carbon.version}</version>
-        </dependency>
-    </dependencies>
-
-    <properties>
-        <version.javax.servlet>3.0.0.v201112011016</version.javax.servlet>
-    </properties>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreGenerator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreGenerator.java b/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreGenerator.java
deleted file mode 100644
index b8e892e..0000000
--- a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreGenerator.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.keystore.mgt;
-
-import org.apache.axiom.om.util.UUIDGenerator;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.bouncycastle.jce.X509Principal;
-import org.bouncycastle.jce.X509V3CertificateGenerator;
-import org.wso2.carbon.core.RegistryResources;
-import org.wso2.carbon.core.util.CryptoUtil;
-import org.apache.stratos.keystore.mgt.util.RealmServiceHolder;
-import org.apache.stratos.keystore.mgt.util.RegistryServiceHolder;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.security.SecurityConstants;
-import org.wso2.carbon.security.keystore.KeyStoreAdmin;
-import org.wso2.carbon.user.core.service.RealmService;
-
-import java.io.ByteArrayOutputStream;
-import java.math.BigInteger;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.KeyStore;
-import java.security.SecureRandom;
-import java.security.cert.X509Certificate;
-import java.util.Date;
-
-/**
- * This class is used to generate a key store for a tenant and store it in the governance registry.
- */
-public class KeyStoreGenerator {
-
-    private static Log log = LogFactory.getLog(KeyStoreGenerator.class);
-    private UserRegistry govRegistry;
-    private int tenantId;
-    private String tenantDomain;
-    private String password;
-
-
-    public KeyStoreGenerator(int  tenantId) throws KeyStoreMgtException {
-        try {
-            this.tenantId = tenantId;
-            this.tenantDomain = getTenantDomainName();
-            this.govRegistry = RegistryServiceHolder.getRegistryService().
-                    getGovernanceSystemRegistry(tenantId);
-            if(govRegistry == null){
-                log.error("Governance registry instance is null");
-                throw new KeyStoreMgtException("Governance registry instance is null");
-            }
-        } catch (RegistryException e) {
-            String errorMsg = "Error while obtaining the governance registry for tenant : " +
-                      tenantId;
-            log.error(errorMsg, e);
-            throw new KeyStoreMgtException(errorMsg, e);
-        }
-    }
-
-
-    /**
-     * This method first generates the keystore, then persist it in the gov.registry of that tenant
-     *
-     * @throws KeyStoreMgtException Error when generating or storing the keystore
-     */
-    public void generateKeyStore() throws KeyStoreMgtException {
-        try {
-            password = generatePassword();
-            KeyStore keyStore = KeyStore.getInstance("JKS");
-            keyStore.load(null, password.toCharArray());
-            X509Certificate pubCert = generateKeyPair(keyStore);
-            persistKeyStore(keyStore, pubCert);
-        } catch (Exception e) {
-            String msg = "Error while instantiating a keystore";
-            log.error(msg, e);
-            throw new KeyStoreMgtException(msg, e);
-        }
-    }
-
-    /**
-     * This method generates the keypair and stores it in the keystore
-     *
-     * @param keyStore A keystore instance
-     * @return Generated public key for the tenant
-     * @throws KeyStoreMgtException Error when generating key pair
-     */
-    private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException {
-        try {
-            CryptoUtil.getDefaultCryptoUtil();
-            //generate key pair
-            KeyPairGenerator keyPairGenerator = null;
-            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
-            keyPairGenerator.initialize(1024);
-            KeyPair keyPair = keyPairGenerator.generateKeyPair();
-
-            // Common Name and alias for the generated certificate
-            String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None";
-
-            //generate certificates
-            X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
-            v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()));
-            v3CertGen.setIssuerDN(new X509Principal(commonName));
-            v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
-            v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
-            v3CertGen.setSubjectDN(new X509Principal(commonName));
-            v3CertGen.setPublicKey(keyPair.getPublic());
-            v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
-            X509Certificate PKCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());
-
-            //add private key to KS
-            keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(),
-                                 new java.security.cert.Certificate[]{PKCertificate});
-            return PKCertificate;
-        } catch (Exception ex) {
-            String msg = "Error while generating the certificate for tenant :" +
-                         tenantDomain + ".";
-            log.error(msg, ex);
-            throw new KeyStoreMgtException(msg, ex);
-        }
-
-    }
-
-    /**
-     * Persist the keystore in the gov.registry
-     *
-     * @param keyStore created Keystore of the tenant
-     * @param PKCertificate pub. key of the tenant
-     * @throws KeyStoreMgtException Exception when storing the keystore in the registry
-     */
-    private void persistKeyStore(KeyStore keyStore, X509Certificate PKCertificate)
-            throws KeyStoreMgtException {
-        try {
-            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
-            keyStore.store(outputStream, password.toCharArray());
-            outputStream.flush();
-            outputStream.close();
-
-            String keyStoreName = generateKSNameFromDomainName();
-            // Use the keystore using the keystore admin
-            KeyStoreAdmin keystoreAdmin = new KeyStoreAdmin(tenantId, govRegistry);
-            keystoreAdmin.addKeyStore(outputStream.toByteArray(), keyStoreName,
-                                      password, " ", "JKS", password);
-            
-            //Create the pub. key resource
-            Resource pubKeyResource = govRegistry.newResource();
-            pubKeyResource.setContent(PKCertificate.getEncoded());
-            pubKeyResource.addProperty(SecurityConstants.PROP_TENANT_PUB_KEY_FILE_NAME_APPENDER,
-                                       generatePubKeyFileNameAppender());
-
-            govRegistry.put(RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE, pubKeyResource);
-
-            //associate the public key with the keystore
-            govRegistry.addAssociation(RegistryResources.SecurityManagement.KEY_STORES + "/" + keyStoreName,
-                                       RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE,
-                                       SecurityConstants.ASSOCIATION_TENANT_KS_PUB_KEY);
-
-        } catch (RegistryException e) {
-            String msg = "Error when writing the keystore/pub.cert to registry";
-            log.error(msg, e);
-            throw new KeyStoreMgtException(msg, e);
-        }
-        catch (Exception e) {
-            String msg = "Error when processing keystore/pub. cert to be stored in registry";
-            log.error(msg, e);
-            throw new KeyStoreMgtException(msg, e);
-        }
-    }
-
-    /**
-     * This method is used to generate a random password for the generated keystore
-     *
-     * @return generated password
-     */
-    private String generatePassword() {
-        SecureRandom random = new SecureRandom();
-        String randString = new BigInteger(130, random).toString(12);
-        return randString.substring(randString.length() - 10, randString.length());
-    }
-
-    /**
-     * This method is used to generate a file name appender for the pub. cert, e.g.
-     * example-com-343743.cert
-     * @return generated string to be used as a file name appender
-     */
-    private String generatePubKeyFileNameAppender(){
-        String uuid = UUIDGenerator.getUUID();
-        return uuid.substring(uuid.length() - 6, uuid.length()-1);
-    }
-
-    /**
-     * This method generates the key store file name from the Domain Name
-     * @return
-     */
-    private String generateKSNameFromDomainName(){
-        String ksName = tenantDomain.trim().replace(".", "-");
-        return (ksName + ".jks" );
-    }
-
-    private String getTenantDomainName() throws KeyStoreMgtException {
-        RealmService realmService = RealmServiceHolder.getRealmService();
-        if (realmService == null) {
-            String msg = "Error in getting the domain name, realm service is null.";
-            log.error(msg);
-            throw new KeyStoreMgtException(msg);
-        }
-        try {
-            return realmService.getTenantManager().getDomain(tenantId);
-        } catch (org.wso2.carbon.user.api.UserStoreException e) {
-            String msg = "Error in getting the domain name for the tenant id: " + tenantId;
-            log.error(msg, e);
-            throw new KeyStoreMgtException(msg, e);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreMgtException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreMgtException.java b/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreMgtException.java
deleted file mode 100644
index de486f0..0000000
--- a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreMgtException.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.keystore.mgt;
-
-/**
- * This class is used to wrap the exceptions thrown from stratos keystore mgt component.
- */
-public class KeyStoreMgtException extends Exception {
-    public KeyStoreMgtException() {
-    }
-
-    public KeyStoreMgtException(String message) {
-        super(message);
-    }
-
-    public KeyStoreMgtException(String message, Throwable cause) {
-        super(message, cause);
-    }
-
-    public KeyStoreMgtException(Throwable cause) {
-        super(cause);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeystoreTenantMgtListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeystoreTenantMgtListener.java b/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeystoreTenantMgtListener.java
deleted file mode 100644
index b4eaf6c..0000000
--- a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/KeystoreTenantMgtListener.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.keystore.mgt;
-
-import org.apache.stratos.common.beans.TenantInfoBean;
-import org.apache.stratos.common.exception.StratosException;
-import org.apache.stratos.common.listeners.TenantMgtListener;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * This class is used to listen to the tenant creation events and fire the keystore creation event
- */
-public class KeystoreTenantMgtListener implements TenantMgtListener {
-
-    private static Log log = LogFactory.getLog(KeystoreTenantMgtListener.class);
-    private static final int EXEC_ORDER = 20;
-
-    /**
-     * Generate the keystore when a new tenant is registered.
-     * @param tenantInfo Information about the newly created tenant
-     */
-    public void onTenantCreate(TenantInfoBean tenantInfo) throws StratosException {
-        try {
-            KeyStoreGenerator ksGenerator = new KeyStoreGenerator(tenantInfo.getTenantId());
-            ksGenerator.generateKeyStore();
-        } catch (KeyStoreMgtException e) {
-            String message = "Error when generating the keystore";
-            log.error(message, e);
-            throw new StratosException(message, e);
-        }
-    }
-
-    public void onTenantUpdate(TenantInfoBean tenantInfo) throws StratosException {
-        // It is not required to implement this method for keystore mgt. 
-    }
-
-    public void onTenantRename(int tenantId, String oldDomainName,
-                             String newDomainName) throws StratosException {
-        // It is not required to implement this method for keystore mgt.
-    }
-
-    public int getListenerOrder() {
-        return EXEC_ORDER;
-    }
-
-    public void onTenantInitialActivation(int tenantId) throws StratosException {
-        // It is not required to implement this method for keystore mgt. 
-    }
-
-    public void onTenantActivation(int tenantId) throws StratosException {
-        // It is not required to implement this method for keystore mgt. 
-    }
-
-    public void onTenantDeactivation(int tenantId) throws StratosException {
-        // It is not required to implement this method for keystore mgt. 
-    }
-
-    public void onSubscriptionPlanChange(int tenentId, String oldPlan, 
-                                         String newPlan) throws StratosException {
-        // It is not required to implement this method for keystore mgt. 
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/internal/KeyStoreMgtServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/internal/KeyStoreMgtServiceComponent.java b/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/internal/KeyStoreMgtServiceComponent.java
deleted file mode 100644
index bc9b44f..0000000
--- a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/internal/KeyStoreMgtServiceComponent.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.keystore.mgt.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.apache.stratos.keystore.mgt.KeystoreTenantMgtListener;
-import org.apache.stratos.keystore.mgt.util.RealmServiceHolder;
-import org.apache.stratos.keystore.mgt.util.RegistryServiceHolder;
-
-/**
- * @scr.component name="org.apache.stratos.keystore.mgt"
- * immediate="true"
- * @scr.reference name="registry.service"
- * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="1..1"
- * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
- * @scr.reference name="user.realmservice.default" interface="org.wso2.carbon.user.core.service.RealmService"
- * cardinality="1..1" policy="dynamic" bind="setRealmService"
- * unbind="unsetRealmService"
- */
-public class KeyStoreMgtServiceComponent {
-
-    private static Log log = LogFactory.getLog(KeyStoreMgtServiceComponent.class);
-
-
-    protected void activate(ComponentContext ctxt){
-        KeystoreTenantMgtListener keystoreTenantMgtListener = new KeystoreTenantMgtListener();
-        ctxt.getBundleContext().registerService(
-                org.apache.stratos.common.listeners.TenantMgtListener.class.getName(),
-                keystoreTenantMgtListener, null);
-        if (log.isDebugEnabled()) {
-            log.debug("*************Stratos Keystore mgt component is activated.**************");
-        }
-    }
-
-    protected void deactivate(ComponentContext ctxt) {
-        if(log.isDebugEnabled()){
-            log.debug("************Stratos keystore mgt component is decativated.*************");
-        }
-    }
-
-    protected void setRegistryService(RegistryService registryService){
-        RegistryServiceHolder.setRegistryService(registryService);
-        if (log.isDebugEnabled()) {
-            log.debug("Registry Service is set for KeyStoreMgtServiceComponent.");
-        }
-    }
-
-    protected void unsetRegistryService(RegistryService registryService){
-        RegistryServiceHolder.setRegistryService(null);
-        if(log.isDebugEnabled()){
-            log.debug("Registry Service is unset for KeyStoreMgtServiceComponent.");
-        }
-    }
-
-    protected void setRealmService(RealmService realmService){
-        RealmServiceHolder.setRealmService(realmService);
-        if (log.isDebugEnabled()) {
-            log.debug("Realm Service is set for KeyStoreMgtServiceComponent.");
-        }
-    }
-
-    protected void unsetRealmService(RealmService realmService){
-        RealmServiceHolder.setRealmService(null);
-        if(log.isDebugEnabled()){
-            log.debug("Realm Service is unset for KeyStoreMgtServiceComponent.");
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/util/RealmServiceHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/util/RealmServiceHolder.java b/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/util/RealmServiceHolder.java
deleted file mode 100644
index a1e6b16..0000000
--- a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/util/RealmServiceHolder.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.keystore.mgt.util;
-
-import org.wso2.carbon.user.core.service.RealmService;
-
-public class RealmServiceHolder {
-
-    private static RealmService realmServiceService;
-
-    public static RealmService getRealmService() {
-        return realmServiceService;
-    }
-
-    public static void setRealmService(RealmService realmService) {
-        RealmServiceHolder.realmServiceService = realmService;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/util/RegistryServiceHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/util/RegistryServiceHolder.java b/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/util/RegistryServiceHolder.java
deleted file mode 100644
index 5b7ab4a..0000000
--- a/components/org.apache.stratos.keystore.mgt/2.1.0/src/main/java/org/apache/stratos/keystore/mgt/util/RegistryServiceHolder.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.keystore.mgt.util;
-
-import org.wso2.carbon.registry.core.service.RegistryService;
-
-public class RegistryServiceHolder {
-
-    private static RegistryService registryService;
-
-    public static RegistryService getRegistryService() {
-        return registryService;
-    }
-
-    public static void setRegistryService(RegistryService registryService) {
-        RegistryServiceHolder.registryService = registryService;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/pom.xml b/components/org.apache.stratos.keystore.mgt/pom.xml
new file mode 100644
index 0000000..df523be
--- /dev/null
+++ b/components/org.apache.stratos.keystore.mgt/pom.xml
@@ -0,0 +1,125 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.keystore.mgt</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Keystore Generation and Management</name>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Private-Package>
+                            org.apache.stratos.keystore.mgt.internal
+                        </Private-Package>
+                        <Export-Package>
+                            !org.apache.stratos.keystore.mgt.internal,
+                            org.apache.stratos.keystore.mgt.*,
+                        </Export-Package>
+                        <Import-Package>
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.wso2.carbon.security.*,
+                            org.apache.lucene.*,
+                            *;resolution:=optional
+                        </Import-Package>
+                        <Embed-Dependency>
+                            bcprov-jdk15|naming-factory|naming-resources|commons-collections;scope=compile|runtime;inline=false
+                        </Embed-Dependency>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+        </dependency>
+	<dependency>
+            <groupId>commons-codec.wso2</groupId>
+            <artifactId>commons-codec</artifactId>
+		<version>1.4.0.wso2v1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.equinox</groupId>
+            <artifactId>javax.servlet</artifactId>
+	    <version>${version.javax.servlet}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.ws.commons.axiom.wso2</groupId>
+            <artifactId>axiom</artifactId>
+            <version>1.2.11.wso2v3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+	    <version>${apache.stratos.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>bouncycastle</groupId>
+            <artifactId>bcprov-jdk15</artifactId>
+            <version>132</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.security.mgt</artifactId>
+	    <version>${wso2carbon.version}</version>
+        </dependency>
+    </dependencies>
+
+    <properties>
+        <version.javax.servlet>3.0.0.v201112011016</version.javax.servlet>
+    </properties>
+</project>


[43/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/impl/AutoscalerServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/impl/AutoscalerServiceImpl.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/impl/AutoscalerServiceImpl.java
deleted file mode 100644
index b87cb50..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/impl/AutoscalerServiceImpl.java
+++ /dev/null
@@ -1,1389 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.impl;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.Closeable;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.RunNodesException;
-import org.jclouds.compute.domain.ComputeMetadata;
-import org.jclouds.compute.domain.NodeMetadata;
-import org.jclouds.compute.domain.NodeMetadata.Status;
-import org.jclouds.compute.domain.Template;
-import org.jclouds.compute.domain.TemplateBuilder;
-import org.jclouds.compute.domain.internal.NodeMetadataImpl;
-import org.jclouds.compute.options.TemplateOptions;
-import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
-import org.apache.stratos.autoscaler.service.IAutoscalerService;
-import org.apache.stratos.autoscaler.service.exception.AutoscalerServiceException;
-import org.apache.stratos.autoscaler.service.exception.DeserializationException;
-import org.apache.stratos.autoscaler.service.exception.SerializationException;
-import org.apache.stratos.autoscaler.service.io.Deserializer;
-import org.apache.stratos.autoscaler.service.io.Serializer;
-import org.apache.stratos.autoscaler.service.jcloud.ComputeServiceBuilder;
-import org.apache.stratos.autoscaler.service.util.AutoscalerConstant;
-import org.apache.stratos.autoscaler.service.util.IaasContext;
-import org.apache.stratos.autoscaler.service.util.IaasProvider;
-import org.apache.stratos.autoscaler.service.util.InstanceContext;
-import org.apache.stratos.autoscaler.service.util.ServiceTemplate;
-import org.apache.stratos.autoscaler.service.xml.ElasticScalerConfigFileReader;
-import org.apache.stratos.lb.common.conf.util.Constants;
-import org.wso2.carbon.utils.CarbonUtils;
-
-/**
- * Autoscaler Service is responsible for starting up new server instances, terminating already
- * started instances, providing pending instance count.
- * 
- */
-public class AutoscalerServiceImpl implements IAutoscalerService {
-
-	
-	private static final Log log = LogFactory.getLog(AutoscalerServiceImpl.class);
-
-    /**
-     * pointer to Carbon Home directory.
-     */
-    private static final String CARBON_HOME = CarbonUtils.getCarbonHome();
-
-    /**
-     * pointer to Carbon Temp directory.
-     */
-    private static final String CARBON_TEMP = CarbonUtils.getTmpDir();
-
-    /**
-     * Tenant id Delimiter
-     */
-	private static final String TENANT_ID_DELIMITER = "/t/";
-
-    /**
-     * This directory will be used to store serialized objects.
-     */
-    private String serializationDir;
-
-    /**
-     * List of all <code>IaaSProviders</code> specified in the config file.
-     */
-    private List<IaasProvider> iaasProviders;
-
-    /**
-     * List of all <code>ServiceTemplate</code> objects.
-     */
-    private List<ServiceTemplate> serviceTemps;
-
-    /**
-     * We keep an enum which contains all supported IaaSes.
-     */
-    public enum Iaases {
-        ec2, openstack
-    };
-
-    /**
-     * List which keeps <code>IaasContext</code> objects.
-     */
-    private List<IaasContext> iaasContextList = new ArrayList<IaasContext>();
-
-    /**
-     * We keep track of the IaaS where the last instance of a domain and a sub domain combination is spawned.
-     * This is required when there are multiple <code>IaasProvider</code>s defined.
-     * Key - domain
-     * Value - a map which has a Key - sub domain and Value - name of the {@link IaasProvider}.
-     */
-    private Map<String, Map<String, String>> lastlyUsedIaasMap = new HashMap<String, Map<String, String>>();
-
-    /**
-     * To track whether the {@link #initAutoscaler(boolean)} method has been called.
-     */
-    boolean isInitialized = false;
-
-    @Override
-    public boolean initAutoscaler(boolean isSpi) {
-
-        if (!isInitialized) {
-
-            log.debug("InitAutoscaler has started ...  IsSPI : " + isSpi);
-
-            // load configuration file
-            ElasticScalerConfigFileReader configReader = new ElasticScalerConfigFileReader();
-
-            // read serialization directory from config file if specified, else will use the
-            // default.
-            if ("".equals(serializationDir = configReader.getSerializationDir())) {
-                serializationDir = CARBON_TEMP;
-
-                log.debug("Directory to be used to serialize objects: " + serializationDir);
-            }
-
-            // let's deserialize and load the serialized objects.
-            deserialize();
-
-            // from config file, we grab the details unique to IaaS providers.
-            iaasProviders = configReader.getIaasProvidersList();
-
-            // from config file, we grab the details related to each service domain.
-            serviceTemps = configReader.getTemplates();
-
-            // we iterate through each IaaSProvider which is loaded from the config file.
-            for (IaasProvider iaas : iaasProviders) {
-
-                // build the JClouds specific ComputeService object
-                ComputeService computeService = ComputeServiceBuilder.buildComputeService(iaas);
-                IaasContext entity;
-
-                // let's see whether there's a serialized entity
-                entity = findIaasContext(iaas.getType());
-
-                if (entity != null) {
-
-                    log.debug("Serializable object is loaded for IaaS " + iaas.getType());
-
-                    // ComputeService isn't serializable, hence we need to set it in the
-                    // deserialized
-                    // object.
-                    entity.setComputeService(computeService);
-                }
-
-                // build JClouds Template objects according to different IaaSes
-                if (iaas.getType().equalsIgnoreCase(Iaases.ec2.toString())) {
-
-                    // initiate the IaasContext object, if it is null.
-                    entity =
-                             (entity == null) ? (entity =
-                                                          new IaasContext(Iaases.ec2,
-                                                                          computeService)) : entity;
-
-                    // we should build the templates only if this is not SPI stuff
-                    if (!isSpi) {
-                        // Build the Template
-                        buildEC2Templates(entity, iaas.getTemplate(), isSpi);
-
-                    } else {
-                        // add to data structure
-                        iaasContextList.add(entity);
-                    }
-
-                } else if (iaas.getType().equalsIgnoreCase(Iaases.openstack.toString())) {
-
-                    // initiate the IaasContext object, if it is null.
-                    entity =
-                             (entity == null) ? (entity =
-                                                          new IaasContext(Iaases.openstack,
-                                                                          computeService)) : entity;
-
-                    // we should build the templates only if this is not SPI stuff
-                    if (!isSpi) {
-                        // Build the Template
-                        buildLXCTemplates(entity, iaas.getTemplate(), isSpi, null);
-
-                    } else {
-                        // add to data structure
-                        iaasContextList.add(entity);
-                    }
-
-                } else {
-                    // unsupported IaaS detected. We only complain, since there could be other
-                    // IaaSes.
-                    String msg =
-                                 "Unsupported IaasProvider is specified in the config file: " +
-                                         iaas.getType() + ". Supported IaasProviders are " +
-                                         print(Iaases.values());
-                    log.warn(msg);
-                    continue;
-                }
-
-                // populate scale up order
-                fillInScaleUpOrder();
-
-                // populate scale down order
-                fillInScaleDownOrder();
-
-                // serialize the objects
-                serialize();
-            }
-
-            // we couldn't locate any valid IaaS providers from config file, thus shouldn't proceed.
-            if (iaasContextList.size() == 0) {
-                String msg = "No valid IaaS provider specified in the config file!";
-                log.error(msg);
-                throw new AutoscalerServiceException(msg);
-            }
-
-            // initialization completed.
-            isInitialized = true;
-
-            log.info("Autoscaler service initialized successfully!!");
-
-            return true;
-        }
-        
-        log.debug("Autoscaler Service is already initialized!");
-        return false;
-    }
-
-    
-    @Override
-    public boolean startInstance(String domainName, String subDomainName) {
-
-        // initialize the service, if it's not already initialized.
-        initAutoscaler(false);
-
-        ComputeService computeService;
-        Template template;
-        
-        subDomainName = checkSubDomain(subDomainName);
-
-        log.info("Starting new instance of domain : " + domainName+" and sub domain : "+subDomainName);
-
-        // sort the IaasContext entities according to scale up order
-        Collections.sort(iaasContextList,
-                         IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_UP_SORT)));
-
-        // traverse through IaasContext object instances in scale up order
-        for (IaasContext iaasCtxt : iaasContextList) {
-
-            // get the ComputeService
-            computeService = iaasCtxt.getComputeService();
-
-            // from the list grab the Template corresponds to this domain
-            template = iaasCtxt.getTemplate(domainName, subDomainName);
-            
-            if(template == null){
-                String msg = "Failed to start an instance in " + iaasCtxt.getName().toString() +
-                        ". Reason : Template is null. You have not specify a matching service " +
-                        "element in the configuration file of Autoscaler.\n Hence, will try to " +
-                        "start in another IaaS if available.";
-                log.error(msg);
-                continue;
-            }
-
-            // generate the group id from domain name and sub domain name.
-            // Should have lower-case ASCII letters, numbers, or dashes.
-            String str = domainName.concat("-"+subDomainName);
-            String group = str.replaceAll("[^a-z0-9-]", "");
-
-            try {
-                // create and start a node
-                Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(group,
-                                                                                      1,
-                                                                                      template);
-
-                NodeMetadata node = nodes.iterator().next();
-
-//                // add the details of the started node to maps
-//                iaasCtxt.addNodeIdToDomainMap(node.getId(), domainName);
-                
-                String ip="";
-
-                // set public Ip, if it's available
-                if (node.getPublicAddresses().size() > 0) {
-                    ip = node.getPublicAddresses().iterator().next();
-//                    iaasCtxt.addPublicIpToDomainMap(publicIp, domainName);
-//                    iaasCtxt.addPublicIpToNodeIdMap(publicIp, node.getId());
-                } else if(node.getPrivateAddresses().size() > 0) { // set private IPs if no public IP s are returned
-                	ip = node.getPrivateAddresses().iterator().next();
-//                    iaasCtxt.addPublicIpToDomainMap(privateIp, domainName);
-//                    iaasCtxt.addPublicIpToNodeIdMap(privateIp, node.getId());
-                } else{
-                    log.debug("Public IP of the node : "+node.getId()+" cannot be found.");
-                }
-                
-        
-                if (iaasCtxt.getInstanceContext(domainName, subDomainName) == null) {
-                    String msg = "Failed to start an instance in " + iaasCtxt.getName().toString() +
-                            ". Reason : InstanceContext is null. Hence, will try to start in another IaaS if available.";
-                    log.error(msg);
-                    continue;
-                }
-                
-                if(node.getId() == null){
-                    String msg = "Node id of the starting instance is null.\n"+ node.toString();
-                    log.fatal(msg);
-                    throw new AutoscalerServiceException(msg);
-                }
-
-                // add run time data to InstanceContext
-                iaasCtxt.addNodeDetails(domainName, subDomainName, node.getId(), ip);
-                
-                // since we modified the IaasContext instance, let's replace it.
-                replaceIaasContext(iaasCtxt);
-
-                // update the lastlyUsedIaasMap
-                addToLastlyUsedIaasMap(domainName, subDomainName, iaasCtxt.getName().toString());
-//                lastlyUsedIaasMap.put(domainName, iaasCtxt.getName().toString());
-
-                if (log.isDebugEnabled()) {
-                    log.debug("Node details: \n" + node.toString() +
-                              "\n***************\n");
-                }
-
-            } catch (RunNodesException e) {
-                log.warn("Failed to start an instance in " + iaasCtxt.getName().toString() +
-                         ". Hence, will try to start in another IaaS if available.", e);
-                continue;
-            }
-
-            log.info("Instance is successfully starting up in IaaS " + iaasCtxt.getName()
-                                                                               .toString() + " ...");
-
-            // serialize the objects
-            serialize();
-
-            return true;
-        }
-
-        log.info("Failed to start instance, in any available IaaS.");
-
-        return false;
-
-    }
-
-    private String checkSubDomain(String subDomainName) {
-        // if sub domain is null, we assume it as default one.
-        if (subDomainName == null || "null".equalsIgnoreCase(subDomainName)) {
-            subDomainName = Constants.DEFAULT_SUB_DOMAIN;
-            log.debug("Sub domain is null, hence using the default value : " + subDomainName);
-        }
-        
-        return subDomainName;
-    }
-
-
-    private void addToLastlyUsedIaasMap(String domainName, String subDomainName, String iaasName) {
-
-        Map<String, String> map;
-        
-        if(lastlyUsedIaasMap.get(domainName) == null){
-            map = new HashMap<String, String>();
-            
-        } else{
-            map = lastlyUsedIaasMap.get(domainName);
-        }
-        
-        map.put(subDomainName, iaasName);
-        lastlyUsedIaasMap.put(domainName, map);
-        
-    }
-
-
-    @Override
-    public String startSpiInstance(String domainName, String subDomainName, String imageId) {
-
-        log.debug("Starting an SPI instance ... | domain: " + domainName + " | sub domain: " +
-        subDomainName + " | ImageId: " + imageId);
-        
-        // initialize the service, if it's not already initialized.
-        initAutoscaler(true);
-        
-        String tenantId = null;
-        String spiDomainName = null;       
-        
-        if(domainName != null) {
-        	// domainName will have the pattern <domainName>/t/<tenantId>
-        	String[] arr = domainName.split(TENANT_ID_DELIMITER);
-        	if(arr.length != 2) {
-        		String msg = "Domain name does not match with the expected pattern. Expected " +
-        				"pattern is <domainName>/t/<tenantId>";
-        		log.error(msg);
-        		throw new AutoscalerServiceException(msg);
-        	}
-        	spiDomainName = arr[0];
-        	tenantId = arr[1];
-        }
-        
-        IaasContext entry;
-
-        // FIXME: Build the Templates, for now we're doing a hack here. I don't know whether
-        // there's a proper fix.
-        // handle openstack case
-        if (imageId.startsWith("nova") && ((entry = findIaasContext(Iaases.openstack)) != null)) {
-
-            buildLXCTemplates(entry, imageId, true, tenantId);
-
-        } else if (((entry = findIaasContext(Iaases.ec2)) != null)) {
-
-            buildEC2Templates(entry, imageId, true);
-
-        } else {
-            String msg = "Invalid image id: " + imageId;
-            log.error(msg);
-            throw new AutoscalerServiceException(msg);
-        }
-
-        // let's start the instance
-        if (startInstance(spiDomainName, subDomainName)) {
-
-            // if it's successful, get the public IP of the started instance.
-            // FIXME remove --> String publicIP =
-            // findIaasContext(iaas).getLastMatchingPublicIp(domainName);
-            String publicIP = entry.getLastMatchingPublicIp(spiDomainName, subDomainName);
-
-            // if public IP is null, return an empty string, else return public IP.
-            return (publicIP == null) ? "" : publicIP;
-
-        }
-
-        return "";
-
-    }
-
-	@Override
-    public boolean terminateInstance(String domainName, String subDomainName) {
-
-        // initialize the service, if it's not already initialized.
-	    initAutoscaler(false);
-        
-        subDomainName = checkSubDomain(subDomainName);
-
-        log.info("Starting to terminate an instance of domain : " + domainName + " and sub domain : "+subDomainName);
-
-        // sort the IaasContext entities according to scale down order.
-        Collections.sort(iaasContextList,
-                         IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_DOWN_SORT)));
-
-        // traverse in scale down order
-        for (IaasContext iaasTemp : iaasContextList) {
-
-            String msg = "Failed to terminate an instance in " + iaasTemp.getName().toString() +
-                         ". Hence, will try to terminate an instance in another IaaS if possible.";
-
-            String nodeId = null;
-
-            // grab the node ids related to the given domain and traverse
-            for (String id : iaasTemp.getNodeIds(domainName, subDomainName)) {
-                if (id != null) {
-                    nodeId = id;
-                    break;
-                }
-            }
-
-            // if no matching node id can be found.
-            if (nodeId == null) {
-
-                log.warn(msg + " : Reason- No matching instance found for domain: " +
-                         domainName + " and sub domain: "+subDomainName+
-                         ".");
-                continue;
-            }
-
-            // terminate it!
-            terminate(iaasTemp, nodeId);
-
-            return true;
-
-        }
-
-        log.info("Termination of an instance which is belong to domain '" + domainName +
-                 "' and sub domain '"+subDomainName+"' , failed!\n Reason: No matching " +
-                 		"running instance found in any available IaaS.");
-
-        return false;
-
-    }
-
-    @Override
-    public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) {
-
-        // initialize the service, if it's not already initialized.
-        initAutoscaler(false);
-        
-        subDomainName = checkSubDomain(subDomainName);
-
-        // see whether there is a matching IaaS, where we spawn an instance belongs to given domain.
-        if (lastlyUsedIaasMap.containsKey(domainName)) {
-
-            // grab the name of the IaaS
-            String iaas = lastlyUsedIaasMap.get(domainName).get(subDomainName);
-
-            // find the corresponding IaasContext
-            IaasContext iaasTemp = findIaasContext(iaas);
-
-            String msg = "Failed to terminate the lastly spawned instance of '" + domainName +
-                         "' service domain.";
-
-            if (iaasTemp == null) {
-                log.error(msg + " : Reason- Iaas' data cannot be located!");
-                return false;
-            }
-
-            // find the instance spawned at last of this IaasContext
-            String nodeId = iaasTemp.getLastMatchingNode(domainName, subDomainName);
-
-            if (nodeId == null) {
-                log.error(msg + " : Reason- No matching instance found for domain: " +
-                        domainName + " and sub domain: "+subDomainName+
-                        ".");
-                return false;
-            }
-
-            // terminate it!
-            terminate(iaasTemp, nodeId);
-
-            return true;
-
-        }
-
-        log.info("Termination of an instance which is belong to domain '" + domainName +
-                 "' and sub domain '"+subDomainName+"' , failed!\n Reason: No matching instance found.");
-
-        return false;
-    }
-
-    @Override
-    public boolean terminateSpiInstance(String publicIp) {
-
-        // initialize the service, if it's not already initialized.
-        initAutoscaler(true);
-
-        // sort the IaasContext entities according to scale down order.
-        Collections.sort(iaasContextList,
-                         IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_DOWN_SORT)));
-
-        // traverse in scale down order
-        for (IaasContext iaasTemp : iaasContextList) {
-
-            String msg = "Failed to terminate an instance in " + iaasTemp.getName().toString() +
-                         "" +
-                         ". Hence, will try to terminate an instance in another IaaS if possible.";
-
-            // grab the node maps with the given public IP address
-            String nodeId = iaasTemp.getNodeWithPublicIp(publicIp);
-
-            if (nodeId == null) {
-                log.warn(msg + " : Reason- No matching instance found for public ip '" +
-                         publicIp +
-                         "'.");
-                continue;
-            }
-
-            // terminate it!
-            terminate(iaasTemp, nodeId);
-
-            return true;
-        }
-
-        log.info("Termination of an instance which has the public IP '" + publicIp + "', failed!");
-
-        return false;
-    }
-
-    @Override
-    public int getPendingInstanceCount(String domainName, String subDomain) {
-
-        // initialize the service, if it's not already initialized.
-        initAutoscaler(false);
-        
-        subDomain = checkSubDomain(subDomain);
-
-        int pendingInstanceCount = 0;
-
-        // traverse through IaasContexts
-        for (IaasContext entry : iaasContextList) {
-
-            ComputeService computeService = entry.getComputeService();
-
-            // get list of node Ids which are belong to the requested domain
-            List<String> nodeIds = entry.getNodeIds(domainName, subDomain);
-            
-            if(nodeIds.isEmpty()){
-                log.debug("Zero nodes spawned in the IaaS "+entry.getName()+
-                          " of domain: "+domainName+" and sub domain: "+subDomain);
-                continue;
-            }
-
-            // get all the nodes spawned by this IaasContext
-            Set<? extends ComputeMetadata> set = computeService.listNodes();
-
-            Iterator<? extends ComputeMetadata> iterator = set.iterator();
-
-            // traverse through all nodes of this ComputeService object
-            while (iterator.hasNext()) {
-                NodeMetadataImpl nodeMetadata = (NodeMetadataImpl) iterator.next();
-
-                // if this node belongs to the requested domain
-                if (nodeIds.contains(nodeMetadata.getId())) {
-
-                    // get the status of the node
-                    Status nodeStatus = nodeMetadata.getStatus();
-
-                    // count nodes that are in pending state
-                    if (nodeStatus.toString().equalsIgnoreCase("PENDING")) {
-                        pendingInstanceCount++;
-                    }
-                }
-
-            }
-        }
-
-        log.info("Pending instance count of domain '" + domainName + "' and sub domain '"+
-        subDomain+"' is " + pendingInstanceCount);
-
-        return pendingInstanceCount;
-
-    }
-
-    /**
-     * Returns matching IaasContext for the given {@link Iaases} entry.
-     */
-    private IaasContext findIaasContext(Enum<Iaases> iaas) {
-
-        for (IaasContext entry : iaasContextList) {
-            if (entry.getName().equals(iaas)) {
-                return entry;
-            }
-        }
-
-        return null;
-    }
-
-    /**
-     * Returns matching IaasContext for the given iaas type.
-     */
-    private IaasContext findIaasContext(String iaasType) {
-
-        for (IaasContext entry : iaasContextList) {
-            if (entry.getName().toString().equals(iaasType)) {
-                return entry;	
-            }
-        }
-
-        return null;
-    }
-
-    private void fillInScaleDownOrder() {
-
-        for (IaasProvider iaas : iaasProviders) {
-            if (findIaasContext(iaas.getType()) != null) {
-                findIaasContext(iaas.getType()).setScaleDownOrder(iaas.getScaleDownOrder());
-            }
-        }
-
-    }
-
-    private void fillInScaleUpOrder() {
-
-        for (IaasProvider iaas : iaasProviders) {
-            if (findIaasContext(iaas.getType()) != null) {
-                findIaasContext(iaas.getType()).setScaleUpOrder(iaas.getScaleUpOrder());
-            }
-        }
-
-    }
-
-    private byte[] getUserData(String payloadFileName, String tenantId) {
- 
-    	byte[] bytes = null;
-    	File outputFile = null;
-    	String tempfilename = UUID.randomUUID().toString();
-        try {
-            File file = new File(payloadFileName);
-            if (!file.exists()) {
-                handleException("Payload file " + payloadFileName + " does not exist");
-            }
-            if (!file.canRead()) {
-                handleException("Payload file " + payloadFileName + " does cannot be read");
-            }
-            if(tenantId != null) {
-            	// Tenant Id is available. This is an spi scenario. Edit the payload content
-            	editPayload(tenantId,file,tempfilename);
-            	outputFile = new File(CARBON_HOME + File.separator + AutoscalerConstant.RESOURCES_DIR + File.separator + tempfilename+".zip");
-            } else {
-            	outputFile = file;
-            }
-            bytes = getBytesFromFile(outputFile);
-
-        } catch (IOException e) {
-            handleException("Cannot read data from payload file " + payloadFileName, e);
-        }
-        
-        // Remove temporary payload file
-        if (tenantId != null) {
-            outputFile.delete();
-        }
-        
-        return bytes;
-    }
-
-    
-    private void editPayload(String tenantName, File file, String tempfileName) {
-		
-    	unzipFile(file, tempfileName);
-    	editContent(tenantName, file, tempfileName);
-    	zipPayloadFile(tempfileName);    	
-	}
-
-    
-    /**
-	 * unzips the payload file
-	 * 
-	 * @param file
-     * @param tempfileName 
-	 */
-	private void unzipFile(File file, String tempfileName) {
-		
-		int buffer = 2048;
-		BufferedOutputStream dest = null;
-		ZipInputStream zis = null;
-		
-		try {
-			FileInputStream fis = new FileInputStream(file);
-			zis = new ZipInputStream(new BufferedInputStream(fis));
-			ZipEntry entry;
-			
-			while ((entry = zis.getNextEntry()) != null) {
-
-				log.debug("Extracting: " + entry);
-				
-				int count;
-				byte data[] = new byte[buffer];
-				String outputFilename = tempfileName + File.separator + entry.getName();
-				createDirIfNeeded(tempfileName, entry);
-
-				// write the files to the disk
-				if (!entry.isDirectory()) {
-					FileOutputStream fos = new FileOutputStream(outputFilename);
-					dest = new BufferedOutputStream(fos, buffer);
-					while ((count = zis.read(data, 0, buffer)) != -1) {
-						dest.write(data, 0, count);
-					}
-					dest.flush();
-					dest.close();
-				}
-			}
-			
-		} catch (Exception e) {
-			log.error("Exception is occurred in unzipping payload file. Reason:" + e.getMessage());
-			throw new AutoscalerServiceException(e.getMessage(), e);
-		} finally {
-			closeStream(zis);			
-			closeStream(dest);
-		}
-	}
-
-
-	private void closeStream(Closeable stream) {
-		if (stream != null) {
-			try {
-				stream.close();
-			} catch (IOException e) {
-				log.error(" Exception is occurred when closing stream. Reason :" + e.getMessage());
-			}
-		}
-	}
-
-	/**
-	 * 
-	 * Modify contents (tenantName) of the debian_cron_script.sh file
-	 * 
-	 * @param tenantName
-	 * @param file
-	 */
-	private void editContent(String tenantName, File file, String tempfileName) {
-
-		File f = new File(CARBON_HOME + File.separator + tempfileName
-				+ File.separator + AutoscalerConstant.PAYLOAD_DIR + File.separator
-				+ AutoscalerConstant.PARAMS_FILE_NAME);
-
-		FileInputStream fs = null;
-		InputStreamReader in = null;
-		BufferedReader br = null;
-
-		StringBuffer sb = new StringBuffer();
-
-		String textinLine;
-
-		try {
-			fs = new FileInputStream(f);
-			in = new InputStreamReader(fs);
-			br = new BufferedReader(in);
-
-			while (true) {
-				
-				textinLine=br.readLine();
-	            if(textinLine==null)
-	                break;
-	            sb.append(editLine(textinLine, tenantName));
-			}
-		} catch (Exception e) {
-			log.error("Exception is occurred in editing payload content. Reason: "+e.getMessage());
-			throw new AutoscalerServiceException(e.getMessage(), e);
-		} finally {
-			closeStream(fs);
-			closeStream(in);
-			closeStream(br);
-		}
-
-		writeChangesBackToFile(f, sb);
-	}
-
-
-	private String editLine(String textinLine, String tenantName) {
-		
-		// Format of the line will be <IP>=<IPvalue>,<Path>=<PathValue>..
-		
-		StringBuffer outputBuffer = new StringBuffer();
-		Map<String, String> paramMap = new HashMap<String, String>();
-		String[] params = textinLine.split(AutoscalerConstant.ENTRY_SEPARATOR);
-
-		for (int i = 0; i < params.length; i++) {
-
-			// split the params one by one
-			String param = params[i];
-			String[] values = param.split(AutoscalerConstant.VALUE_SEPARATOR);
-			
-			if(values.length != 2) {
-				throw new AutoscalerServiceException("Incorrect format in parameters file");
-			}
-			
-			String key = values[0];
-			String value = values[1];
-
-			String updatedValue = value;
-
-			if (AutoscalerConstant.TENANT_KEY.equals(key)) {
-				updatedValue = tenantName;
-			} else if (AutoscalerConstant.APP_PATH_KEY.equals(key)) {
-				updatedValue = getAppPathForTenant(tenantName,value);
-			} 
-			paramMap.put(key, updatedValue);
-		}
-
-		// Loop through the map and put values into a string
-		reOrganizeContent(outputBuffer, paramMap);
-
-		// cleanup output buffer
-		if (outputBuffer.substring(0, 1).equals(AutoscalerConstant.ENTRY_SEPARATOR)) {
-			outputBuffer.delete(0, 1);
-		}
-
-		return outputBuffer.toString();
-	}
-
-
-	private void reOrganizeContent(StringBuffer outputBuffer, Map<String, String> paramMap) {
-		
-		for (Map.Entry<String, String> entry : paramMap.entrySet()) {
-			outputBuffer.append(AutoscalerConstant.ENTRY_SEPARATOR).append(entry.getKey()).append(AutoscalerConstant.VALUE_SEPARATOR)
-																		.append(entry.getValue());
-		}
-	}
-
-
-	private String getAppPathForTenant(String tenantName, String appPath) {
-		// Assumes app path is /opt/wso2-app/repository/
-		StringBuffer updatedAppPath = new StringBuffer();
-		if(tenantName.equals(AutoscalerConstant.SUPER_TENANT_ID)){ 
-			updatedAppPath.append(appPath).append("deployment").append(File.separator).append("server")
-															   .append(File.separator).append("phpapps");
-		}else{
-			updatedAppPath.append(appPath).append(tenantName).append(File.separator).append("phpapps");
-		}
-		return updatedAppPath.toString();
-	}
-
-
-	private void writeChangesBackToFile(File f, StringBuffer sb) {
-		FileWriter fstream = null;
-		BufferedWriter outobj = null;
-		
-		try {
-			fstream = new FileWriter(f);
-			outobj = new BufferedWriter(fstream);
-			outobj.write(sb.toString());
-		} catch (Exception e) {
-			throw new RuntimeException(e);
-		} finally {
-			closeStream(outobj);
-		}
-	}
-	
-	/**
-	 * 
-	 * Compress the modified files back into payload.zip
-	 * @param tempfileName 
-	 * 
-	 */
-	private void zipPayloadFile(String tempfileName) {
-		
-		int buffer = 2048;
-		BufferedInputStream origin = null;
-		ZipOutputStream out = null;
-		
-		try {
-	         
-	         FileOutputStream dest = new 
-	           FileOutputStream(CARBON_HOME + File.separator + AutoscalerConstant.RESOURCES_DIR + File.separator + tempfileName+".zip");
-	         out = new ZipOutputStream(new BufferedOutputStream(dest));
-	         byte data[] = new byte[buffer];
-	         
-	         File f = new File(CARBON_HOME + File.separator + tempfileName + File.separator + AutoscalerConstant.PAYLOAD_DIR);
-	         String files[] = f.list();
-
-	         for (int i=0; i<files.length; i++) {
-	            FileInputStream fi = new FileInputStream(CARBON_HOME + File.separator + tempfileName
-		 				+ File.separator + AutoscalerConstant.PAYLOAD_DIR + File.separator + files[i]);
-	            origin = new BufferedInputStream(fi, buffer);
-	            ZipEntry entry = new ZipEntry(AutoscalerConstant.PAYLOAD_DIR + File.separator + files[i]);
-	            out.putNextEntry(entry);
-	            
-	            int count;
-	            while((count = origin.read(data, 0, buffer)) != -1) {
-	               out.write(data, 0, count);
-	            }
-	            origin.close();
-	         }
-	         
-	         // delete temp files
-	         deleteDir(f);
-	         File fl = new File(CARBON_HOME + File.separator + tempfileName);
-	         fl.delete();
-	         
-	      } catch(Exception e) {
-	    	  log.error("Exception is occurred in zipping payload file after modification. Reason:" + e.getMessage());
-	    	  throw new AutoscalerServiceException(e.getMessage(),e);
-	      } finally {
-	    	  closeStream(origin);	    	  
-	    	  closeStream(out);
-	      }
-	}	
-
-	private static boolean deleteDir(File dir) {
-	    if (dir.isDirectory()) {
-	        String[] children = dir.list();
-	        for (int i=0; i<children.length; i++) {
-	            boolean success = deleteDir(new File(dir, children[i]));
-	            if (!success) {
-	                return false;
-	            }
-	        }
-	    }
-
-	    // The directory is now empty so delete it
-	    return dir.delete();
-	}
-
-	private void createDirIfNeeded(String destDirectory, ZipEntry entry) {
-		
-		String name = entry.getName();
-
-        if(name.contains("/"))
-        {
-            log.debug("directory will need to be created");
-
-            int index = name.lastIndexOf("/");
-            String dirSequence = name.substring(0, index);
-
-            File newDirs = new File(destDirectory + File.separator + dirSequence);
-
-            //create the directory
-            newDirs.mkdirs();
-        }
-		
-	}
-
-
-	/**
-     * Returns the contents of the file in a byte array
-     * 
-     * @param file
-     *            - Input File
-     * @return Bytes from the file
-     * @throws java.io.IOException
-     *             , if retrieving the file contents failed.
-     */
-    private byte[] getBytesFromFile(File file) throws IOException {
-        if (!file.exists()) {
-            log.error("Payload file " + file.getAbsolutePath() + " does not exist");
-            return null;
-        }
-        InputStream is = new FileInputStream(file);
-        byte[] bytes;
-
-        try {
-            // Get the size of the file
-            long length = file.length();
-
-            // You cannot create an array using a long type.
-            // It needs to be an int type.
-            // Before converting to an int type, check
-            // to ensure that file is not larger than Integer.MAX_VALUE.
-            if (length > Integer.MAX_VALUE) {
-                if (log.isDebugEnabled()) {
-                    log.debug("File is too large");
-                }
-            }
-
-            // Create the byte array to hold the data
-            bytes = new byte[(int) length];
-
-            // Read in the bytes
-            int offset = 0;
-            int numRead;
-            while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
-                offset += numRead;
-            }
-
-            // Ensure all the bytes have been read in
-            if (offset < bytes.length) {
-                throw new IOException("Could not completely read file " + file.getName());
-            }
-        } finally {
-            // Close the input stream and return bytes
-            is.close();
-        }
-
-        return bytes;
-    }
-
-    /**
-     * handles the exception
-     * 
-     * @param msg
-     *            exception message
-     */
-    private void handleException(String msg) {
-        log.error(msg);
-        throw new SynapseException(msg);
-    }
-
-    /**
-     * handles the exception
-     * 
-     * @param msg
-     *            exception message
-     * @param e
-     *            exception
-     */
-    private static void handleException(String msg, Exception e) {
-        log.error(msg, e);
-        throw new SynapseException(msg, e);
-    }
-
-
-    /**
-     * This will replace an existing entry in iaasEntities list, if there's such.
-     * If not this will add the replacement value to the list.
-     * 
-     * @param replacement
-     *            IaasContext entry to be added.
-     */
-    private void replaceIaasContext(IaasContext replacement) {
-        for (IaasContext entry : iaasContextList) {
-            if (entry.equals(replacement)) {
-                int idx = iaasContextList.indexOf(entry);
-                iaasContextList.remove(idx);
-                iaasContextList.add(idx, replacement);
-                return;
-            }
-        }
-        iaasContextList.add(replacement);
-
-    }
-
-    /**
-     * Builds the LXC Template object.
-     */
-    private void buildLXCTemplates(IaasContext entity, String imageId, boolean blockUntilRunning, String tenantId) {
-
-        if (entity.getComputeService() == null) {
-            throw new AutoscalerServiceException("Compute service is null for IaaS provider: " + entity.getName());
-        }
-
-//        // if domain to template map is null
-//        if (entity.getDomainToTemplateMap() == null) {
-//            // we initialize it
-//            entity.setDomainToTemplateMap(new HashMap<String, Template>());
-//        }
-
-        TemplateBuilder templateBuilder = entity.getComputeService().templateBuilder();
-        templateBuilder.imageId(imageId);
-
-        // to avoid creation of template objects in each and every time, we create all
-        // at once!
-        for (ServiceTemplate temp : serviceTemps) {
-
-            String instanceType;
-
-            // set instance type 
-            if (((instanceType = temp.getProperty("instanceType." + Iaases.openstack.toString())) != null) ) {
-
-                templateBuilder.hardwareId(instanceType);
-            }
-
-            Template template = templateBuilder.build();
-
-            template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
-
-            template.getOptions()
-                    .as(NovaTemplateOptions.class)
-                    .securityGroupNames(temp.getProperty("securityGroups").split(AutoscalerConstant.ENTRY_SEPARATOR));
-
-            if (temp.getProperty(AutoscalerConstant.PAYLOAD_DIR) != null) {
-                template.getOptions()
-                        .as(NovaTemplateOptions.class)
-                        .userData(getUserData(CARBON_HOME + File.separator +
-                                              temp.getProperty(AutoscalerConstant.PAYLOAD_DIR), tenantId));
-            }
-
-            template.getOptions()
-                    .as(NovaTemplateOptions.class)
-                    .keyPairName(temp.getProperty("keyPair"));
-
-            // add to the data structure
-            if (entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()) == null) {
-                entity.addInstanceContext(new InstanceContext(temp.getDomainName(),
-                                                              temp.getSubDomainName(), template));
-            }
-            else{
-                entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()).setTemplate(template);
-            }
-
-        }
-
-        // since we modified the Context, we need to replace
-        replaceIaasContext(entity);
-    }
-
-    /**
-     * Builds EC2 Template object
-     * 
-     */
-    private void buildEC2Templates(IaasContext entity, String imageId, boolean blockUntilRunning) {
-
-        if (entity.getComputeService() == null) {
-            throw new AutoscalerServiceException("Compute service is null for IaaS provider: " + entity.getName());
-        }
-
-//        // if domain to template map is null
-//        if (entity.getDomainToTemplateMap() == null) {
-//            // we initialize it
-//            entity.setDomainToTemplateMap(new HashMap<String, Template>());
-//        }
-
-        TemplateBuilder templateBuilder = entity.getComputeService().templateBuilder();
-
-        // set image id specified
-        templateBuilder.imageId(imageId);
-
-        // to avoid creation of template objects in each and every time, we create all
-        // at once! FIXME we could use caching and lazy loading
-        for (ServiceTemplate temp : serviceTemps) {
-
-            if (temp.getProperty("instanceType." + Iaases.ec2.toString()) != null) {
-                // set instance type eg: m1.large
-                templateBuilder.hardwareId(temp.getProperty("instanceType." + Iaases.ec2.toString()));
-            }
-
-            // build the Template
-            Template template = templateBuilder.build();
-
-            // make it non blocking
-            template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
-
-            // set EC2 specific options
-            template.getOptions()
-                    .as(AWSEC2TemplateOptions.class)
-                    .placementGroup(temp.getProperty("availabilityZone"));
-
-            template.getOptions()
-                    .as(AWSEC2TemplateOptions.class)
-                    .securityGroups(temp.getProperty("securityGroups").split(AutoscalerConstant.ENTRY_SEPARATOR));
-
-            if (temp.getProperty(AutoscalerConstant.PAYLOAD_DIR) != null) {
-                template.getOptions()
-                        .as(AWSEC2TemplateOptions.class)
-                        .userData(getUserData(CARBON_HOME + File.separator +
-                                              temp.getProperty(AutoscalerConstant.PAYLOAD_DIR), null));
-            }
-
-            template.getOptions()
-                    .as(AWSEC2TemplateOptions.class)
-                    .keyPair(temp.getProperty("keyPair"));
-
-            // add to the data structure
-            if (entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()) == null) {
-                entity.addInstanceContext(new InstanceContext(temp.getDomainName(),
-                                                              temp.getSubDomainName(), template));
-            }
-            else{
-                entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()).setTemplate(template);
-            }
-
-        }
-
-        // since we modified the Context, we need to replace
-        replaceIaasContext(entity);
-
-    }
-
-    private String print(Iaases[] values) {
-        String str = "";
-        for (Iaases iaases : values) {
-            str = iaases.name() + ", ";
-        }
-        str = str.trim();
-        return str.endsWith(AutoscalerConstant.ENTRY_SEPARATOR) ? str.substring(0, str.length() - 1) : str;
-    }
-
-    @SuppressWarnings("unchecked")
-    private void deserialize() {
-
-        String path;
-
-        try {
-            path = serializationDir + File.separator +
-                   AutoscalerConstant.IAAS_CONTEXT_LIST_SERIALIZING_FILE;
-
-            Object obj = Deserializer.deserialize(path);
-            if (obj != null) {
-                iaasContextList = (List<IaasContext>) obj;
-                log.debug("Deserialization was successful from file: " + path);
-            }
-
-            path = serializationDir + File.separator +
-                   AutoscalerConstant.LASTLY_USED_IAAS_MAP_SERIALIZING_FILE;
-
-            obj = Deserializer.deserialize(path);
-
-            if (obj != null) {
-                lastlyUsedIaasMap = (Map<String, Map<String, String>>) obj;
-                log.debug("Deserialization was successful from file: " + path);
-            }
-
-        } catch (Exception e) {
-            String msg = "Deserialization of objects failed!";
-            log.fatal(msg, e);
-            throw new DeserializationException(msg, e);
-        }
-
-    }
-
-    /**
-     * Does all the serialization stuff!
-     */
-    private void serialize() {
-
-        try {
-            Serializer.serialize(iaasContextList,
-                                 serializationDir + File.separator +
-                                         AutoscalerConstant.IAAS_CONTEXT_LIST_SERIALIZING_FILE);
-
-            Serializer.serialize(lastlyUsedIaasMap,
-                                 serializationDir + File.separator +
-                                         AutoscalerConstant.LASTLY_USED_IAAS_MAP_SERIALIZING_FILE);
-
-        } catch (IOException e) {
-            String msg = "Serialization of objects failed!";
-            log.fatal(msg, e);
-            throw new SerializationException(msg, e);
-        }
-    }
-
-    /**
-     * A helper method to terminate an instance.
-     */
-    private void terminate(IaasContext iaasTemp, String nodeId) {
-
-        // this is just to be safe
-        if (iaasTemp.getComputeService() == null) {
-            String msg = "Unexpeced error occured! IaasContext's ComputeService is null!";
-            log.error(msg);
-            throw new AutoscalerServiceException(msg);
-        }
-
-        // destroy the node
-        iaasTemp.getComputeService().destroyNode(nodeId);
-
-        // remove the node id from the Context
-        iaasTemp.removeNodeId(nodeId);
-
-        // replace this IaasContext instance, as it reflects the new changes.
-        replaceIaasContext(iaasTemp);
-
-        // serialize the objects
-        serialize();
-
-        log.info("Node with Id: '" + nodeId + "' is terminated!");
-    }
-
-    /**
-     * Comparator to compare IaasContexts on different attributes.
-     */
-    public enum IaasContextComparator implements Comparator<IaasContext> {
-        SCALE_UP_SORT {
-            public int compare(IaasContext o1, IaasContext o2) {
-                return Integer.valueOf(o1.getScaleUpOrder()).compareTo(o2.getScaleUpOrder());
-            }
-        },
-        SCALE_DOWN_SORT {
-            public int compare(IaasContext o1, IaasContext o2) {
-                return Integer.valueOf(o1.getScaleDownOrder()).compareTo(o2.getScaleDownOrder());
-            }
-        };
-
-        public static Comparator<IaasContext> ascending(final Comparator<IaasContext> other) {
-            return new Comparator<IaasContext>() {
-                public int compare(IaasContext o1, IaasContext o2) {
-                    return other.compare(o1, o2);
-                }
-            };
-        }
-
-        public static Comparator<IaasContext>
-                getComparator(final IaasContextComparator... multipleOptions) {
-            return new Comparator<IaasContext>() {
-                public int compare(IaasContext o1, IaasContext o2) {
-                    for (IaasContextComparator option : multipleOptions) {
-                        int result = option.compare(o1, o2);
-                        if (result != 0) {
-                            return result;
-                        }
-                    }
-                    return 0;
-                }
-            };
-        }
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/internal/AutoscalerServiceDSComponent.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/internal/AutoscalerServiceDSComponent.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/internal/AutoscalerServiceDSComponent.java
deleted file mode 100644
index 71df23c..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/internal/AutoscalerServiceDSComponent.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.autoscaler.service.internal;
-
-import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.component.ComponentContext;
-import org.apache.stratos.autoscaler.service.IAutoscalerService;
-
-/**
- * Registering Autoscaler Service.
- * @scr.component name="org.apache.stratos.autoscaler.service" immediate="true"
- */
-public class AutoscalerServiceDSComponent {
-
-    private static final Log log = LogFactory.getLog(AutoscalerServiceDSComponent.class);
-
-    protected void activate(ComponentContext context) {
-        try {
-            BundleContext bundleContext = context.getBundleContext();
-            bundleContext.registerService(IAutoscalerService.class.getName(),
-                                          new AutoscalerServiceImpl(), null);
-
-            log.debug("******* Autoscaler Service bundle is activated ******* ");
-        } catch (Exception e) {
-            log.error("******* Autoscaler Service bundle is failed to activate ****", e);
-        }
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/io/Deserializer.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/io/Deserializer.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/io/Deserializer.java
deleted file mode 100644
index 8732094..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/io/Deserializer.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.io;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class Deserializer {
-    
-    private static final Log log = LogFactory.getLog(Deserializer.class);
-
-    /**
-     * We deserialize only if the path to the serialized object file is exists.
-     * @param filePath path to the serialized object file
-     * @return the object obtained after deserialization or null if file isn't valid.
-     * @throws Exception
-     */
-    public static Object deserialize(String filePath) throws Exception {
-
-        ObjectInputStream objIn = null; 
-        Object obj = null;
-        
-        if(!new File(filePath).isFile()){
-            return obj;
-        }
-        
-        try {
-
-            objIn = new ObjectInputStream(new FileInputStream(filePath));
-            obj = objIn.readObject();
-
-        } catch (IOException e) {
-            log.error("Failed to deserialize the file at "+filePath , e);
-            throw e;
-            
-        } catch (ClassNotFoundException e) {
-            log.error("Failed to deserialize the file at "+filePath , e);
-            throw e;
-            
-        } finally{
-            objIn.close();
-        }
-        
-        return obj;
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/io/Serializer.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/io/Serializer.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/io/Serializer.java
deleted file mode 100644
index 16f27c4..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/io/Serializer.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.io;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class Serializer {
-    
-    private static final Log log = LogFactory.getLog(Serializer.class);
-
-    public static void serialize(Object serializableObj, String filePath) throws IOException {
-
-        File outFile = new File(filePath);
-        ObjectOutput ObjOut = null;
-        
-        try {
-
-            if(outFile.createNewFile()){
-                log.debug("Serialization file is created at "+filePath);
-            } else{
-                log.debug("Serialization file is already existing at "+filePath);
-            }
-            
-            ObjOut = new ObjectOutputStream(new FileOutputStream(outFile));
-            ObjOut.writeObject(serializableObj);
-
-        } catch (IOException e) {
-            log.error("Failed to serialize the object "+serializableObj.toString()
-                      + " to file "+filePath , e);
-            throw e;
-            
-        } finally{
-            ObjOut.close();
-        }
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/jcloud/ComputeServiceBuilder.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/jcloud/ComputeServiceBuilder.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/jcloud/ComputeServiceBuilder.java
deleted file mode 100644
index b8d5615..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/jcloud/ComputeServiceBuilder.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.jcloud;
-
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.stratos.autoscaler.service.util.IaasProvider;
-import org.jclouds.ContextBuilder;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.ComputeServiceContext;
-import org.jclouds.enterprise.config.EnterpriseConfigurationModule;
-import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
-import org.jclouds.sshj.config.SshjSshClientModule;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.inject.Module;
-
-/**
- * This class is responsible for creating a JClouds specific ComputeService object instances.
- */
-public class ComputeServiceBuilder {
-    
-    public static ComputeService buildComputeService(IaasProvider iaas) {
-
-        Properties properties = new Properties();
-
-        // load properties
-        for (Map.Entry<String, String> entry : iaas.getProperties().entrySet()) {
-            properties.put(entry.getKey(), entry.getValue());
-        }
-
-        // set modules
-        Iterable<Module> modules =
-            ImmutableSet.<Module> of(new SshjSshClientModule(), new SLF4JLoggingModule(),
-                                     new EnterpriseConfigurationModule());
-
-        // build context
-        ContextBuilder builder =
-            ContextBuilder.newBuilder(iaas.getProvider())
-                          .credentials(iaas.getIdentity(), iaas.getCredential()).modules(modules)
-                          .overrides(properties);
-
-        // return the compute service object
-        return builder.buildView(ComputeServiceContext.class).getComputeService();
-    }
-    
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/AutoscalerConstant.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/AutoscalerConstant.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/AutoscalerConstant.java
deleted file mode 100644
index ba07a0b..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/AutoscalerConstant.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.util;
-
-public final class AutoscalerConstant {
-
-    /**
-     * elastic-scaler-config XML file's elements
-     */
-    public static final String SERIALIZATION_DIR_ELEMENT = "serializationDir";
-    public static final String IAAS_PROVIDER_ELEMENT = "iaasProvider";
-    public static final String IAAS_PROVIDER_TYPE_ATTR = "type";
-    public static final String IAAS_PROVIDER_NAME_ATTR = "name";
-    public static final String PROPERTY_ELEMENT = "property";
-    public static final String PROPERTY_NAME_ATTR= "name";
-    public static final String PROPERTY_VALUE_ATTR = "value";
-    public static final String IMAGE_ID_ELEMENT = "imageId";
-    public static final String SCALE_DOWN_ORDER_ELEMENT = "scaleDownOrder";
-    public static final String SCALE_UP_ORDER_ELEMENT = "scaleUpOrder";
-    public static final String PROVIDER_ELEMENT = "provider";
-    public static final String IDENTITY_ELEMENT = "identity";
-    public static final String CREDENTIAL_ELEMENT = "credential";
-    public static final String DEFAULT_SERVICE_ELEMENT = "default";
-    public static final String SERVICE_ELEMENT = "service";
-    public static final String SERVICE_DOMAIN_ATTR = "domain";
-    public static final String SERVICE_SUB_DOMAIN_ATTR = "subDomain";
-    
-    /**
-     * Secret Manager related aliases.
-     */
-    public static final String EC2_IDENTITY_ALIAS = "elastic.scaler.ec2.identity";
-    public static final String EC2_CREDENTIAL_ALIAS = "elastic.scaler.ec2.credential";
-    public static final String OPENSTACK_IDENTITY_ALIAS = "elastic.scaler.openstack.identity";
-    public static final String OPENSTACK_CREDENTIAL_ALIAS = "elastic.scaler.openstack.credential";
-    
-    /**
-     * Serializer related constants
-     */
-    public static final String IAAS_CONTEXT_LIST_SERIALIZING_FILE = "iaas-context-list.txt";
-    public static final String LASTLY_USED_IAAS_MAP_SERIALIZING_FILE = "lastly-used-iaas.txt";
-    
-    /**
-     * Payload related constants
-     */
-    public static final String PAYLOAD_DIR = "payload";
-    public static final String PARAMS_FILE_NAME = "launch-params";
-    public static final String RESOURCES_DIR = "resources";
-    public static final String VALUE_SEPARATOR = "=";
-    public static final String ENTRY_SEPARATOR = ",";
-    public static final String APP_PATH_KEY = "APP_PATH";
-    public static final String TENANT_KEY = "TENANT";
-    
-    /**
-	 * Super tenant id
-	 */
-    public static final String SUPER_TENANT_ID = "-1234";
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/IaasContext.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/IaasContext.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/IaasContext.java
deleted file mode 100644
index 82f5473..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/IaasContext.java
+++ /dev/null
@@ -1,391 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.util;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-
-import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl;
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.jclouds.compute.ComputeService;
-import org.jclouds.compute.domain.Template;
-
-/**
- * This object holds all IaaS related runtime data.
- */
-public class IaasContext implements Serializable{
-   
-    private static final long serialVersionUID = -922284976926131383L;
-    
-    // name of the IaaS
-    private Enum<AutoscalerServiceImpl.Iaases> name;
-    
-    /* We keep following maps in order to make the look up time, low.*/
-    
-    /**
-     * Key - domain
-     * Value - is another map
-     *          key - sub domain
-     *          value - <code>InstanceContext</code>
-     */
-    private Map<String, Map<String, InstanceContext>> instanceCtxts;
-    
-    /**
-     * Key - public IP
-     * Value - <code>InstanceContext</code>
-     */
-    private Map<String, InstanceContext> publicIpToInstanceCtxt;
-    
-    /**
-     * Key - node id 
-     * Value - <code>InstanceContext</code>
-     */
-    private Map<String, InstanceContext> nodeIdToInstanceCtxt;
-    
-    
-//    private transient Map<String, Template> domainToTemplateMap;
-    private transient ComputeService computeService;
-    
-    // Since Jclouds' NodeMetadata object contains unserializable objects, I had to use 3 maps.
-//    private Map<String, String> nodeIdToDomainMap = new LinkedHashMap<String, String>();
-//    private Map<String, String> publicIpToDomainMap = new LinkedHashMap<String, String>();
-//    private Map<String, String> publicIpToNodeIdMap = new LinkedHashMap<String, String>();
-    
-    private int scaleUpOrder, scaleDownOrder;
-
-    public IaasContext(Enum<AutoscalerServiceImpl.Iaases> name, ComputeService computeService) {
-        this.name = name;
-        this.computeService = computeService;
-        instanceCtxts = new LinkedHashMap<String, Map<String,InstanceContext>>();
-        publicIpToInstanceCtxt = new LinkedHashMap<String, InstanceContext>();
-        nodeIdToInstanceCtxt = new LinkedHashMap<String, InstanceContext>();
-    }
-
-    public Enum<AutoscalerServiceImpl.Iaases> getName() {
-        return name;
-    }
-    
-    public void addInstanceContext(InstanceContext ctx) {
-        
-        if(ctx == null){
-            return;
-        }
-        
-        String domain = ctx.getDomain();
-        String subDomain = ctx.getSubDomain();
-        
-        if(domain != null && subDomain != null){
-            addToInstanceCtxts(domain, subDomain, ctx);
-        }
-        
-    }
-    
-    public void addNodeDetails(String domain, String subDomain, String nodeId, String ip) {
-        
-        if(getInstanceContext(domain, subDomain) != null){
-            getInstanceContext(domain, subDomain).addNode(nodeId, ip);
-            
-            nodeIdToInstanceCtxt.put(nodeId, getInstanceContext(domain, subDomain));
-            publicIpToInstanceCtxt.put(ip, getInstanceContext(domain, subDomain));
-        }
-    }
-    
-    private void addToInstanceCtxts(String domainName, String subDomainName, InstanceContext ctx) {
-
-        Map<String, InstanceContext> map;
-        
-        if(instanceCtxts.get(domainName) == null){
-            map = new HashMap<String, InstanceContext>();
-            
-        } else{
-            map = instanceCtxts.get(domainName);
-        }
-        
-        map.put(subDomainName, ctx);
-        instanceCtxts.put(domainName, map);
-        
-    }
-
-//    public void addToDomainToTemplateMap(String key, Template value) {
-//        domainToTemplateMap.put(key, value);
-//    }
-
-    public Template getTemplate(String domain, String subDomain) {
-        if(getInstanceContext(domain, subDomain) == null){
-            return null;
-        }
-        return getInstanceContext(domain, subDomain).getTemplate();
-    }
-    
-    public InstanceContext getInstanceContext(String domain, String subDomain) {
-        if (instanceCtxts.get(domain) != null) {
-            return instanceCtxts.get(domain).get(subDomain);
-        }
-        return null;
-    }
-
-    public ComputeService getComputeService() {
-        return computeService;
-    }
-    
-    public void setComputeService(ComputeService computeService) {
-        this.computeService = computeService;
-    }
-
-//    public void addNodeIdToDomainMap(String nodeId, String domain) {
-//        nodeIdToDomainMap.put(nodeId, domain);
-//    }
-//    
-//    public void addPublicIpToDomainMap(String ip, String domain) {
-//        publicIpToDomainMap.put(ip, domain);
-//    }
-//    
-//    public void addPublicIpToNodeIdMap(String ip, String nodeId) {
-//        publicIpToNodeIdMap.put(ip, nodeId);
-//    }
-
-    /**
-     * This will return the node id of the node which is belong to the
-     * requesting domain, sub domain and which is the most recently created. If it cannot find a
-     * matching node id, this will return <code>null</code>.
-     * @param domain service domain.
-     * @param subDomain service sub domain. 
-     * @return the node Id of the node
-     */
-    public String getLastMatchingNode(String domain, String subDomain) {
-        
-        InstanceContext ctx = getInstanceContext(domain, subDomain);
-        
-        if(ctx == null){
-            return null;
-        }
-        
-        // iterate in reverse order
-        ListIterator<String> iter =
-            new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
-                                listIterator(ctx.getNodeIdToIpMap().size());
-
-        if (iter.hasPrevious()) {
-            return iter.previous();
-        }
-        
-        return null;
-    }
-    
-    /**
-     * This will return the public IP of the node which is belong to the
-     * requesting domain, sub domain and which is the most recently created. If it cannot find a
-     * matching public IP, this will return <code>null</code>.
-     * @param domain service domain. 
-     * @param subDomain service sub domain. 
-     * @return the public IP of the node
-     */
-    public String getLastMatchingPublicIp(String domain, String subDomain) {
-        
-        InstanceContext ctx = getInstanceContext(domain, subDomain);
-        
-        if(ctx == null){
-            return null;
-        }
-        
-        // iterate in reverse order
-        ListIterator<String> iter =
-            new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
-                                listIterator(ctx.getNodeIdToIpMap().size());
-
-        while (iter.hasPrevious()) {
-            return ctx.getNodeIdToIpMap().get(iter.previous());
-        }
-        
-        return null;
-        
-//        // traverse from the last entry of the map
-//        ListIterator<Map.Entry<String, String>> iter =
-//            new ArrayList<Entry<String, String>>(publicIpToDomainMap.entrySet()).
-//                                listIterator(publicIpToDomainMap.size());
-//
-//        while (iter.hasPrevious()) {
-//            Map.Entry<String, String> entry = iter.previous();
-//            if (entry.getValue().equals(domain)) {
-//                return entry.getKey();
-//            }
-//        }
-//        
-//        return null;
-    }
-
-    /**
-     * This will return the node id of the node which is belong to the
-     * requesting domain, sub domain and which is created at first. If it cannot find a
-     * matching node id, this will return <code>null</code>.
-     * @param domain service domain.
-     * @param subDomain service sub domain.
-     * @return node id of the node
-     */
-    public String getFirstMatchingNode(String domain, String subDomain) {
-        
-        InstanceContext ctx = getInstanceContext(domain, subDomain);
-        
-        if(ctx == null){
-            return null;
-        }
-        
-        // iterate in added order
-        ListIterator<String> iter =
-            new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
-                                listIterator(0);
-
-        while (iter.hasNext()) {
-            return iter.next();
-        }
-        
-        return null;
-        
-//        for (Entry<String, String> entry : nodeIdToDomainMap.entrySet()) {
-//            if (entry.getValue().equals(domain)) {
-//                return entry.getKey();
-//            }
-//        }
-//        return null;
-    }
-
-    /**
-     * This will return the node id of the node which has the given public IP. 
-     * If it cannot find a matching node id, this will return 
-     * <code>null</code>.
-     * @param publicIp public IP of a node.
-     * @return node id of the matching node.
-     */
-    public String getNodeWithPublicIp(String publicIp) {
-
-        InstanceContext ctx;
-
-        for (String ip : publicIpToInstanceCtxt.keySet()) {
-
-            if (ip.equals(publicIp)) {
-
-                ctx = publicIpToInstanceCtxt.get(ip);
-
-                for (String nodeId : nodeIdToInstanceCtxt.keySet()) {
-                    if (ctx.equals(nodeIdToInstanceCtxt.get(nodeId))) {
-                        return nodeId;
-                    }
-                }
-            }
-        }
-
-        return null;
-    }
-
-    /**
-     * This will return a list of node Ids that are started in this IaaS and that are 
-     * belong to the given domain, sub domain.
-     * @param domain service domain.
-     * @param subDomain service sub domain.
-     * @return List of node Ids.
-     */
-    public List<String> getNodeIds(String domain, String subDomain) {
-        
-        InstanceContext ctx = getInstanceContext(domain, subDomain);
-        
-        if(ctx == null){
-            return new ArrayList<String>();
-        }
-        
-        return new ArrayList<String>(ctx.getNodeIdToIpMap().keySet());
-        
-
-//        List<String> nodeIds = new ArrayList<String>();
-//
-//        for (Entry<String, String> entry : nodeIdToDomainMap.entrySet()) {
-//            if (entry.getValue().equals(domain)) {
-//                nodeIds.add(entry.getKey());
-//            }
-//        }
-//
-//        return nodeIds;
-    }
-
-    /**
-     * Removes a specific node id and related entries.
-     * @param node id of the node to be removed.
-     */
-    public void removeNodeId(String nodeId) {
-        
-        InstanceContext ctx;
-        
-        if(nodeIdToInstanceCtxt.containsKey(nodeId)){
-            // remove from node id map
-            ctx = nodeIdToInstanceCtxt.remove(nodeId);
-            
-            // remove from public ip map
-            publicIpToInstanceCtxt.remove(ctx.getNodeIdToIpMap().get(nodeId));
-            
-            // remove from main map
-            instanceCtxts.get(ctx.getDomain()).get(ctx.getSubDomain()).removeNode(nodeId);
-            
-        }
-    }
-
-    public boolean equals(Object obj) {
-
-        if (obj instanceof IaasContext) {
-            return new EqualsBuilder().append(getName(), ((IaasContext) obj).getName()).isEquals();
-        }
-        return false;
-
-    }
-    
-    public int hashCode() {
-        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
-        append(name).
-        toHashCode();
-    }
-
-    public int getScaleDownOrder() {
-        return scaleDownOrder;
-    }
-
-    public void setScaleDownOrder(int scaleDownOrder) {
-        this.scaleDownOrder = scaleDownOrder;
-    }
-
-    public int getScaleUpOrder() {
-        return scaleUpOrder;
-    }
-
-    public void setScaleUpOrder(int scaleUpOrder) {
-        this.scaleUpOrder = scaleUpOrder;
-    }
-    
-//    public void setDomainToTemplateMap(Map<String, Template> map) {
-//        domainToTemplateMap = map;
-//    }
-//    
-//    public Map<String, Template> getDomainToTemplateMap() {
-//        return domainToTemplateMap;
-//    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/IaasProvider.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/IaasProvider.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/IaasProvider.java
deleted file mode 100644
index aa123ac..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/IaasProvider.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.util;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * This is the basic data structure which holds an IaaS specific details.
- */
-public class IaasProvider {
-    
-    /**
-     * Unique id to identify this IaaS provider.
-     */
-    private String type;
-    
-    /**
-     * human description of this IaaS provider
-     */
-    private String name;
-    
-    /**
-     * Property map for this IaaS provider.
-     */
-    private Map<String, String> properties = new HashMap<String, String>();
-    
-    /**
-     * Image identifier.
-     */
-    private String template;
-    
-    /**
-     * Scale up order and scale down order of the IaaS.
-     */
-    private int scaleUpOrder, scaleDownOrder;
-    
-    private String provider, identity, credential;
-    
-//    public enum SortParameter {
-//        SCALE_UP, SCALE_DOWN
-//    }
-
-    
-    public String getType() {
-        return type;
-    }
-
-    public void setType(String id) {
-        this.type = id;
-    }
-
-    public Map<String, String> getProperties() {
-        return properties;
-    }
-    
-    public void setProperty(String key, String value) {
-        
-        if(key != null && value != null){
-            properties.put(key, value);
-        }
-    }
-
-    public void setProperties(Map<String, String> properties) {
-        this.properties = properties;
-    }
-
-    public String getTemplate() {
-        return template;
-    }
-
-    public void setTemplate(String template) {
-        this.template = template;
-    }
-
-    public int getScaleUpOrder() {
-        return scaleUpOrder;
-    }
-
-    public void setScaleUpOrder(int scaleUpOrder) {
-        this.scaleUpOrder = scaleUpOrder;
-    }
-
-    public int getScaleDownOrder() {
-        return scaleDownOrder;
-    }
-
-    public void setScaleDownOrder(int scaleDownOrder) {
-        this.scaleDownOrder = scaleDownOrder;
-    }
-
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getProvider() {
-        return provider;
-    }
-
-    public void setProvider(String provider) {
-        this.provider = provider;
-    }
-
-    public String getIdentity() {
-        return identity;
-    }
-
-    public void setIdentity(String identity) {
-        this.identity = identity;
-    }
-
-    public String getCredential() {
-        return credential;
-    }
-
-    public void setCredential(String credential) {
-        this.credential = credential;
-    }
-
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/InstanceContext.java
----------------------------------------------------------------------
diff --git a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/InstanceContext.java b/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/InstanceContext.java
deleted file mode 100644
index a1544bf..0000000
--- a/components/autoscaler-service/org.apache.stratos.autoscaler.service/4.1.0/src/main/java/org/apache/stratos/autoscaler/service/util/InstanceContext.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.autoscaler.service.util;
-
-import java.io.Serializable;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-import org.jclouds.compute.domain.Template;
-
-/**
- * This will hold the run-time data related to an instance.
- * Instance can be an EC2 one, Openstack one etc.
- */
-public class InstanceContext implements Serializable {
-
-    private static final long serialVersionUID = -2604902942512629140L;
-    private String domain;
-    private String subDomain;
-    private transient Template template;
-
-    /**
-     * Key - node Id
-     * Value - IP
-     */
-    private Map<String, String> nodeIdToIpMap;
-    
-    public InstanceContext(String domain, String subDomain, Template temp) {
-        this.domain = domain;
-        this.subDomain = subDomain;
-        this.template = temp;
-        nodeIdToIpMap = new LinkedHashMap<String, String>();
-    }
-//    
-//    public InstanceContext(String domain, String subDomain, Template temp, String nodeId, String publicIp) {
-//        this.domain = domain;
-//        this.subDomain = subDomain;
-//        this.template = temp;
-//        this.nodeId = nodeId;
-//        this.publicIp = publicIp;
-//    }
-
-    
-    public String getDomain() {
-        return domain;
-    }
-
-    public String getSubDomain() {
-        return subDomain;
-    }
-    
-    public Template getTemplate() {
-        return template;
-    }
-    
-    public void setTemplate(Template temp) {
-        this.template = temp;
-    }
-    
-    public void addNode(String nodeId, String ip) {
-        if("".equals(ip)){
-            ip = null;
-        }
-        nodeIdToIpMap.put(nodeId, ip);
-    }
-    
-    public void removeNode(String nodeId) {
-        nodeIdToIpMap.remove(nodeId);
-    }
-
-
-    public Map<String, String> getNodeIdToIpMap() {
-        return nodeIdToIpMap;
-    }
-
-    
-}


[09/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
new file mode 100644
index 0000000..3cf1c85
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
@@ -0,0 +1,148 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.state.check;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class PendingInstancesStateChecker implements Runnable {
+    
+    private static final Log log = LogFactory.getLog(PendingInstancesStateChecker.class);
+    private LoadBalancerContext groupCtxt = null;
+    private String domain;
+    private String subDomain;
+    private int expectedIncrementOfinstanceCount, originalRunningInstanceCount;
+    private CloudControllerClient ccClient;
+    
+    public PendingInstancesStateChecker(LoadBalancerContext ctxt, String aDomain, String aSubDomain,
+            int anexpectedInstanceCount, int currentCount, CloudControllerClient client) {
+        groupCtxt = ctxt;
+        domain = aDomain;
+        subDomain = aSubDomain;
+        expectedIncrementOfinstanceCount = anexpectedInstanceCount;
+        originalRunningInstanceCount = currentCount;
+        ccClient = client;
+    }
+
+    @Override
+    public void run() {
+
+        if (groupCtxt != null) {
+
+            int totalWaitedTime = 0;
+            int serverStartupDelay = AutoscalerTaskDSHolder
+                .getInstance()
+                .getWholeLoadBalancerConfig()
+                .getLoadBalancerConfig()
+                .getServerStartupDelay();
+
+            log.debug("Pending Instances State Checker has started for: " +
+                AutoscaleUtil.domainSubDomainString(domain, subDomain) + ". Check expiry time : " + serverStartupDelay);
+
+            // for each sub domain, get the clustering group management agent
+            GroupManagementAgent agent =
+                AutoscalerTaskDSHolder.getInstance().getAgent()
+                    .getGroupManagementAgent(domain,
+                        subDomain);
+            int startingRunningInstanceCount = agent.getMembers().size();
+
+            // we give some time for the server to get joined, we'll check time to time
+            // whether the instance has actually joined the ELB.
+            while ((agent.getMembers().size() < (originalRunningInstanceCount + expectedIncrementOfinstanceCount)) &&
+                totalWaitedTime < serverStartupDelay) {
+                int upToDateRunningInstanceCount = agent.getMembers().size();
+
+                log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+                    " - Number of current running instances " +
+                        upToDateRunningInstanceCount);
+
+                if (upToDateRunningInstanceCount > startingRunningInstanceCount) {
+                    int newlyJoinedInstanceCount = upToDateRunningInstanceCount - startingRunningInstanceCount;
+                    // set new running instance count
+                    groupCtxt.setRunningInstanceCount(upToDateRunningInstanceCount);
+                    // decrement the pending instance count
+                    groupCtxt.decrementPendingInstancesIfNotZero(newlyJoinedInstanceCount);
+                    // update the starting running instance count
+                    startingRunningInstanceCount = upToDateRunningInstanceCount;
+
+                    log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+                        " - Instances newly joined: " +
+                            newlyJoinedInstanceCount);
+                }
+
+                try {
+                    Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
+                } catch (InterruptedException ignore) {
+                }
+
+                totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
+            }
+
+            log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) + "- Waited for : " +
+                totalWaitedTime +
+                " (milliseconds) till pending members get joined.");
+
+            if (agent.getMembers().size() < (originalRunningInstanceCount + expectedIncrementOfinstanceCount)) {
+
+                int instanceCountFailedToJoin =
+                    originalRunningInstanceCount + expectedIncrementOfinstanceCount - agent.getMembers().size();
+                log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+                    "Instances that are failed to join: " +
+                        instanceCountFailedToJoin);
+
+                // to avoid an infinite loop
+                int retries = instanceCountFailedToJoin + 2;
+
+                while (instanceCountFailedToJoin > 0 && retries > 0) {
+                    // instances spawned haven't joined ELB, so we assume that instance is
+                    // corrupted.
+                    // hence, we ask CC to terminate it.
+                    try {
+                        log.debug("Terminating lastly spwaned instance of " +
+                            AutoscaleUtil.domainSubDomainString(domain, subDomain));
+                        ccClient.terminateLastlySpawnedInstance(domain, subDomain);
+                        instanceCountFailedToJoin--;
+                        // decrement pending count
+                        groupCtxt.decrementPendingInstancesIfNotZero(1);
+                    } catch (Exception e) {
+                        log
+                            .error(
+                                "Instance termination failed for " +
+                                    AutoscaleUtil.domainSubDomainString(domain, subDomain),
+                                e);
+                    } finally {
+                        retries--;
+                    }
+                }
+
+                // decrement pending count
+                groupCtxt.decrementPendingInstancesIfNotZero(instanceCountFailedToJoin);
+            }
+
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
new file mode 100644
index 0000000..d135d22
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
@@ -0,0 +1,89 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.state.check;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class TerminatingInstancesStateChecker implements Runnable {
+    
+    private static final Log log = LogFactory.getLog(TerminatingInstancesStateChecker.class);
+    private LoadBalancerContext groupCtxt = null;
+    private String domain;
+    private String subDomain;
+    
+    public TerminatingInstancesStateChecker(LoadBalancerContext ctxt, String aDomain, String aSubDomain) {
+        groupCtxt = ctxt;
+        domain = aDomain;
+        subDomain = aSubDomain;
+    }
+
+    @Override
+    public void run() {
+
+        if (groupCtxt != null) {
+
+            groupCtxt.incrementTerminatingInstances(1);
+            
+            int totalWaitedTime = 0;
+            int serverStartupDelay = AutoscalerTaskDSHolder
+                .getInstance()
+                .getWholeLoadBalancerConfig()
+                .getLoadBalancerConfig()
+                .getServerStartupDelay();
+            log.info("Terminating Instances State Checker has started for: " +
+                AutoscaleUtil.domainSubDomainString(domain, subDomain) + ". Check expiry time : " + serverStartupDelay);
+
+            // for each sub domain, get the clustering group management agent
+            GroupManagementAgent agent =
+                AutoscalerTaskDSHolder.getInstance().getAgent()
+                    .getGroupManagementAgent(domain,
+                        subDomain);
+
+            int startingRunningInstanceCount = agent.getMembers().size();
+
+            // we give some time for the server to be terminated, we'll check time to time
+            // whether the instance has actually left the cluster.
+            while (agent.getMembers().size() == startingRunningInstanceCount &&
+                totalWaitedTime < serverStartupDelay) {
+
+                try {
+                    Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
+                } catch (InterruptedException ignore) {
+                }
+
+                totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
+            }
+
+            log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) + "- Waited for : " +
+                totalWaitedTime +
+                " (milliseconds) till terminating member left the cluster.");
+
+            // we recalculate number of alive instances
+            groupCtxt.decrementTerminatingInstancesIfNotZero(1);
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
new file mode 100644
index 0000000..a38fecd
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
@@ -0,0 +1,50 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.mediator.autoscale.lbautoscale.task;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.synapse.task.TaskConstants;
+import org.apache.synapse.task.TaskDescriptionRepository;
+import org.apache.synapse.task.TaskScheduler;
+import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver;
+
+public class AutoscalerTaskInitializer extends AbstractAxis2ConfigurationContextObserver {
+
+    public static final java.lang.String CARBON_TASK_SCHEDULER = "CARBON_TASK_SCHEDULER";
+    public static final java.lang.String CARBON_TASK_REPOSITORY = "CARBON_TASK_REPOSITORY";
+
+    public void createdConfigurationContext(ConfigurationContext configContext) {
+        TaskScheduler scheduler = (TaskScheduler)configContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER);
+        if (scheduler == null) {
+            scheduler = new TaskScheduler(TaskConstants.TASK_SCHEDULER);
+            scheduler.init(null);
+            configContext.setProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER, scheduler);
+        } else if(!scheduler.isInitialized()) {
+            scheduler.init(null);
+        }
+
+        if (configContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_REPOSITORY) == null) {
+            TaskDescriptionRepository repository = new TaskDescriptionRepository();
+            configContext.setProperty(
+                    AutoscalerTaskInitializer.CARBON_TASK_REPOSITORY, repository);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
new file mode 100644
index 0000000..5f83f7e
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
@@ -0,0 +1,348 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.task;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+import org.apache.axiom.om.util.AXIOMUtil;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskDescriptionFactory;
+import org.apache.synapse.task.TaskDescriptionSerializer;
+import org.apache.synapse.task.service.TaskManagementService;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.task.TaskManagementException;
+import org.wso2.carbon.task.TaskManager;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import java.util.*;
+
+public class AutoscalerTaskMgmtAdminService extends AbstractAdmin implements TaskManagementService{
+
+    private static final Log log = LogFactory.getLog(AutoscalerTaskMgmtAdminService.class);
+
+    private TaskSchedulingManager schedulingManager;
+
+
+    private static final String TASK_EXTENSION_NS =
+            "http://www.wso2.org/tasks";
+
+    private static final OMFactory FACTORY = OMAbstractFactory.getOMFactory();
+
+    private static final OMNamespace TASK_OM_NAMESPACE = FACTORY.createOMNamespace(
+            TASK_EXTENSION_NS, "task");
+
+    public AutoscalerTaskMgmtAdminService(){}
+    
+    public AutoscalerTaskMgmtAdminService(ConfigurationContext configurationContext) {
+        this.schedulingManager = TaskSchedulingManager.getInstance();
+        this.configurationContext = configurationContext;
+    }
+
+    public void shutdown() {
+        schedulingManager.shutDown(getConfigContext());
+    }
+
+    public void addTaskDescription(TaskDescription taskDescription, Map<String, Object> resources)
+            throws Exception {
+        if (log.isDebugEnabled()) {
+            log.debug("Adding the Task " + taskDescription.getName());
+        }
+        try {
+            schedulingManager.scheduleTask(taskDescription, resources, getConfigContext());
+        } catch (Exception e) {
+            String msg = "Cannot add the task " + taskDescription.getName() + "..";
+            log.error(msg, e);  
+            throw e;
+        }
+    }
+
+    /**
+     * Passing the Task Description to scheduling manager to actually add it to the Task
+     * Description Repository.
+     *
+     * @param taskDescription TaskDescription
+     */
+    public void addTaskDescription(TaskDescription taskDescription) {
+        if (log.isDebugEnabled()) {
+            log.debug("Adding the Task " + taskDescription.getName());
+        }
+        try {
+            Map<String, Object> resources = new HashMap<String, Object>();
+            schedulingManager.scheduleTask(taskDescription, resources, getConfigContext());
+        } catch (Exception e) {
+            String msg = "Cannot add the task";
+            log.error(msg, e);
+        }
+    }
+
+    public void addTaskDescriptionInAnOmElement(String taskElementString) throws
+                                                                          TaskManagementException,
+                                                                          XMLStreamException {
+        OMElement taskElement = AXIOMUtil.stringToOM(taskElementString);
+        if (log.isDebugEnabled()) {
+            log.debug("Add TaskDescription - Get a Task configuration  :" + taskElement);
+        }
+        TaskDescription taskDescription = validateAndCreate(taskElement);
+
+        try {
+            addTaskDescription(taskDescription);
+        } catch (Exception e) {
+            try {
+                getTaskManager().deleteTaskDescription(taskDescription.getName(),
+                        taskDescription.getGroup());
+            } catch (Exception ignored) {
+            }
+            handleException("Error creating a task : " + e.getMessage(), e);
+        }
+    }
+
+
+
+    public void deleteTaskDescription(TaskDescription taskDescription) {
+        String taskName = taskDescription.getName();
+        if (log.isDebugEnabled()) {
+            log.debug("Deleting the task " + taskName);
+        }
+        try {
+            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
+        } catch (Exception e) {
+            log.error("Cannot delete the task " + taskName, e);
+        }
+    }
+
+    /**
+     * Indicating Task Scheduling manager to delete the task with the given task Name.
+     *
+     * @param taskName taskName
+     */
+    public void deleteTaskDescription(String taskName) {
+        if (log.isDebugEnabled()) {
+            log.debug("Deleting the task " + taskName);
+        }
+        try {
+            TaskDescription taskDescription = new TaskDescription();
+            taskDescription.setName(taskName);
+            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
+        } catch (Exception e) {
+            log.error("Cannot delete the task " + taskName, e);
+        }
+    }
+
+    /**
+     * Notifying the Task Scheduling Manager to delete the previous Task Description from the
+     * Task Description Repository and add the edited task.
+     *
+     * @param taskDescription TaskDescription
+     */
+    public void editTaskDescription(TaskDescription taskDescription) {
+        if (log.isDebugEnabled()) {
+            log.debug("Editing the task " + taskDescription.getName());
+        }
+        if (schedulingManager.isContains(taskDescription.getName(), getConfigContext())) {
+            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
+            schedulingManager.scheduleTask(taskDescription, null, getConfigContext());
+        } else {
+            log.error("Task " + taskDescription.getName() + "does not exist");
+        }
+    }
+
+    public void editTaskDescriptionInOmElement(
+            String taskElementString) throws TaskManagementException, XMLStreamException {
+        OMElement taskElement = AXIOMUtil.stringToOM(taskElementString);
+        if (log.isDebugEnabled()) {
+            log.debug("Edit TaskDescription - Get a Task configuration  :" + taskElement);
+        }
+        try {
+            editTaskDescription(validateAndCreate(taskElement));
+        } catch (Exception e) {
+            String msg = "Error editing Task";
+            throw new TaskManagementException(msg, e);
+        }
+    }
+
+    /**
+     * Returns the list of Task Descriptions that have been already added to the Task Description
+     * Repository.
+     *
+     * @return A list of Task Descriptions
+     */
+    public List<TaskDescription> getAllTaskDescriptions() {
+        List<TaskDescription> taskDescriptions = new ArrayList<TaskDescription>();
+        Iterator<TaskDescription> iterator = schedulingManager.getAllTaskDescriptions(
+                getConfigContext());
+
+        while (iterator.hasNext()) {
+            TaskDescription taskDescription = iterator.next();
+            if (taskDescription != null) {
+                taskDescriptions.add(taskDescription);
+            }
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("All available Task based Scheduled Functions " + taskDescriptions);
+        }
+        return taskDescriptions;
+    }
+
+    public String getAllTaskDescriptionsInAnOMElement() throws AxisFault {
+        OMElement rootElement =
+                OMAbstractFactory.getOMFactory().createOMElement(new QName(TASK_EXTENSION_NS,
+                        "taskExtension", "task"));
+        try {
+            List<TaskDescription> descriptions = getAllTaskDescriptions();
+            for (TaskDescription taskDescription : descriptions) {
+                if (taskDescription != null) {
+                    OMElement taskElement =
+                            TaskDescriptionSerializer.serializeTaskDescription(TASK_OM_NAMESPACE,
+                                                                               taskDescription);
+                    validateTaskElement(taskElement);
+                    rootElement.addChild(taskElement);
+                }
+            }
+        } catch (TaskManagementException e) {
+            String msg = "Error loading all tasks";
+            log.error(msg, e);
+            throw new AxisFault(msg, e);
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Returning all TaskDescriptions as  :" + rootElement);
+        }
+        return rootElement.toString();
+    }
+
+    /**
+     * Returns the names of job groups that are being executed.
+     *
+     * @return An array of strings
+     */
+    public String[] getAllJobGroups() {
+        List<String> strings = getTaskManager().getAllJobGroups();
+        return strings.toArray(new String[strings.size()]);
+    }
+
+    /**
+     * Returns the TaskDescription associates with a particular task name
+     *
+     * @param taskName Task Name
+     * @return TaskDescription
+     */
+    public TaskDescription getTaskDescription(String taskName) {
+        return schedulingManager.getTaskDescription(taskName, getConfigContext());
+    }
+
+    public boolean isContains(String taskName) {
+        return schedulingManager.isContains(taskName, getConfigContext());
+    }
+
+    /**
+     * @param taskClass taskClass
+     * @return list of strings containing properties of the task class
+     */
+    public List<String> getPropertyNames(String taskClass) {
+        return null;
+    }
+
+    /**
+     * Returns the TaskManager instance currently being used
+     *
+     * @return TaskManager
+     */
+    private synchronized TaskManager getTaskManager() {
+        return (TaskManager) getConfigContext().getProperty(
+                TaskManager.CARBON_TASK_MANAGER);
+    }
+
+    /**
+     * Validates the OMElement which has a particular TaskDescription
+     * serialized into it.
+     *
+     * @param taskElement taskElement
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void validateTaskElement(
+            OMElement taskElement) throws TaskManagementException {
+        if (taskElement == null) {
+            handleException("Task Description OMElement can not be found.");
+        }
+    }
+
+    /**
+     * Handles the exception thrown and logs it.
+     *
+     * @param msg message to be logged
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void handleException(String msg) throws TaskManagementException {
+        log.error(msg);
+        throw new TaskManagementException(msg);
+    }
+
+    /**
+     * Handles the exception thrown and logs it.
+     *
+     * @param msg message to be logged
+     * @param e   exception thrown
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void handleException(String msg, Exception e) throws TaskManagementException {
+        log.error(msg, e);
+        throw new TaskManagementException(msg, e);
+    }
+
+    /**
+     * Validates an OMElement which has a TaskDescription serialized into it
+     * and returns the corresponding TaskDescription
+     *
+     * @param taskElement OMElement containing the TaskDescription
+     * @return TaskDescription
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static TaskDescription validateAndCreate(
+            OMElement taskElement) throws TaskManagementException {
+
+        validateTaskElement(taskElement);
+        TaskDescription taskDescription =
+                TaskDescriptionFactory.createTaskDescription(taskElement, TASK_OM_NAMESPACE);
+        validateTaskDescription(taskDescription);
+        if (log.isDebugEnabled()) {
+            log.debug("Task Description : " + taskDescription);
+        }
+        return taskDescription;
+    }
+
+    /**
+     * Validates TaskDescriptions
+     *
+     * @param description TaskDescription
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void validateTaskDescription(
+            TaskDescription description) throws TaskManagementException {
+        if (description == null) {
+            handleException("Task Description can not be found.");
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
new file mode 100644
index 0000000..852c6bd
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
@@ -0,0 +1,68 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.mediator.autoscale.lbautoscale.task;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.task.Task;
+import org.quartz.Job;
+import org.quartz.JobDetail;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import java.util.Map;
+
+public class AutoscalingJob implements Job {
+
+    public static final String AUTOSCALER_TASK = "autoscalerTask";
+
+    public static final String SYNAPSE_ENVI = "synapseEnv";
+
+    private static final Log log = LogFactory.getLog(AutoscalingJob.class);
+
+    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
+
+        try {
+
+            Task task = null;
+
+            JobDetail jobDetail = jobExecutionContext.getJobDetail();
+
+            if (log.isDebugEnabled()) {
+                log.debug("Executing Autoscaler task : " + jobDetail.getKey().getName());
+            }
+
+            @SuppressWarnings("rawtypes")
+            Map mjdm = jobExecutionContext.getMergedJobDataMap();
+
+            task = (Task) mjdm.get(AUTOSCALER_TASK);
+
+            if (task instanceof ManagedLifecycle) {
+                // Execute Autoscaler task
+                ((ServiceRequestsInFlightAutoscaler) task).execute();
+            }
+
+        } catch (Exception e) {
+            throw new JobExecutionException(e);
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
new file mode 100644
index 0000000..05f987d
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
@@ -0,0 +1,524 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.task;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.callables.InstanceCountCallable;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
+import org.apache.synapse.task.Task;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.mediator.autoscale.lbautoscale.callables.AppNodeSanityCheckCallable;
+import org.apache.stratos.mediator.autoscale.lbautoscale.callables.AutoscaleDeciderCallable;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerOsgiClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerStubClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.apache.stratos.lb.common.replication.RequestTokenReplicationCommand;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+
+/**
+ * Service request in flight autoscaler task for Stratos service level auto-scaling
+ */
+public class ServiceRequestsInFlightAutoscaler implements Task, ManagedLifecycle {
+
+    private static final Log log = LogFactory.getLog(ServiceRequestsInFlightAutoscaler.class);
+
+    /**
+     * This instance holds the loadbalancer configuration
+     */
+    private LoadBalancerConfiguration loadBalancerConfig;
+
+    /**
+     * Autoscaler service client instance
+     */
+    private CloudControllerClient autoscalerService;
+
+    /**
+     * AppDomainContexts for each domain
+     * Key - domain
+     * Value - Map of key - sub domain
+     * value - {@link AppDomainContext}
+     */
+    private Map<String, Map<String, ?>> appDomainContexts =
+        new HashMap<String, Map<String, ?>>();
+
+    /**
+     * LB Context for LB cluster
+     */
+    private final LoadBalancerContext lbContext = new LoadBalancerContext();
+
+    /**
+     * Attribute to keep track whether this instance is the primary load balancer.
+     */
+    private boolean isPrimaryLoadBalancer;
+
+    /**
+     * Keeps track whether this task is still running
+     */
+    private boolean isTaskRunning;
+    
+    /**
+     * Thread pool used in this task to execute parallel tasks.
+     */
+    private ExecutorService executor = Executors.newFixedThreadPool(100);
+
+    /**
+     * Check that all app nodes in all clusters meet the minimum configuration
+     */
+    private void appNodesSanityCheck() {
+        
+        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
+        
+        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
+            
+            String msg =
+                    "Sanity check is failed to run. No Appdomain context is generated for the" +
+                        " domain " + serviceDomain;
+            
+            // get the list of service sub_domains specified in loadbalancer config
+            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
+
+            for (String serviceSubDomain : serviceSubDomains) {
+                log.debug("Sanity check has started for: "+AutoscaleUtil.domainSubDomainString(serviceDomain, serviceSubDomain));
+                AppDomainContext appCtxt;
+                if (appDomainContexts.get(serviceDomain) != null) {
+                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
+                    
+                    if (appCtxt != null) {
+                        // Concurrently perform the application node sanity check.
+                        Callable<Boolean> worker =
+                            new AppNodeSanityCheckCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
+                        Future<Boolean> appNodeSanityCheck = executor.submit(worker);
+                        jobList.add(appNodeSanityCheck);
+
+                    } else{
+                        log.error(msg + " and sub domain " + serviceSubDomain + " combination.");
+                    }
+                } else{
+                    log.error(msg);
+                }
+            }
+        }
+        
+        // Retrieve the results of the concurrently performed sanity checks.
+        for (Future<Boolean> job : jobList) {
+            try {
+                job.get();
+            } catch (Exception ignore) {
+                log.error(ignore.getMessage(), ignore);
+                // no need to throw
+            } 
+        }
+
+    }
+
+    /**
+     * Autoscale the entire system, analyzing the requests in flight of each domain - sub domain
+     */
+    private void autoscale() {
+        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
+
+        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
+
+            String msg =
+                "Autoscaler check is failed to run. No Appdomain context is generated for the" +
+                    " domain " + serviceDomain;
+
+            // get the list of service sub_domains specified in loadbalancer config
+            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
+
+            for (String serviceSubDomain : serviceSubDomains) {
+
+                log.debug("Autoscaling analysis is starting to run for domain: " + serviceDomain +
+                    " and sub domain: " + serviceSubDomain);
+
+                AppDomainContext appCtxt;
+                if (appDomainContexts.get(serviceDomain) != null) {
+                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
+
+                    if (appCtxt != null) {
+
+                        // Concurrently make the auto-scaling decisions
+                        Callable<Boolean> worker =
+                            new AutoscaleDeciderCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
+                        Future<Boolean> autoscalerDeciderCheck = executor.submit(worker);
+                        jobList.add(autoscalerDeciderCheck);
+
+                    } else {
+                        log.error(msg + " and sub domain " + serviceSubDomain + " combination.");
+                    }
+                } else {
+                    log.error(msg);
+                }
+            }
+        }
+
+        // Retrieve the results of the concurrently performed sanity checks.
+        for (Future<Boolean> job : jobList) {
+            try {
+                job.get();
+            } catch (Exception ignore) {
+                log.error(ignore.getMessage(), ignore);
+                // no need to throw
+            }
+        }
+    }
+
+    /**
+     * We compute the number of running instances of a particular domain using clustering agent.
+     */
+    private void computeRunningAndPendingInstances() {
+
+        int runningInstances = 0, pendingInstances = 0;
+
+        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
+
+        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
+
+            // get the list of service sub_domains specified in loadbalancer config
+            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
+
+            for (String serviceSubDomain : serviceSubDomains) {
+
+                AppDomainContext appCtxt;
+                if (appDomainContexts.get(serviceDomain) != null) {
+                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
+                    
+                    log.debug("Values in App domain context: " +
+                        appCtxt.getPendingInstanceCount() +
+                            " - " +
+                            appCtxt.getRunningInstanceCount() +
+                            " - Ctxt: " +
+                            appCtxt.hashCode());
+
+                    if (appCtxt != null) {
+                        Callable<Boolean> worker =
+                            new InstanceCountCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
+                        Future<Boolean> countInstancesJob = executor.submit(worker);
+                        jobList.add(countInstancesJob);
+                    }
+                }
+            }
+        }
+
+        for (Future<Boolean> job : jobList) {
+            try {
+                job.get();
+            } catch (Exception ignore) {
+                log.error(ignore.getMessage(), ignore);
+                // no need to throw
+            }
+        }
+
+        /* Calculate running load balancer instances */
+
+        // count this LB instance in.
+        runningInstances = 1;
+
+        runningInstances += AutoscalerTaskDSHolder.getInstance().getAgent().getAliveMemberCount();
+
+        lbContext.setRunningInstanceCount(runningInstances);
+
+        if (AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("domain") == null) {
+            String msg = "Clustering Agent's domain parameter is null. Please specify a domain" +
+                " name in axis2.xml of Elastic Load Balancer.";
+            log.error(msg);
+            throw new RuntimeException(msg);
+        }
+
+        String lbDomain = AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("domain").getValue().toString();
+
+        String lbSubDomain = null;
+
+        if (AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("subDomain") != null) {
+            lbSubDomain =
+                AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("subDomain").getValue().toString();
+        }
+
+        // reset
+        pendingInstances = 0;
+        try {
+            pendingInstances = lbContext.getPendingInstanceCount();
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            // no need to throw
+        }
+
+        lbContext.setPendingInstanceCount(pendingInstances);
+
+        log.debug("Load Balancer members of domain: " +
+            lbDomain +
+            " and sub domain: " +
+            lbSubDomain +
+            " running instances (including this): " +
+            runningInstances +
+            " - pending instances: "
+            +
+            pendingInstances);
+
+    }
+
+    @Override
+    public void destroy() {
+        appDomainContexts.clear();
+        log.debug("Cleared AppDomainContext Map.");
+    }
+
+    /**
+     * This is method that gets called periodically when the task runs.
+     * <p/>
+     * The exact sequence of execution is shown in this method.
+     */
+    @Override
+    public void execute() {
+
+        appDomainContexts =
+            AutoscaleUtil.getAppDomainContexts(
+                AutoscalerTaskDSHolder.getInstance().getConfigCtxt(),
+                loadBalancerConfig);
+
+        if (isTaskRunning) {
+            log.debug("Task is already running!");
+            return;
+        }
+        try {
+            isTaskRunning = true;
+            setIsPrimaryLB();
+            if (!isPrimaryLoadBalancer) {
+                log.debug("This is not the primary load balancer, hence will not " +
+                        "perform any sanity check.");
+                return;
+            }
+            sanityCheck();
+            autoscale();
+        } finally {
+            // if there are any changes in the request length
+            if (Boolean.parseBoolean(System.getProperty(AutoscaleConstants.IS_TOUCHED))) {
+                // primary LB will send out replication message to all load balancers
+                sendReplicationMessage();
+            }
+            isTaskRunning = false;
+            log.debug("Task finished a cycle.");
+        }
+    }
+
+    @Override
+    public void init(final SynapseEnvironment synEnv) {
+
+        String msg = "Autoscaler Service initialization failed and cannot proceed.";
+
+        loadBalancerConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
+
+        if (loadBalancerConfig == null) {
+            log.error(msg + "Reason: Load balancer configuration is null.");
+            throw new RuntimeException(msg);
+        }
+
+        ConfigurationContext configCtx = ((Axis2SynapseEnvironment) synEnv).getAxis2ConfigurationContext();
+        AutoscalerTaskDSHolder.getInstance().setConfigCtxt(configCtx);
+
+        appDomainContexts = AutoscaleUtil.getAppDomainContexts(configCtx, loadBalancerConfig);
+        
+        AutoscalerTaskDSHolder.getInstance().setAgent(configCtx.getAxisConfiguration().getClusteringAgent());
+
+        boolean useEmbeddedAutoscaler = loadBalancerConfig.getLoadBalancerConfig().useEmbeddedAutoscaler();
+        
+        try {
+
+            if(useEmbeddedAutoscaler){
+                autoscalerService = new CloudControllerOsgiClient();
+            } else{
+                autoscalerService = new CloudControllerStubClient();
+            }
+            // let's initialize the auto-scaler service
+            autoscalerService.init();
+
+        }catch (Exception e) {
+            log.error(msg, e);
+            throw new RuntimeException(msg, e);
+        }
+
+        if (log.isDebugEnabled()) {
+
+            log.debug("Autoscaler task is initialized.");
+
+        }
+    }
+
+    /**
+     * Sanity check to see whether the number of LBs is the number specified in the LB config
+     */
+    private void loadBalancerSanityCheck() {
+
+        log.debug("Load balancer sanity check has started.");
+
+        // get current LB instance count
+        int currentLBInstances = lbContext.getInstances();
+
+        LoadBalancerConfiguration.LBConfiguration lbConfig =
+            loadBalancerConfig.getLoadBalancerConfig();
+
+        // get minimum requirement of LB instances
+        int requiredInstances = lbConfig.getInstances();
+
+        if (currentLBInstances < requiredInstances) {
+            log.debug("LB Sanity check failed. Running/Pending LB instances: " + currentLBInstances +
+                ". Required LB instances: " + requiredInstances);
+            int diff = requiredInstances - currentLBInstances;
+
+            // gets the domain of the LB
+            String lbDomain =
+                AutoscalerTaskDSHolder
+                    .getInstance()
+                    .getAgent()
+                    .getParameter("domain")
+                    .getValue()
+                    .toString();
+            String lbSubDomain =
+                AutoscalerTaskDSHolder
+                    .getInstance()
+                    .getAgent()
+                    .getParameter("subDomain")
+                    .getValue()
+                    .toString();
+
+            // Launch diff number of LB instances
+            log.debug("Launching " + diff + " LB instances.");
+
+            runInstances(lbContext, lbDomain, lbSubDomain, diff);
+        }
+    }
+
+    private int runInstances(final LoadBalancerContext context, final String domain,
+        final String subDomain,
+        int diff) {
+
+        int successfullyStartedInstanceCount = diff;
+
+        while (diff > 0) {
+            // call autoscaler service and ask to spawn an instance
+            // and increment pending instance count only if autoscaler service returns
+            // true.
+            try {
+                String ip = autoscalerService.startInstance(domain, subDomain);
+
+                if (ip == null || ip.isEmpty()) {
+                    log.debug("Instance start up failed. domain: " +
+                        domain +
+                            ", sub domain: " +
+                            subDomain);
+                    successfullyStartedInstanceCount--;
+                } else {
+                    log.debug("An instance of domain: " +
+                        domain +
+                            " and sub domain: " +
+                            subDomain +
+                            " is started up.");
+                    if (context != null) {
+                        context.incrementPendingInstances(1);
+                    }
+                }
+            } catch (Exception e) {
+                log.error("Failed to start an instance of sub domain: " + subDomain +
+                    " of domain : " + domain + ".\n", e);
+                successfullyStartedInstanceCount--;
+            }
+
+            diff--;
+        }
+
+        return successfullyStartedInstanceCount;
+    }
+
+    /**
+     * This method makes sure that the minimum configuration of the clusters in the system is
+     * maintained
+     */
+    private void sanityCheck() {
+
+        if (!isPrimaryLoadBalancer) {
+            log.debug("This is not the primary load balancer, hence will not " +
+                "perform any sanity check.");
+            return;
+        }
+
+        log.debug("This is the primary load balancer, starting to perform sanity checks.");
+
+        computeRunningAndPendingInstances();
+        loadBalancerSanityCheck();
+        appNodesSanityCheck();
+    }
+
+    /**
+     * Replicate information needed to take autoscaling decision for other ELBs
+     * in the cluster.
+     */
+    private void sendReplicationMessage() {
+
+        ClusteringAgent clusteringAgent = AutoscalerTaskDSHolder.getInstance().getAgent();
+        if (clusteringAgent != null) {
+            RequestTokenReplicationCommand msg = new RequestTokenReplicationCommand();
+            msg.setAppDomainContexts(appDomainContexts);
+            try {
+                clusteringAgent.sendMessage(msg, true);
+                System.setProperty(AutoscaleConstants.IS_TOUCHED, "false");
+                log.debug("Request token replication messages sent out successfully!!");
+
+            } catch (ClusteringFault e) {
+                log.error("Failed to send the request token replication message.", e);
+            }
+        }
+        else {
+            log
+                .debug("Clustering Agent is null. Hence, unable to send out the replication message.");
+        }
+    }
+
+    /**
+     * This method will check whether this LB is the primary LB or not and set
+     * attribute accordingly.
+     */
+    private void setIsPrimaryLB() {
+
+        ClusteringAgent clusteringAgent = AutoscalerTaskDSHolder.getInstance().getAgent();
+        if (clusteringAgent != null) {
+
+            isPrimaryLoadBalancer = clusteringAgent.isCoordinator();
+
+        }
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
new file mode 100644
index 0000000..b97deb4
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
@@ -0,0 +1,188 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.task;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskDescriptionRepository;
+import org.apache.synapse.task.TaskScheduler;
+import org.wso2.carbon.task.TaskManager;
+
+import java.util.Iterator;
+import java.util.Map;
+
+public class TaskSchedulingManager {
+
+    private static final Log log = LogFactory.getLog(TaskSchedulingManager.class);
+
+    private static TaskSchedulingManager thisInstance = new TaskSchedulingManager();
+
+    public static TaskSchedulingManager getInstance() {
+        return thisInstance;
+    }
+
+    /**
+     * This method adds a particular Task to the Task Description Repository and schedule it
+     * for the execution.
+     *
+     * @param taskDescription      TaskDescription
+     * @param resources            Map containing require meta data for the task execution.
+     * @param configurationContext ConfigurationContext
+     */
+    public void scheduleTask(TaskDescription taskDescription, Map<String, Object> resources,
+                             ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Adding a Task Description to the Task Description Repository");
+        }
+
+        getTaskDescriptionRepository(configurationContext).addTaskDescription(taskDescription);
+        getTaskScheduler(configurationContext).scheduleTask(
+                taskDescription, resources, AutoscalingJob.class);
+
+        if (log.isDebugEnabled()) {
+            log.debug("Task Description " + taskDescription.getName() +
+                    " added to the Task Description Repository");
+        }
+    }
+
+    /**
+     * Returns a Task Description with a given name from the Task Description Repository.
+     *
+     * @param taskName             taskName
+     * @param configurationContext ConfigurationContext
+     * @return TaskDescription
+     */
+    public TaskDescription getTaskDescription(
+            String taskName, ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Returning a Start up : " + taskName + " from the configuration");
+        }
+
+        TaskDescription taskDescription = getTaskDescriptionRepository(
+                configurationContext).getTaskDescription(taskName);
+
+        if (taskDescription != null) {
+            if (log.isDebugEnabled()) {
+                log.debug("Returning a Task Description : " + taskDescription);
+
+            }
+            return taskDescription;
+        } else {
+            if (log.isDebugEnabled()) {
+                log.debug("No Task Description can be found with name :" + taskName);
+            }
+            return null;
+        }
+    }
+
+    /**
+     * This method search for a given Task which has already been added to the Task Description
+     * Repository and removes it.
+     *
+     * @param taskDescription             TaskDescription
+     * @param configurationContext ConfigurationContext
+     */
+    public void deleteTaskDescription(TaskDescription taskDescription, ConfigurationContext configurationContext) {
+        String taskName = null;
+        if (taskDescription != null) {
+            taskName = taskDescription.getName();
+            getTaskDescriptionRepository(configurationContext).removeTaskDescription(taskName);
+            getTaskScheduler(configurationContext).deleteTask(taskName, taskDescription.getGroup());
+
+            if (log.isDebugEnabled()) {
+                log.debug("Deleted TaskDescription : " + taskName + " from the configuration");
+            }
+        } else {
+            log.warn("Unable to delete the Task " + taskName
+                    + ",as it doesn't exist in the Repository");
+        }
+    }
+
+    /**
+     * Retrieves all Task Descriptions added to the Task Description Repository at a given instance.
+     *
+     * @param configurationContext ConfigurationContext
+     * @return TaskDescription Iterator
+     */
+    public Iterator<TaskDescription> getAllTaskDescriptions(
+            ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Returning a All TaskDescription from the configuration");
+        }
+        return getTaskDescriptionRepository(configurationContext).getAllTaskDescriptions();
+    }
+
+    /**
+     * This method checks whether a particular Task has already been added to the Task Description
+     * Repository associated with the context of this execution and returns a flag indicating the
+     * existence.
+     *
+     * @param taskName             Name of the task to be searched
+     * @param configurationContext ConfigurationContext
+     * @return a boolean depending on the existence of a task
+     */
+    public boolean isContains(String taskName, ConfigurationContext configurationContext) {
+        return !getTaskDescriptionRepository(configurationContext).isUnique(taskName);
+    }
+
+    /**
+     * Returns the Carbon TaskDescriptionRepository instance that carries details of the added
+     * tasks for execution.
+     *
+     * @param configurationContext ConfigurationContext
+     * @return TaskDescriptionRepository
+     */
+    private synchronized TaskDescriptionRepository getTaskDescriptionRepository(
+            ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Retrieving access to Task Description Repository");
+        }
+        return (TaskDescriptionRepository) configurationContext.getProperty(
+                TaskManager.CARBON_TASK_REPOSITORY);
+    }
+
+    /**
+     * Returns the carbon TaskScheduler associated with the context of scheduling the task execution
+     *
+     * @param configurationContext ConfigurationContext
+     * @return TaskScheduler
+     */
+    private synchronized TaskScheduler getTaskScheduler(ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Retrieving access to Task Scheduler");
+        }
+        return (TaskScheduler) configurationContext.getProperty(
+                TaskManager.CARBON_TASK_SCHEDULER);
+    }
+
+    public void shutDown(ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Starting to shut down tasks");
+        }
+
+//        getTaskDescriptionRepository(configurationContext).addTaskDescription(taskDescription);
+        getTaskScheduler(configurationContext).shutDown();
+
+        if (log.isDebugEnabled()) {
+            log.debug("All tasks shut down");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
new file mode 100644
index 0000000..ed549c3
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
@@ -0,0 +1,68 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.util;
+
+/**
+ * Constants
+ */
+public final class AutoscaleConstants {
+    public static final String REQUEST_ID = "request.id";
+    public static final String APP_DOMAIN_CONTEXTS = "autoscale.app.domain.contexts";
+    public static final String TARGET_DOMAIN = "autoscale.target.domain";
+    public static final String TARGET_SUB_DOMAIN = "autoscale.target.sub.domain";
+    public static final String LOAD_BALANCER_CONFIG = "loadbalancer.conf";
+    
+    /**
+     * we use this to track the changes happen to request token list lengths.
+     */
+    public static final String IS_TOUCHED = "is_touched";
+    
+    /**
+     * We'll check whether a server is started up in every this much of time.
+     * (in milliseconds)
+     */
+    public static final int SERVER_START_UP_CHECK_TIME = 30000;
+    
+    /**
+     * We'll check whether an instance is left the cluster in every this much of time.
+     * (in milliseconds)
+     */
+    public static final int INSTANCE_REMOVAL_CHECK_TIME = 5000;
+
+    /**
+     * Name of the EC2 instance tag which if set on an instance, the autoscaler will not
+     * terminate such instance
+     */
+    public static final String AVOID_TERMINATION = "avoidTermination";
+
+    public static enum InstanceState {
+        RUNNING("running"), PENDING("pending"), TERMINATED("terminated"), SHUTTING_DOWN("shutting-down");
+
+        private String state;
+
+        InstanceState(String state) {
+            this.state = state;
+        }
+
+        public String getState() {
+            return state;
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
new file mode 100644
index 0000000..747d3a2
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
@@ -0,0 +1,359 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.util;
+
+import org.apache.axiom.om.util.Base64;
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.protocol.HTTP;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.state.check.PendingInstancesStateChecker;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Utility methods for Autoscale mediator
+ */
+public final class AutoscaleUtil {
+
+    private static final Log log = LogFactory.getLog(AutoscaleUtil.class);
+
+    private AutoscaleUtil() {
+    }
+
+    /**
+     * handles the exception
+     *
+     * @param msg exception message
+     */
+    public static void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+
+    /**
+     * handles the exception
+     *
+     * @param msg exception message
+     * @param e   exception
+     */
+    public static void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new SynapseException(msg, e);
+    }
+
+    /**
+     * Returns the contents of the file in a byte array
+     *
+     * @param file - Input File
+     * @return Bytes from the file
+     * @throws java.io.IOException, if retrieving the file contents failed.
+     */
+    public static byte[] getBytesFromFile(File file) throws IOException {
+        if (!file.exists()) {
+            log.error("Payload file " + file.getAbsolutePath() + " does not exist");
+            return null;
+        }
+        InputStream is = new FileInputStream(file);
+        byte[] bytes;
+
+        try {
+            // Get the size of the file
+            long length = file.length();
+
+            // You cannot create an array using a long type.
+            // It needs to be an int type.
+            // Before converting to an int type, check
+            // to ensure that file is not larger than Integer.MAX_VALUE.
+            if (length > Integer.MAX_VALUE) {
+                if (log.isDebugEnabled()) {
+                    log.debug("File is too large");
+                }
+            }
+
+            // Create the byte array to hold the data
+            bytes = new byte[(int) length];
+
+            // Read in the bytes
+            int offset = 0;
+            int numRead;
+            while (offset < bytes.length
+                   && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
+                offset += numRead;
+            }
+
+            // Ensure all the bytes have been read in
+            if (offset < bytes.length) {
+                throw new IOException("Could not completely read file " + file.getName());
+            }
+        } finally {
+            // Close the input stream and return bytes
+            is.close();
+        }
+
+        return bytes;
+    }
+
+    /**
+     * Replaces the variables
+     *
+     * @param text input string
+     * @return output String
+     */
+    public static String replaceVariables(String text) {
+        int indexOfStartingChars;
+        int indexOfClosingBrace;
+
+        // The following condition deals with properties.
+        // Properties are specified as ${system.property},
+        // and are assumed to be System properties
+        if ((indexOfStartingChars = text.indexOf("${")) != -1 &&
+            (indexOfClosingBrace = text.indexOf("}")) != -1) { // Is a property used?
+            String var = text.substring(indexOfStartingChars + 2,
+                                        indexOfClosingBrace);
+
+            String propValue = System.getProperty(var);
+            if (propValue == null) {
+                propValue = System.getenv(var);
+            }
+            if (propValue != null) {
+                text = text.substring(0, indexOfStartingChars) + propValue +
+                       text.substring(indexOfClosingBrace + 1);
+            }
+        }
+        return text;
+    }
+
+/*    public static InstanceManager createEC2InstanceManager(String accessKey,
+                                                              String secretKey,
+                                                              String instanceMgtEPR) {
+        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
+        AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentials);
+        ec2Client.setEndpoint(instanceMgtEPR);
+        return new InstanceManager(ec2Client);
+    }*/
+
+    public static String getUserData(String payloadFileName) {
+        String userData = null;
+        try {
+            File file = new File(payloadFileName);
+            if (!file.exists()) {
+                handleException("Payload file " + payloadFileName + " does not exist");
+            }
+            if (!file.canRead()) {
+                handleException("Payload file " + payloadFileName + " does cannot be read");
+            }
+            byte[] bytes = AutoscaleUtil.getBytesFromFile(file);
+            if (bytes != null) {
+//                /BASE64.e encoder = new BASE64Encoder();
+                userData = Base64.encode(bytes);
+            }
+        } catch (IOException e) {
+            AutoscaleUtil.handleException("Cannot read data from payload file " + payloadFileName,
+                                          e);
+        }
+        return userData;
+    }
+
+    /*public static boolean areEqual(List<GroupIdentifier> securityGroups1, String[] sourceGroups2) {
+        for (String sourceGroup : sourceGroups2) {
+            boolean isSourceGroupFound = false;
+            for (GroupIdentifier securityGroup : securityGroups1) {
+                if (securityGroup.getGroupName().equals(sourceGroup)) {
+                    isSourceGroupFound = true;
+                }
+            }
+            if (!isSourceGroupFound) {
+                return false;
+            }
+        }
+        return true;
+    } */
+
+    /**
+     * TODO These methods should use to common place since these are using endpoints and mediators
+     */
+    public static int getTenantId(String url) {
+        String address = url;
+        String servicesPrefix = "/t/";
+        if (address != null && address.contains(servicesPrefix)) {
+            int domainNameStartIndex =
+                    address.indexOf(servicesPrefix) + servicesPrefix.length();
+            int domainNameEndIndex = address.indexOf('/', domainNameStartIndex);
+            String domainName = address.substring(domainNameStartIndex,
+                    domainNameEndIndex == -1 ? address.length() : domainNameEndIndex);
+            // return tenant id if domain name is not null
+            if (domainName != null) {
+                try {
+                    return AutoscalerTaskDSHolder.getInstance().getRealmService().getTenantManager().getTenantId(domainName);
+                } catch (org.wso2.carbon.user.api.UserStoreException e) {
+                    log.error("An error occurred while obtaining the tenant id.", e);
+                }
+            }
+        }
+        // return 0 if the domain name is null
+        return 0;
+    }
+
+    /**
+     * TODO These methods should use to common place since these are using endpoints and mediators
+     */
+    @SuppressWarnings("unchecked")
+    public static String getTargetHost(MessageContext synCtx) {
+        org.apache.axis2.context.MessageContext axis2MessageContext =
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+        Map<String, String> headers =
+                (Map<String, String>) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+        String address = headers.get(HTTP.TARGET_HOST);
+        if (address.contains(":")) {
+            address = address.substring(0, address.indexOf(":"));
+        }
+        return address;
+    }
+
+    @SuppressWarnings("unchecked")
+    public static Map<String, Map<String, ?>> getAppDomainContexts(ConfigurationContext configCtx,
+ LoadBalancerConfiguration lbConfig) {
+        Map<String, Map<String, ?>> oldAppDomainContexts =
+        	(Map<String, Map<String, ?>>) configCtx.getPropertyNonReplicable(AutoscaleConstants.APP_DOMAIN_CONTEXTS);
+        Map<String, Map<String, ?>> newAppDomainContexts = new HashMap<String, Map<String, ?>>();
+        
+            ClusteringAgent clusteringAgent = configCtx.getAxisConfiguration().getClusteringAgent();
+
+            for (String domain : lbConfig.getServiceDomains()) {
+
+                for (String subDomain : lbConfig.getServiceSubDomains(domain)) {
+                    if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+                        throw new SynapseException("Axis2 clustering GroupManagementAgent for domain: " + domain +
+                                                   ", sub-domain: " + subDomain +
+                                                   " has not been defined");
+                    }
+
+                    if(oldAppDomainContexts == null || oldAppDomainContexts.get(domain) == null || 
+                    		(oldAppDomainContexts.get(domain) != null && oldAppDomainContexts.get(domain).get(subDomain) == null)){
+                    	
+                    	AppDomainContext appCtxt = new AppDomainContext(lbConfig.getServiceConfig(domain,
+                                subDomain));
+
+                    	addAppDomainContext(newAppDomainContexts, domain, subDomain, appCtxt);
+                    	
+                    } else {
+                        addAppDomainContext(newAppDomainContexts, domain, subDomain, (AppDomainContext) oldAppDomainContexts.get(domain).get(subDomain));
+                    }
+                    
+                }
+
+            }
+//        }
+        configCtx.setNonReplicableProperty(AutoscaleConstants.APP_DOMAIN_CONTEXTS,
+                                           newAppDomainContexts);
+
+        return newAppDomainContexts;
+    }
+    
+    
+    private static void addAppDomainContext(Map<String, Map<String, ?>> appDomainContexts,
+                                     String domain, String subDomain, AppDomainContext appCtxt) {
+
+        Map<String, AppDomainContext> map ;
+        
+        if(appDomainContexts.containsKey(domain)){
+            map = (Map<String, AppDomainContext>) appDomainContexts.get(domain);
+        }
+        else{
+            map = new HashMap<String, AppDomainContext>();
+        }
+        // put this appDomainContext
+        map.put(subDomain, appCtxt);
+        
+        // update the parent map
+        appDomainContexts.put(domain, map);
+        
+    }
+    
+    public static String domainSubDomainString(String domain, String subDomain){
+        return "Domain: "+domain+" - Sub Domain: "+subDomain;
+    }
+    
+    public static int runInstances(final CloudControllerClient client, final LoadBalancerContext context, final String domain,
+        final String subDomain, int diff) {
+
+        int successfullyStartedInstanceCount = diff;
+
+        if(context == null){
+            // can't help
+            return 0;
+        }
+        
+        while (diff > 0) {
+            // call autoscaler service and ask to spawn an instance
+            // and increment pending instance count only if autoscaler service returns
+            // true.
+            try {
+                String ip = client.startInstance(domain, subDomain);
+
+                if (ip == null || ip.isEmpty()) {
+                    log.debug("Instance start up failed for " + domainSubDomainString(domain, subDomain));
+                    successfullyStartedInstanceCount--;
+                    
+                } else {
+                    log.debug("An instance of " + domainSubDomainString(domain, subDomain) +
+                        " is started up.");
+                    if (context != null) {
+                        context.incrementPendingInstances(1);
+                    }
+                }
+            } catch (Exception e) {
+                log.error("Failed to start an instance of " + domainSubDomainString(domain, subDomain) + ".\n", e);
+                successfullyStartedInstanceCount--;
+            }
+
+            diff--;
+        }
+
+        if (successfullyStartedInstanceCount > 0) {
+            
+            Thread stateChecker =
+                new Thread(new PendingInstancesStateChecker(
+                    context,
+                    domain,
+                    subDomain,
+                    successfullyStartedInstanceCount,
+                    context.getRunningInstanceCount(),
+                    client));
+            stateChecker.start();
+        }
+
+        return successfullyStartedInstanceCount;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
new file mode 100644
index 0000000..7b8e50f
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
@@ -0,0 +1,129 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.util;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.LBConfiguration;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.apache.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * Singleton class to hold Agent Management Service
+ */
+public class AutoscalerTaskDSHolder {
+    
+    private ConfigurationContextService configurationContextService;
+    private LoadBalancerConfiguration wholeLbConfig;
+    private CloudControllerService cloudControllerService;  
+
+    private RealmService realmService;
+    private ClusteringAgent agent;
+    private ConfigurationContext configCtxt;
+    private UserRegistry configRegistry;
+    private UserRegistry governanceRegistry;
+
+    private static AutoscalerTaskDSHolder instance = new AutoscalerTaskDSHolder();
+
+    private AutoscalerTaskDSHolder(){
+
+    }
+
+    public static AutoscalerTaskDSHolder getInstance(){
+        return instance;
+    }
+
+    public ConfigurationContextService getConfigurationContextServiceService(){
+        return this.configurationContextService;
+    }
+
+    public void setConfigurationContextService(ConfigurationContextService cCtxService){
+        this.configurationContextService = cCtxService;
+    }
+    
+    public LoadBalancerConfiguration getWholeLoadBalancerConfig() {
+        return wholeLbConfig;
+    }
+    
+    public LBConfiguration getLoadBalancerConfig() {
+        return wholeLbConfig.getLoadBalancerConfig();
+    }
+
+    public ClusteringAgent getAgent() {
+        return agent;
+    }
+
+    public void setAgent(ClusteringAgent agent) {
+        this.agent = agent;
+    }
+
+
+    public void setRealmService(RealmService realmService) {
+        this.realmService = realmService;
+    }
+
+    public RealmService getRealmService() {
+        return realmService;
+    }
+    
+    public void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
+        if (lbConfigSer != null) {
+            this.wholeLbConfig = (LoadBalancerConfiguration) lbConfigSer.getLoadBalancerConfig();
+        } else {
+            this.wholeLbConfig = null;
+        }
+    }
+
+	public void setConfigCtxt(ConfigurationContext configCtxt) {
+		this.configCtxt = configCtxt;
+	}
+
+	public ConfigurationContext getConfigCtxt() {
+		return configCtxt;
+	}
+
+	public void setCloudControllerService(CloudControllerService cc) {
+        this.cloudControllerService = cc;
+    }
+	
+	public CloudControllerService getCloudControllerService() {
+        return cloudControllerService;
+    }
+
+	public UserRegistry getConfigRegistry() {
+        return configRegistry;
+    }
+
+    public void setConfigRegistry(UserRegistry configRegistry) {
+        this.configRegistry = configRegistry;
+    }
+    
+    public UserRegistry getGovernanceRegistry() {
+        return governanceRegistry;
+    }
+
+    public void setGovernanceRegistry(UserRegistry governanceRegistry) {
+        this.governanceRegistry = governanceRegistry;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory b/components/org.apache.stratos.mediator.autoscale/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
new file mode 100644
index 0000000..399d502
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
@@ -0,0 +1,2 @@
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleInMediatorFactory
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleOutMediatorFactory

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer b/components/org.apache.stratos.mediator.autoscale/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
new file mode 100644
index 0000000..05fce78
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
@@ -0,0 +1,2 @@
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleInMediatorSerializer
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleOutMediatorSerializer
\ No newline at end of file


[14/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/structure/Node.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/structure/Node.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/structure/Node.java
deleted file mode 100644
index 579eda5..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/structure/Node.java
+++ /dev/null
@@ -1,356 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.conf.structure;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.commons.lang.builder.HashCodeBuilder;
-
-/**
- * This is the basic data structure which holds a <i>Nginx</i> formatted configuration file.
- * 
- */
-public class Node implements Serializable{
-
-    private static final long serialVersionUID = 4071569903421115370L;
-
-    /**
-     * Name of this Node element
-     */
-    private String name;
-
-    /**
-     * Every node can have 0..n child nodes. 
-     * They are kept in a List.
-     */
-    private List<Node> childNodes = new ArrayList<Node>();
-
-    /**
-     * Every node can have 0..n properties. 
-     * They are kept in a Map, in the order they appear.
-     * Key: property name
-     * Value: property value
-     */
-    private Map<String, String> properties = new LinkedHashMap<String, String>();
-
-    public void setChildNodes(List<Node> childNodes) {
-        this.childNodes = childNodes;
-    }
-
-    public void setProperties(Map<String, String> properties) {
-        this.properties = properties;
-    }
-
-    /**
-     * This will convert each child Node of this Node to a String.
-     * @return a string which represents child nodes of this node.
-     */
-    public String childNodesToString(int indentation) {
-        StringBuilder childNodesString = new StringBuilder();
-        indentation++;
-        
-        for (Node node : childNodes) {
-            childNodesString.append(node.toString(indentation)+"\n");
-        }
-        
-        return childNodesString.toString();
-    }
-
-    /**
-     * This will try to find a child Node of this Node, which has the given name.
-     * @param name name of the child node to find.
-     * @return child Node object if found or else <code>null</code>.
-     */
-    public Node findChildNodeByName(String name) {
-        for (Node aNode : childNodes) {
-            if (aNode.getName().equals(name)) {
-                return aNode;
-            }
-        }
-
-        return null;
-    }
-
-    /**
-     * Returns the name of this Node. 
-     * @return name of the node.
-     */
-    public String getName() {
-        return name;
-    }
-
-    /**
-     * Returns child nodes List of this Node.
-     * @return List of Node
-     */
-    public List<Node> getChildNodes() {
-        return childNodes;
-    }
-
-    /**
-     * Returns properties Map of this Node.
-     * @return Map whose keys and values are String.  
-     */
-    public Map<String, String> getProperties() {
-        return properties;
-    }
-
-    /**
-     * Returns the value of a given property.
-     * @param key name of a property.
-     * @return trimmed value if the property is found in this Node, or else <code>null</code>. 
-     */
-    public String getProperty(String key) {
-        if (properties.get(key) == null) {
-            return null;
-        }
-        return properties.get(key).trim();
-    }
-
-    /**
-     * Returns all the properties of this Node as a String.
-     * Key and value of the property is separated by a tab (\t) character and
-     * each property is separated by a new line character.
-     * @param indentation relative number of tabs 
-     * @return properties of this node as a String.
-     */
-    public String propertiesToString(int indentation) {
-        
-        String indent = getIndentation(indentation);
-        
-        StringBuilder sb = new StringBuilder();
-        for (Map.Entry<String, String> entry : properties.entrySet()) {
-            // hack to get a quick fix in.
-            if (!"tenant_id".equals(entry.getKey()) && !"alias".equals(entry.getKey())) {
-                sb.append(indent + entry.getKey() + "\t" + entry.getValue() + ";\n");
-            }
-        }
-        return sb.toString();
-    }
-    
-    /**
-     * Removes the first occurrence of a node having the given name
-     * and returns the removed {@link Node}.
-     * @param name name of the child node to be removed.
-     * @return removed {@link Node} or else <code>null</code>.
-     */
-    public Node removeChildNode(String name) {
-        Node aNode = findChildNodeByName(name);
-        
-        if(aNode != null){
-            if(childNodes.remove(aNode)){
-                return aNode;
-            }
-        }
-        
-        return null;
-    }
-
-    /**
-     * Removes the first occurrence of a node equals to the given node.
-     * @param node {@link Node} to be removed.
-     * @return whether the removal is successful or not.
-     */
-    public boolean removeChildNode(Node node){
-
-        return childNodes.remove(node);
-    }
-    
-    /**
-     * Sets the name of this Node.
-     * @param name String to be set as the name.
-     */
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    /**
-     * Appends a child node at the end of the List of child nodes of this Node, if 
-     * a similar node is not already present as a child node.
-     * @param aNode child Node to be appended.
-     */
-    public void appendChild(Node aNode) {
-        if (aNode != null && !nodeAlreadyPresent(aNode)) {
-            childNodes.add(aNode);
-        }
-    }
-    
-    /**
-     * Adds a new property to properties Map of this Node if and only if 
-     * key is not <code>null</code>.
-     * @param key name of the property to be added.
-     * @param value value of the property to be added.
-     */
-    public void addProperty(String key, String value) {
-        if (key != null) {
-            properties.put(key, value);
-        }
-    }
-    
-    /**
-     * Convert this Node to a String which is in <i>Nginx</i> format.
-     * <br/>
-     * Sample:
-     * <br></br>
-     * <code>
-     * ij {
-     * <br/>
-     * klm n;
-     * <br/>
-     * pq {
-     * <br/>
-     * rst u;
-     * <br/>
-     * }
-     * <br/>
-     * }
-     * <br/>
-     * </code>
-     */
-    public String toString() {
-        
-        String nodeString = 
-                getName()+" {\n" +
-                (propertiesToString(1)) +
-                (childNodesToString(1)) +
-                "}";
-        
-        return nodeString;
-    }
-    
-    public boolean equals(Object node) {
-        
-        if(node instanceof Node){
-            return this.getName().equals(((Node) node).getName()) &&
-                    isIdenticalProperties(this.getProperties(), ((Node) node).getProperties()) &&
-                    isIdenticalChildren(this.getChildNodes(), ((Node) node).getChildNodes());
-        }
-        
-        return false;
-        
-    }
-    
-    public int hashCode() {
-        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
-            append(name).
-            append(properties).
-            append(childNodes).
-            toHashCode();
-    }
-    
-    private boolean isIdenticalChildren(List<Node> childNodes1, List<Node> childNodes2) {
-        
-        if(childNodes1.size() != childNodes2.size()){
-            return false;
-        }
-        
-        for (Node node1 : childNodes1) {
-            int i=0;
-            for (Node node2 : childNodes2) {
-                
-                i++;
-                if(node1.equals(node2)){
-                    break;
-                }
-                
-                if(i == childNodes1.size()){
-                    return false;
-                }
-                
-            }
-        }
-        
-        return true;
-    }
-    
-    private boolean nodeAlreadyPresent(Node aNode){
-        
-        for(Node node : this.childNodes){
-            if(node.equals(aNode)){
-                return true;
-            }
-        }
-        
-        return false;
-    }
-
-    private boolean isIdenticalProperties(Map<String, String> map1,
-        Map<String, String> map2) {
-        
-        if(map1.size() != map2.size()){
-            return false;
-        }
-        
-        for (Iterator<Entry<String, String>> iterator1 = map1.entrySet().iterator(); iterator1.hasNext();) {
-            Map.Entry<String, String> entry1 = (Map.Entry<String, String>) iterator1.next();
-            
-            int i=0;
-            
-            for(Iterator<Entry<String, String>> iterator2 = map2.entrySet().iterator(); iterator2.hasNext();) {
-                Map.Entry<String, String> entry2 = (Map.Entry<String, String>) iterator2.next();
-                
-                i++;
-                
-                if((entry1.getKey().equals(entry2.getKey()) &&
-                        entry1.getValue().equals(entry2.getValue()))){
-                    
-                    break;
-                }
-                
-                if(i == map1.size()){
-                    return false;
-                }
-                
-            }
-        }
-        
-        return true;
-    }
-
-    private String toString(int indentation){
-        
-        String indent = getIndentation(indentation-1);
-        
-        String nodeString = 
-                indent + getName()+" {\n" +
-                (propertiesToString(indentation)) +
-                (childNodesToString(indentation)) +
-                indent + "}";
-        
-        return nodeString;
-    }
-    
-    private String getIndentation(int tabs){
-        
-        StringBuilder indent = new StringBuilder("");
-        
-        for (int i = 0; i < tabs; i++) {
-            indent.append("\t");
-        }
-                
-        return indent.toString();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/structure/NodeBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/structure/NodeBuilder.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/structure/NodeBuilder.java
deleted file mode 100644
index 4801c1d..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/structure/NodeBuilder.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.conf.structure;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.common.conf.util.Constants;
-
-/**
- * This responsible for build up a Node object from a given content.
- * Every closing brace should be in a new line.
- */
-public class NodeBuilder {
-    
-    private static final Log log = LogFactory.getLog(NodeBuilder.class);
-
-    /**
-     * This method is useful when you do not have a root node in your content.
-     * @param aNode
-     *            Node object whose name set.
-     * @param content
-     *            should be something similar to following.
-     * 
-     *            abc d;
-     *            efg h;
-     *            # comment 
-     *            ij { # comment
-     *              klm n;
-     * 
-     *              pq {
-     *                  rst u;
-     *              }
-     *            }
-     * 
-     * @return fully constructed Node
-     */
-    public static Node buildNode(Node aNode, String content) {
-
-    	if(content == null || content.isEmpty()){
-    		return aNode;
-    	}
-    	
-        String[] lines = content.split("\n");
-
-        for (int i = 0; i < lines.length; i++) {
-            String line = lines[i].trim();
-
-            // avoid line comments
-            if (!line.startsWith(Constants.NGINX_COMMENT)) {
-                
-                // skip comments in-line 
-                if(line.contains(Constants.NGINX_COMMENT)){
-                    line = line.substring(0, line.indexOf(Constants.NGINX_COMMENT));
-                }
-                
-                // another node is detected and it is not a variable starting from $
-                if (line.contains(Constants.NGINX_NODE_START_BRACE) && 
-                        !line.contains(Constants.NGINX_VARIABLE)) {
-                    
-                    try {
-                        Node childNode = new Node();
-                        childNode.setName(line.substring(0, line.indexOf(Constants.NGINX_NODE_START_BRACE)).trim());
-
-                        StringBuilder sb = new StringBuilder();
-
-                        int matchingBraceTracker = 1;
-
-                        while (!line.contains(Constants.NGINX_NODE_END_BRACE) || matchingBraceTracker != 0) {
-                            i++;
-                            if (i == lines.length) {
-                                break;
-                            }
-                            line = lines[i];
-                            if (line.contains(Constants.NGINX_NODE_START_BRACE)) {
-                                matchingBraceTracker++;
-                            }
-                            if (line.contains(Constants.NGINX_NODE_END_BRACE)) {
-                                matchingBraceTracker--;
-                            }
-                            sb.append(line + "\n");
-                        }
-
-                        childNode = buildNode(childNode, sb.toString());
-						if (aNode == null) {
-							aNode = childNode;
-						} else {
-							aNode.appendChild(childNode);
-						}
-
-                    } catch (Exception e) {
-                        String msg = "Malformatted element is defined in the configuration file. [" +
-                                i + "] \n";
-                        log.error(msg , e);
-                        throw new RuntimeException(msg + line, e);
-                    }
-
-                }
-                // this is a property
-                else {
-                    if (!line.isEmpty() && !Constants.NGINX_NODE_END_BRACE.equals(line)) {
-                        String[] prop = line.split(Constants.NGINX_SPACE_REGEX);
-                        String value = line.substring(prop[0].length(), line.indexOf(Constants.NGINX_LINE_DELIMITER)).trim();
-                        try {
-                            aNode.addProperty(prop[0], value);
-                        } catch (Exception e) {
-                            String msg = "Malformatted property is defined in the configuration file. [" +
-                                    i + "] \n";
-                            log.error(msg, e);
-                            throw new RuntimeException(msg + line, e);
-                        }
-                    }
-                }
-            
-            }
-        }
-
-        return aNode;
-
-    }
-    
-    public static Node buildNode(String content) {
-	    return buildNode(null, content);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/Constants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/Constants.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/Constants.java
deleted file mode 100644
index 8cf6c2f..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/Constants.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.conf.util;
-
-/**
- * This keeps the element names used in loadbalancer.conf file
- */
-public class Constants {
-    
-    public static final String LOAD_BALANCER_ELEMENT = "loadbalancer";
-    public static final String SERVICES_ELEMENT = "services";
-    public static final String DEFAULTS_ELEMENT = "defaults";
-    public static final String HOSTS_ELEMENT = "hosts";
-    public static final String HOSTS_DELIMITER = ",";
-    public static final String DOMAIN_ELEMENT = "domains";
-    public static final String TENANT_RANGE_ELEMENT = "tenant_range";
-    public static final String SUB_DOMAIN_ELEMENT = "sub_domain";
-    public static final String TENANT_RANGE_DELIMITER = "-";
-    public static final String UNLIMITED_TENANT_RANGE = "*";
-    public static final String AUTOSCALER_ENABLE_ELEMENT = "enable_autoscaler";
-    public static final String SUB_DOMAIN_DELIMITER = "#";
-    public static final String DEFAULT_SUB_DOMAIN = "__$default";
-    
-    /* Nginx format related constants */
-    
-    public static final String NGINX_COMMENT = "#";
-    public static final String NGINX_NODE_START_BRACE = "{";
-    public static final String NGINX_NODE_END_BRACE = "}";
-    public static final String NGINX_VARIABLE = "${";
-    public static final String NGINX_LINE_DELIMITER = ";";
-    public static final String NGINX_SPACE_REGEX = "[\\s]+";
-    
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/HostContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/HostContext.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/HostContext.java
deleted file mode 100644
index d9ad14a..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/HostContext.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.conf.util;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.synapse.endpoints.algorithms.AlgorithmContext;
-import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
-
-/**
- * For each unique host name defined in loadbalancer configuration, we'll generate
- * this object. 
- */
-public class HostContext {
-    
-    /**
-     * A unique identifier to identify this {@link #HostContext()}
-     */
-    private String hostName;
-    
-    /**
-     * Key - tenant id
-     * Value - <code>TenantDomainContext</code> of the corresponding tenant
-     */
-    private Map<Integer, TenantDomainContext> tenantIdToTenantDomainContextMap = new HashMap<Integer, TenantDomainContext>();
-    
-    /**
-     * AlgorithmContext of this host
-     */
-    private AlgorithmContext algorithmContext;
-    
-    /**
-     * Load balance algorithm of this host
-     */
-    private LoadbalanceAlgorithm algorithm;
-    
-    private String urlSuffix;
-    
-    public HostContext(String hostName) {
-        this.hostName = hostName;
-    }
-    
-    public void addTenantDomainContexts(List<TenantDomainContext> ctxts) {
-        
-        for (TenantDomainContext tenantDomainContext : ctxts) {
-            tenantIdToTenantDomainContextMap.put(tenantDomainContext.getTenantId(), tenantDomainContext);
-        }
-    }
-    
-    @Deprecated
-    public void addTenantDomainContext(TenantDomainContext ctxt) {
-        tenantIdToTenantDomainContextMap.put(ctxt.getTenantId(), ctxt);
-    }
-    
-    public TenantDomainContext getTenantDomainContext(int tenantId) {
-        return tenantIdToTenantDomainContextMap.get(tenantId);
-    }
-    
-    /**
-     * Returns all the {@link TenantDomainContext} entries.
-     */
-    public Collection<TenantDomainContext> getTenantDomainContexts() {
-        return tenantIdToTenantDomainContextMap.values();
-    }
-    
-    /**
-     * Given a tenant id, this will return its domain.
-     * @param tenantId 
-     * @return domain if this tenant has a dedicated one, it will be returned.
-     * If not, and there's a default (*) domain, it will be returned.
-     * If neither of the above is defined, null will be returned.
-     */
-    public String getDomainFromTenantId(int tenantId) {
-        if (tenantIdToTenantDomainContextMap.get(tenantId) == null) {
-            // if there's no specific domain for this tenant, we will redirect it to the default
-            // cluster
-            
-            if(tenantIdToTenantDomainContextMap.get(0) == null){
-                return null;
-            }
-            
-            return tenantIdToTenantDomainContextMap.get(0).getDomain();
-        }
-
-        return tenantIdToTenantDomainContextMap.get(tenantId).getDomain();
-    }
-    
-    /**
-     * Given a tenant id, this will return its sub domain.
-     * @param tenantId 
-     * @return sub_domain if this tenant has a dedicated one, it will be returned.
-     * If not, and there's a default (*) sub domain, it will be returned.
-     * If neither of the above is defined, null will be returned.
-     */
-    public String getSubDomainFromTenantId(int tenantId) {
-        if (tenantIdToTenantDomainContextMap.get(tenantId) == null) {
-            // if there's no specific domain for this tenant, we will redirect it to the default
-            // cluster
-            
-            if(tenantIdToTenantDomainContextMap.get(0) == null){
-                return null;
-            }
-            
-            return tenantIdToTenantDomainContextMap.get(0).getSubDomain();
-        }
-
-        return tenantIdToTenantDomainContextMap.get(tenantId).getSubDomain();
-    }
-
-    public String getHostName() {
-        return hostName;
-    }
-    
-    public LoadbalanceAlgorithm getAlgorithm() {
-        return algorithm;
-    }
-
-    public AlgorithmContext getAlgorithmContext() {
-        return algorithmContext;
-    }
-
-    public void setAlgorithmContext(AlgorithmContext algorithmContext) {
-        this.algorithmContext = algorithmContext;
-    }
-
-    public void setAlgorithm(LoadbalanceAlgorithm algorithm) {
-        this.algorithm = algorithm;
-    }
-
-    public Map<Integer, TenantDomainContext> getTenantIdToTenantDomainContextMap() {
-        return tenantIdToTenantDomainContextMap;
-    }
-    
-    public void setUrlSuffix(String suffix)  {
-        this.urlSuffix = suffix;
-    }
-
-    public String getUrlSuffix() {
-        return this.urlSuffix;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/LoadBalancerConfigUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/LoadBalancerConfigUtil.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/LoadBalancerConfigUtil.java
deleted file mode 100644
index 61eceb4..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/LoadBalancerConfigUtil.java
+++ /dev/null
@@ -1,291 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.conf.util;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.SynapseException;
-import sun.misc.BASE64Encoder;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Utility methods for Autoscale mediator
- */
-public final class LoadBalancerConfigUtil {
-
-    private static final Log log = LogFactory.getLog(LoadBalancerConfigUtil.class);
-
-    private LoadBalancerConfigUtil() {
-    }
-
-    /**
-     * handles the exception
-     * 
-     * @param msg
-     *            exception message
-     */
-    public static void handleException(String msg) {
-        log.error(msg);
-        throw new RuntimeException(msg);
-    }
-
-    /**
-     * handles the exception
-     * 
-     * @param msg
-     *            exception message
-     * @param e
-     *            exception
-     */
-    public static void handleException(String msg, Exception e) {
-        log.error(msg, e);
-        throw new SynapseException(msg, e);
-    }
-
-    /**
-     * Replaces the variables
-     * 
-     * @param text
-     *            input string
-     * @return output String
-     */
-    public static String replaceVariables(String text) {
-        int indexOfStartingChars;
-        int indexOfClosingBrace;
-
-        // The following condition deals with properties.
-        // Properties are specified as ${system.property},
-        // and are assumed to be System properties
-        if ((indexOfStartingChars = text.indexOf("${")) != -1 &&
-            (indexOfClosingBrace = text.indexOf("}")) != -1) { // Is a property used?
-            String var = text.substring(indexOfStartingChars + 2, indexOfClosingBrace);
-
-            String propValue = System.getProperty(var);
-            if (propValue == null) {
-                propValue = System.getenv(var);
-            }
-            if (propValue != null) {
-                text =
-                       text.substring(0, indexOfStartingChars) + propValue +
-                               text.substring(indexOfClosingBrace + 1);
-            }
-        }
-        return text;
-    }
-
-    public static String getUserData(String payloadFileName) {
-        String userData = null;
-        try {
-            File file = new File(payloadFileName);
-            if (!file.exists()) {
-                handleException("Payload file " + payloadFileName + " does not exist");
-            }
-            if (!file.canRead()) {
-                handleException("Payload file " + payloadFileName + " does cannot be read");
-            }
-            byte[] bytes = LoadBalancerConfigUtil.getBytesFromFile(file);
-            if (bytes != null) {
-                BASE64Encoder encoder = new BASE64Encoder();
-                userData = encoder.encode(bytes);
-            }
-        } catch (Exception e) {
-            LoadBalancerConfigUtil.handleException("Cannot read data from payload file " +
-                                                   payloadFileName, e);
-
-        }
-        return userData;
-    }
-
-    /**
-     * Returns the contents of the file in a byte array
-     * 
-     * @param file
-     *            - Input File
-     * @return Bytes from the file
-     * @throws java.io.IOException
-     *             , if retrieving the file contents failed.
-     */
-    public static byte[] getBytesFromFile(File file) throws IOException {
-        if (!file.exists()) {
-            log.error("Payload file " + file.getAbsolutePath() + " does not exist");
-            return null;
-        }
-        InputStream is = new FileInputStream(file);
-        byte[] bytes;
-
-        try {
-            // Get the size of the file
-            long length = file.length();
-
-            // You cannot create an array using a long type.
-            // It needs to be an int type.
-            // Before converting to an int type, check
-            // to ensure that file is not larger than Integer.MAX_VALUE.
-            if (length > Integer.MAX_VALUE) {
-                if (log.isDebugEnabled()) {
-                    log.debug("File is too large");
-                }
-            }
-
-            // Create the byte array to hold the data
-            bytes = new byte[(int) length];
-
-            // Read in the bytes
-            int offset = 0;
-            int numRead;
-            while (offset < bytes.length &&
-                   (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
-                offset += numRead;
-            }
-
-            // Ensure all the bytes have been read in
-            if (offset < bytes.length) {
-                throw new IOException("Could not completely read file " + file.getName());
-            }
-        } finally {
-            // Close the input stream and return bytes
-            is.close();
-        }
-
-        return bytes;
-    }
-
-    /**
-     * @deprecated
-     *             Extract the domain part given a string which is in
-     *             &lt;sub_domain&gt;#&lt;domain&gt; format.
-     * @param str
-     *            in &lt;sub_domain&gt;#&lt;domain&gt; format.
-     * @return the domain part. If # is not present this will return the trimmed
-     *         input string.
-     */
-    public static String getDomain(String str) {
-        str = str.trim();
-        if (!str.contains(Constants.SUB_DOMAIN_DELIMITER)) {
-            return str;
-        }
-        return str.substring(str.indexOf(Constants.SUB_DOMAIN_DELIMITER) + 1);
-    }
-
-    /**
-     * @deprecated
-     *             Extract the sub_domain part given a string which is in
-     *             &lt;sub_domain&gt;#&lt;domain&gt; format.
-     * @param str
-     *            in &lt;sub_domain&gt;#&lt;domain&gt; format.
-     * @return the sub_domain part. If # is not present this will return <code>null</code>.
-     */
-    public static String getSubDomain(String str) {
-        str = str.trim();
-        if (!str.contains(Constants.SUB_DOMAIN_DELIMITER)) {
-            return null;
-        }
-        return str.substring(0, str.indexOf(Constants.SUB_DOMAIN_DELIMITER));
-    }
-
-    // public static EC2InstanceManager createEC2InstanceManager(String accessKey,
-    // String secretKey,
-    // String instanceMgtEPR) {
-    // AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
-    // AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentials);
-    // ec2Client.setEndpoint(instanceMgtEPR);
-    // return new EC2InstanceManager(ec2Client);
-    // }
-
-    public static List<TenantDomainContext> getTenantDomainContexts(String tenantRange, String domain, String subDomain) {
-        
-        List<TenantDomainContext> ctxts = new ArrayList<TenantDomainContext>();
-        List<Integer> tenantIds = getTenantIds(tenantRange);
-        
-        // iterate through all tenant ids under this host
-        for (Integer tId : tenantIds) {
-
-            // create a new TenantDomainContext
-            TenantDomainContext tenantCtxt =
-                                             new TenantDomainContext(
-                                                                     tId,
-                                                                     domain,
-                                                                     subDomain);
-            // add it to the list
-            ctxts.add(tenantCtxt);
-        }
-        
-        return ctxts;
-        
-    }
-    
-    /**
-     * This method will read the tenant range string and return a list of tenant ids
-     * which is derived from tenant range string.
-     * 
-     * @param tenantRange
-     * @return list of tenant ids.
-     */
-    public static List<Integer> getTenantIds(String tenantRange) {
-
-        List<Integer> tenantIds = new ArrayList<Integer>();
-
-        String[] parsedLine = tenantRange.trim().split("-");
-
-        if (parsedLine[0].equalsIgnoreCase("*")) {
-            tenantIds.add(0);
-
-        } else if (parsedLine.length == 1) {
-            try {
-                int tenantId = Integer.parseInt(tenantRange);
-                tenantIds.add(tenantId);
-
-            } catch (NumberFormatException e) {
-                String msg = "Invalid tenant range is specified : " + tenantRange;
-                log.error(msg, e);
-                throw new RuntimeException(msg, e);
-            }
-        } else if (parsedLine.length == 2) {
-            try {
-
-                int startIndex = Integer.parseInt(parsedLine[0]);
-                int endIndex = Integer.parseInt(parsedLine[1]);
-
-                for (int tenantId = startIndex; tenantId <= endIndex; tenantId++) {
-
-                    tenantIds.add(tenantId);
-                }
-
-            } catch (NumberFormatException e) {
-                String msg = "Invalid tenant range is specified : " + tenantRange;
-                log.error(msg, e);
-                throw new RuntimeException(msg, e);
-            }
-
-        } else {
-            String msg = "Invalid tenant range is specified : " + tenantRange;
-            log.error(msg);
-            throw new RuntimeException(msg);
-        }
-
-        return tenantIds;
-    }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/TenantDomainContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/TenantDomainContext.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/TenantDomainContext.java
deleted file mode 100644
index 65a4b45..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/util/TenantDomainContext.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.conf.util;
-
-/**
- * This object will hold all the data related to a tenant.
- */
-public class TenantDomainContext {
-    
-    /**
-     * this is the unique identifier for this object
-     */
-    private int tenantId;
-    
-    /**
-     * Domain, which this tenant belongs to.
-     */
-    private String domain;
-    
-    /**
-     * Sub domain, which this tenant belongs to.
-     */
-    private String subDomain;
-    
-    public TenantDomainContext(int tenantId, String domain, String subDomain) {
-        this.tenantId = tenantId;
-        this.domain = domain;
-        this.subDomain = subDomain;
-    }
-    
-    
-    /** Getters and Setters **/
-
-    public int getTenantId() {
-        return tenantId;
-    }
-
-    public void setTenantId(int tenantId) {
-        this.tenantId = tenantId;
-    }
-
-    public String getDomain() {
-        return domain;
-    }
-
-    public void setDomain(String domain) {
-        this.domain = domain;
-    }
-
-    public String getSubDomain() {
-        return subDomain;
-    }
-
-    public void setSubDomain(String subDomain) {
-        this.subDomain = subDomain;
-    }
-    
-    
-    /** End of Getters and Setters **/
-    
-    
-    
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
deleted file mode 100644
index 4341728..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.group.mgt;
-
-import org.apache.axis2.clustering.Member;
-import org.apache.axis2.clustering.management.DefaultGroupManagementAgent;
-import org.apache.synapse.endpoints.dispatch.SALSessions;
-import org.apache.stratos.lb.common.conf.util.Constants;
-
-/**
- * This GroupManagementAgent can handle group membership based on cluster sub-domains.
- */
-public class SubDomainAwareGroupManagementAgent extends DefaultGroupManagementAgent {
-
-    private String subDomain;
-
-    public SubDomainAwareGroupManagementAgent(String subDomain) {
-        this.subDomain = subDomain;
-    }
-
-    @Override
-    public void applicationMemberAdded(Member member) {
-        String subDomain = member.getProperties().getProperty("subDomain");
-        if ((subDomain == null && Constants.DEFAULT_SUB_DOMAIN.equals(this.subDomain)) ||
-            subDomain.equals(this.subDomain)) {
-            super.applicationMemberAdded(member);
-        }
-    }
-
-    @Override
-    public void applicationMemberRemoved(Member member) {
-        
-        // remove the sessions bound with this member
-        SALSessions.getInstance().removeSessionsOfMember(member);
-        
-        String subDomain = member.getProperties().getProperty("subDomain");
-        if ((subDomain == null && Constants.DEFAULT_SUB_DOMAIN.equals(this.subDomain)) ||
-            subDomain.equals(this.subDomain)) {
-            super.applicationMemberRemoved(member);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java
deleted file mode 100644
index 5d26a2c..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.replication;
-
-import org.apache.axis2.clustering.ClusteringCommand;
-import org.apache.axis2.clustering.ClusteringFault;
-import org.apache.axis2.clustering.ClusteringMessage;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.util.Map;
-
-/**
- * This is the notification message a primary load balancer will send to all other load balancers
- * in the cluster, to replicate its state. When the other load balancers received this message, 
- * they will set their states to the state of primary load balancer.
- */
-public class RequestTokenReplicationCommand extends ClusteringMessage {
-
-    private static final long serialVersionUID = -7897961078018830555L;
-    private static final Log log = LogFactory.getLog(RequestTokenReplicationCommand.class);
-    private Map<String, Map<String, ?>> appDomainContexts;
-
-    public Map<String, Map<String, ?>> getAppDomainContexts() {
-        return appDomainContexts;
-    }
-
-    public void setAppDomainContexts(Map<String, Map<String, ?>> appDomainContexts) {
-        this.appDomainContexts = appDomainContexts;
-    }
-
-    public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
-        // set the appDomainContexts map
-        configurationContext.setNonReplicableProperty("autoscale.app.domain.contexts",
-                                          getAppDomainContexts());
-        
-        log.info("Request Tokens Replicated! ");
-    }
-
-    public String toString() {
-        return "Replication message sent!";
-    }
-
-    @Override
-    public ClusteringCommand getResponse() {
-        return new ClusteringCommand() {
-            
-            private static final long serialVersionUID = -8271265673996681347L;
-
-            @Override
-            public void execute(ConfigurationContext arg0) throws ClusteringFault {
-                // do nothing
-            }
-        };
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java
deleted file mode 100644
index 5958ad9..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.service;
-
-import org.apache.stratos.lb.common.conf.util.HostContext;
-
-import java.util.Map;
-
-/**
- * This service provides a way to consume details in loadbalancer.conf file.
- * Also to update the runtime object model of loadbalancer conf.
- */
-public interface LoadBalancerConfigurationService {
-
-    /**
-     * Provides a reference to the runtime object model of loadbalancer.conf
-     * @return {@link Object} which is an instance of {@link org.apache.stratos.lb.common.conf.LoadBalancerConfiguration}
-     */
-    public Object getLoadBalancerConfig();
-    
-//    /**
-//     * Return a {@link Map} of {@link HostContext} objects, built using the given config.
-//     * @param config service configuration.
-//     * @return {@link Map} {@link Object}
-//     */
-//    public Object getHostContext(String config);
-    
-    /**
-     * Return a {@link Map} of {@link HostContext} objects, built using the given configuration.
-     * @param config service configuration diff. This can be in following format.
-     * 
-     * <p/>
-     * appserver {
-     * hosts                   appserver.cloud-test.wso2.com;
-     * domains   {
-     * 		wso2.as1.domain {
-     * 			tenant_range    1-100;
-     * 		}
-     *		wso2.as2.domain {
-     * 			tenant_range    101-200;
-     * 		}
-     * 		wso2.as3.domain {
-     *	 		tenant_range    *;
-     * 		}
-     * 	}
-     * } 
-     * <p/>
-     * esb {
-     * hosts                   esb.cloud-test.wso2.com;
-     * domains   {
-     * 		wso2.esb.domain {
-     *	 		tenant_range    *;
-     * 		}
-     * 	}
-     * }
-     * <p/>
-     * @return a {@link Map} of {@link HostContext} objects.
-     * key - host name
-     * Value - {@link HostContext}
-     */
-    public Object getHostContexts(String config) ;
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
deleted file mode 100644
index 99c2ced..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.service.impl;
-
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.structure.Node;
-import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
-import org.apache.stratos.lb.common.conf.util.Constants;
-import org.apache.stratos.lb.common.conf.util.HostContext;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
-
-import java.util.Map;
-
-public class LoadBalancerConfigurationServiceImpl implements LoadBalancerConfigurationService {
-
-    @Override
-    public Object getLoadBalancerConfig() {
-        return LoadBalancerConfiguration.getInstance();
-    }
-
-	@Override
-    public Object getHostContexts(String config) {
-
-		// build a Node object for whole loadbalancer.conf
-        Node rootNode = new Node();
-        rootNode.setName(Constants.SERVICES_ELEMENT);
-        rootNode = NodeBuilder.buildNode(rootNode, config);
-		
-        Map<String, HostContext> oldMap = LoadBalancerConfiguration.getInstance().getHostContextMap();
-        LoadBalancerConfiguration.getInstance().createServicesConfig(rootNode);
-        
-//        MapDifference<String, HostContext> diff = Maps.difference(LoadBalancerConfiguration.getInstance().getHostContextMap(),
-//                                                             oldMap );
-//		
-//		return diff.entriesOnlyOnLeft();
-        return LoadBalancerConfiguration.getInstance().getHostContextMap();
-    }
-
-//	@Override
-//    public Object getHostContext(String config) {
-//	    return null;
-//    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java
deleted file mode 100644
index 7355833..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.util;
-
-/**
- *
- */
-public class DomainMapping {
-    private String mapping;
-    private String actualHost;
-
-    public DomainMapping(String mapping) {
-        this.mapping = mapping;
-    }
-
-    public String getActualHost() {
-        return actualHost;
-    }
-
-    public void setActualHost(String actualHost) {
-        this.actualHost = actualHost;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.lb.common/4.1.3/src/main/resources/META-INF/services.xml
deleted file mode 100644
index 6d1f398..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<serviceGroup>
-    <service name="LoadBalancerConfigurationService" scope="application">
-        <parameter name="ServiceClass">org.wso2.stratos.lb.common.service.impl.LoadBalancerConfigurationServiceImpll</parameter>
-        <messageReceivers>
-        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
-        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
-    </messageReceivers>
-    </service>
-</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java b/components/org.apache.stratos.lb.common/4.1.3/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java
deleted file mode 100644
index 4efbbd2..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.test;
-
-import java.io.File;
-
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.apache.stratos.lb.common.conf.util.HostContext;
-
-import junit.framework.TestCase;
-
-public class LoadBalancerConfigurationTest extends TestCase {
-    
-    private LoadBalancerConfiguration lbConfig ;
-    private LoadBalancerConfiguration lbConfig1;
-    
-    
-    @Override
-    protected void setUp() throws Exception {
-
-        LoadBalancerConfiguration.setInstance(null);
-        File f = new File("src/test/resources/loadbalancer.conf");
-        System.setProperty("loadbalancer.conf", f.getAbsolutePath());
-        lbConfig = LoadBalancerConfiguration.getInstance();
-    }
-    
-    public final void testCreateLoadBalancerConfig() {
-
-        LoadBalancerConfiguration.LBConfiguration loadBalancerConfig =
-            lbConfig.getLoadBalancerConfig();
-        
-        assertEquals(1, loadBalancerConfig.getInstances());
-        assertEquals(5000, loadBalancerConfig.getAutoscalerTaskInterval());
-        assertEquals(15000, loadBalancerConfig.getServerStartupDelay());
-    }
-
-    public final void testCreateServicesConfig() {
-
-        /* Tests relavant to loadbalancer.conf file */
-        
-        ServiceConfiguration asServiceConfig =
-                                               lbConfig.getServiceConfig("wso2.as1.domain",
-                                                                         "worker");
-
-        assertEquals(1, asServiceConfig.getInstancesPerScaleUp());
-        assertEquals(5, asServiceConfig.getMaxAppInstances());
-        assertEquals(0, asServiceConfig.getMinAppInstances());
-        assertEquals(60000, asServiceConfig.getMessageExpiryTime());
-        assertEquals(400, asServiceConfig.getMaxRequestsPerSecond());
-        assertEquals(0.65, asServiceConfig.getAlarmingUpperRate());
-        assertEquals(10, asServiceConfig.getRoundsToAverage());
-        assertEquals("worker", asServiceConfig.getSubDomain());
-
-        asServiceConfig = lbConfig.getServiceConfig("wso2.as2.domain", "worker1");
-        assertEquals("worker1", asServiceConfig.getSubDomain());
-
-        asServiceConfig = lbConfig.getServiceConfig("wso2.esb.domain", "mgt");
-        assertEquals("mgt", asServiceConfig.getSubDomain());
-
-        assertEquals(2, lbConfig.getHostNamesTracker().keySet().size());
-        assertEquals(3, lbConfig.getHostNamesTracker().get("appserver").size());
-        assertEquals(2, lbConfig.getHostNamesTracker().get("esb").size());
-
-        for (HostContext ctx : lbConfig.getHostContextMap().values()) {
-
-            if (ctx.getHostName().equals("appserver.cloud-test.wso2.com")) {
-
-                assertEquals("nirmal", ctx.getSubDomainFromTenantId(30));
-                assertEquals(18, ctx.getTenantDomainContexts().size());
-            } else if (ctx.getHostName().equals("as2.cloud-test.wso2.com")) {
-                assertEquals("worker", ctx.getSubDomainFromTenantId(2));
-            } else if (ctx.getHostName().equals("esb.cloud-test.wso2.com")) {
-                assertEquals("mgt", ctx.getSubDomainFromTenantId(5));
-            }
-        }
-        
-        /* tests relevant to loadbalancer1.conf file */
-        
-        File f = new File("src/test/resources/loadbalancer2.conf");
-        System.setProperty("loadbalancer.conf", f.getAbsolutePath());
-        
-        LoadBalancerConfiguration.setInstance(null);
-        lbConfig1 = LoadBalancerConfiguration.getInstance();
-        
-        for (HostContext ctx : lbConfig1.getHostContextMap().values()) {
-
-            if (ctx.getHostName().equals("appserver.cloud-test.wso2.com")) {
-
-                assertEquals("nirmal", ctx.getSubDomainFromTenantId(30));
-                assertEquals("wso2.as1.domain", ctx.getDomainFromTenantId(5));
-                assertEquals("wso2.as.domain", ctx.getDomainFromTenantId(8));
-                assertEquals("wso2.as.domain", ctx.getDomainFromTenantId(2));
-                assertEquals(4, ctx.getTenantDomainContexts().size());
-                
-            } else if (ctx.getHostName().equals("esb.cloud-test.wso2.com")) {
-                
-                assertEquals("mgt", ctx.getSubDomainFromTenantId(5));
-            }
-        }
-
-    }
-
-    public final void testGetServiceDomains() throws Exception {
-
-        setUp();
-        String[] serviceDomains = lbConfig.getServiceDomains();
-        assertEquals(4, serviceDomains.length);
-        
-        assertTrue("wso2.as1.domain".equals(serviceDomains[0]) ||
-            "wso2.as1.domain".equals(serviceDomains[1]) ||
-            "wso2.as1.domain".equals(serviceDomains[2]) ||
-            "wso2.as1.domain".equals(serviceDomains[3]));
-        
-        assertTrue("wso2.as2.domain".equals(serviceDomains[0]) ||
-            "wso2.as2.domain".equals(serviceDomains[1]) ||
-            "wso2.as2.domain".equals(serviceDomains[2]) ||
-            "wso2.as2.domain".equals(serviceDomains[3]));
-        
-        assertTrue("wso2.as3.domain".equals(serviceDomains[0]) ||
-            "wso2.as3.domain".equals(serviceDomains[1]) ||
-            "wso2.as3.domain".equals(serviceDomains[2]) ||
-            "wso2.as3.domain".equals(serviceDomains[3]));
-        
-        assertTrue("wso2.esb.domain".equals(serviceDomains[0]) ||
-                   "wso2.esb.domain".equals(serviceDomains[1]) ||
-                   "wso2.esb.domain".equals(serviceDomains[2]) ||
-                   "wso2.esb.domain".equals(serviceDomains[3]));
-        
-    }
-    
-    public final void testGetServiceSubDomains() throws Exception {
-
-        setUp();
-        String[] serviceSubDomains = lbConfig.getServiceSubDomains("wso2.as3.domain");
-        assertEquals(2, serviceSubDomains.length);
-        
-        assertTrue("nirmal".equals(serviceSubDomains[0]) ||
-            "nirmal".equals(serviceSubDomains[1]));
-        
-        assertTrue("nirmal2".equals(serviceSubDomains[0]) ||
-            "nirmal2".equals(serviceSubDomains[1]));
-        
-        serviceSubDomains = lbConfig.getServiceSubDomains("wso2.esb.domain");
-        assertEquals(2, serviceSubDomains.length);
-        
-        serviceSubDomains = lbConfig.getServiceSubDomains("wso2.as1.domain");
-        assertEquals(1, serviceSubDomains.length);
-        
-        
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java b/components/org.apache.stratos.lb.common/4.1.3/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java
deleted file mode 100644
index e3b2f5e..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.test;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-import org.apache.stratos.lb.common.conf.structure.Node;
-import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
-
-public class NodeBuilderTest extends TestCase {
-
-    String content;
-
-    public void setUp() throws Exception {
-    }
-
-    public final void testBuildNode() {
-
-        // Testing a node only has properties
-        Node a = new Node();
-        a.setName("loadbalancer");
-
-        content =
-            "securityGroups      stratos-appserver-lb;\ninstanceType        m1.large;\n"
-                + "instances           1;\nelasticIP           ${ELASTIC_IP};\n"
-                + "availabilityZone    us-east-1c;\npayload             /mnt/payload.zip;";
-
-        a = NodeBuilder.buildNode(a, content);
-
-        Assert.assertEquals("loadbalancer", a.getName());
-        Assert.assertEquals("stratos-appserver-lb", a.getProperty("securityGroups"));
-        Assert.assertEquals("${ELASTIC_IP}", a.getProperty("elasticIP"));
-        Assert.assertEquals("/mnt/payload.zip", a.getProperty("payload"));
-        Assert.assertNull(a.getProperty("payloader"));
-
-        // Testing a node has sub nodes and properties
-        a = new Node();
-        a.setName("appserver");
-
-        content =
-            "hosts                   appserver.cloud-test.wso2.com,as.cloud-test.wso2.com;\n"
-                + "domains   {\n" + "wso2.as1.domain {\n" + "tenant_range    1-100;\n" + "}\n"
-                + "wso2.as2.domain {\n" + "tenant_range    101-200;\n" + "}\n"
-                + "wso2.as3.domain { # domain\n" + "tenant_range    *;\n" + "}\n" + "}\n"
-                + "# line comment \n"
-                + "payload                 resources/cluster_node.zip;# payload\n"
-                + "availability_zone       us-east-1c;\n";
-
-        a = NodeBuilder.buildNode(a, content);
-
-        Assert.assertEquals("appserver", a.getName());
-        Assert.assertEquals(1, a.getChildNodes().size());
-        Assert.assertEquals("domains", a.getChildNodes().get(0).getName());
-        Assert.assertEquals("appserver.cloud-test.wso2.com,as.cloud-test.wso2.com",
-                            a.getProperty("hosts"));
-        Assert.assertEquals("resources/cluster_node.zip", a.getProperty("payload"));
-        Assert.assertEquals(null, a.getProperty("payloader"));
-
-        Node b = a.getChildNodes().get(0);
-
-        Assert.assertEquals(3, b.getChildNodes().size());
-        Assert.assertEquals(null, b.getProperty("payload"));
-
-        Node c = b.getChildNodes().get(0);
-
-        Assert.assertEquals(0, c.getChildNodes().size());
-        Assert.assertEquals("1-100", c.getProperty("tenant_range"));
-
-        c = b.getChildNodes().get(2);
-
-        Assert.assertEquals(0, c.getChildNodes().size());
-        Assert.assertEquals("*", c.getProperty("tenant_range"));
-        
-        String nodeStr = "appserver {\n" +
-                "\thosts\tappserver.cloud-test.wso2.com,as.cloud-test.wso2.com;\n" +
-                "\tpayload\tresources/cluster_node.zip;\n" +
-        		"\tavailability_zone\tus-east-1c;\n" +
-        		"\tdomains {\n" +
-        		"\t\twso2.as1.domain {\n" +
-        		"\t\t\ttenant_range\t1-100;\n" +
-        		"\t\t}\n" +
-        		"\t\twso2.as2.domain {\n" +
-        		"\t\t\ttenant_range\t101-200;\n" +
-        		"\t\t}\n" +
-        		"\t\twso2.as3.domain {\n" +
-        		"\t\t\ttenant_range\t*;\n" +
-        		"\t\t}\n" +
-        		"\t}\n" +
-        		"}";
-        
-        assertEquals(nodeStr, a.toString());
-        
-        // test equals method
-        assertEquals(true, a.equals(a));
-        assertEquals(false, a.equals(b));
-        assertEquals(false, c.equals(b));
-        
-        // test buildNode(String)
-        c = NodeBuilder.buildNode(nodeStr);
-        
-        assertEquals(c.getName(), "appserver");
-        assertEquals(c.getChildNodes().size(), 1);
-        assertEquals(c.getProperty("availability_zone"), "us-east-1c");
-
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer.conf b/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer.conf
deleted file mode 100644
index b2fd44f..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer.conf
+++ /dev/null
@@ -1,64 +0,0 @@
-loadbalancer {
-    instances	1;
-    enable_autoscaler	true;
-    # interval between two task executions in milliseconds
-    autoscaler_task_interval	5000;
-    # after an instance booted up, task will wait till this much of time and let the server started up
-    server_startup_delay		15000; #default will be 60000ms
-}
-
-services {
-    defaults {
-        min_app_instances 1;
-        max_app_instances       5;
-        max_requests_per_second   400;
-        alarming_upper_rate 0.65;
-        alarming_lower_rate 0.2;
-        scale_down_factor 0.25;
-        rounds_to_average       10;
-        instances_per_scale_up  1;
-        message_expiry_time     60000;
-    }
-
-    appserver {
-        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
-        sub_domain      worker1;
-        domains   {
-            wso2.as1.domain {
-            	hosts as2.cloud-test.wso2.com;
-            	  min_app_instances   0;
-            	  sub_domain      worker;
-                tenant_range    1-5;
-            }
-            wso2.as2.domain {
-                tenant_range    7;
-            }
-            wso2.as3.domain {
-                sub_domain nirmal;
-                tenant_range    10-20;
-            }
-            
-            wso2.as3.domain {
-                sub_domain nirmal2;
-                tenant_range    21-25;
-            }
-            
-            wso2.esb.domain {
-            	sub_domain nirmal;
-                tenant_range    *;
-            }
-        }
-    }
-    
-    esb {
-        hosts                   esb.cloud-test.wso2.com,mgt.as.cloud-test.wso2.com;
-        domains   {
-            wso2.esb.domain {
-                sub_domain      mgt;
-                tenant_range    *;
-            }
-        }
-    }
-
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer1.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer1.conf b/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer1.conf
deleted file mode 100644
index 8b87a32..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer1.conf
+++ /dev/null
@@ -1,39 +0,0 @@
-loadbalancer {
-    instances	1;
-    enable_autoscaler	true;
-    # interval between two task executions in milliseconds
-    autoscaler_task_interval	5000;
-    # after an instance booted up, task will wait till this much of time and let the server started up
-    server_startup_delay		15000; #default will be 60000ms
-}
-
-services {
-
-    appserver {
-        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
-        sub_domain      worker1;
-        domains   {
-            
-            wso2.as.domain {
-            	sub_domain nirmal;
-                tenant_range    *;
-            }
-            wso2.as1.domain {
-            	sub_domain nirmal;
-                tenant_range    5-7;
-            }
-        }
-    }
-    
-    esb {
-        hosts                   esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
-        domains   {
-            wso2.esb.domain {
-                sub_domain      mgt;
-                tenant_range    *;
-            }
-        }
-    }
-
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer2.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer2.conf b/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer2.conf
deleted file mode 100644
index 718d881..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/loadbalancer2.conf
+++ /dev/null
@@ -1,30 +0,0 @@
-services {
-
-    appserver {
-        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
-        sub_domain      worker1;
-        domains   {
-            
-            wso2.as.domain {
-            	sub_domain nirmal;
-                tenant_range    *;
-            }
-            wso2.as1.domain {
-            	sub_domain nirmal;
-                tenant_range    5-7;
-            }
-        }
-    }
-    
-    esb {
-        hosts                   esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
-        domains   {
-            wso2.esb.domain {
-                sub_domain      mgt;
-                tenant_range    *;
-            }
-        }
-    }
-
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/testng.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/testng.xml b/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/testng.xml
deleted file mode 100644
index 44b9822..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/test/resources/testng.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Default suite">
-  <test verbose="2" name="Default test">
-    <classes>
-      <!--class name="org.wso2.carbon.lb.common.test.AgentPersistenceManagerTest">
-          <methods>
-            <include name="addZone" />
-              <include name="addHostMachine" />
-              <include name="deleteHostMachine" />
-          </methods>
-      </class-->
-    </classes>
-  </test>
-</suite>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/pom.xml b/components/org.apache.stratos.lb.common/pom.xml
new file mode 100644
index 0000000..9c8a19d
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/pom.xml
@@ -0,0 +1,118 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.apache.stratos</groupId>
+    <artifactId>org.apache.stratos.lb.common</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos Loadbalancer - Common</name>
+    <url>http://apache.org</url>
+    
+    <dependencies>
+    	<dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>com.google.guava.wso2</groupId>
+	        <artifactId>guava</artifactId>
+            <version>${google.guava.wso2.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-core</artifactId>
+            <version>${synapse.core.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>${junit.version}</version>
+        </dependency>
+        <!--dependency>
+          <groupId>org.testng</groupId>
+          <artifactId>testng</artifactId>
+          <version>6.3.1</version>
+          <scope>test</scope>
+        </dependency-->
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.logging</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <!--dependency>
+        	<groupId>mysql</groupId>
+        	<artifactId>mysql-connector-java</artifactId>
+        	<version>5.1.6</version>
+        </dependency-->
+        <!-- This mysql dependency is required for tests-->
+    </dependencies>
+
+    <build>
+        <plugins>
+            <!--plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <version>2.12</version>
+                <configuration>
+                  <suiteXmlFiles>
+                    <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
+                  </suiteXmlFiles>
+                </configuration>
+              </plugin-->
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.apache.stratos.lb.common.*,
+                        </Export-Package>
+                        <Private-Package>
+                        	org.apache.stratos.lb.common.conf.internal;
+                        </Private-Package>
+                        <Import-Package>
+                            !org.apache.commons.logging,
+                            org.apache.commons.logging; version=0.0.0,
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/cache/LRUCache.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/cache/LRUCache.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/cache/LRUCache.java
new file mode 100644
index 0000000..342430c
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/cache/LRUCache.java
@@ -0,0 +1,103 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.cache;
+
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+/**
+ * A simple, thread-safe LRU cache implementation. This cache allows concurrent reads.
+ * Concurrent write attempts are synchronized using an exclusive lock.
+ */
+public class LRUCache<K,V> extends LinkedHashMap<K,V> {
+
+    private static final long serialVersionUID = 5901026458782787628L;
+    private int maxEntries;
+    private ReadWriteLock lock;
+
+    public LRUCache(int maxEntries) {
+        super(maxEntries + 1, 1, false);
+        this.maxEntries = maxEntries;
+        this.lock = new ReentrantReadWriteLock();
+    }
+
+    @Override
+    public V get(Object key) {
+        lock.readLock().lock();
+        try {
+            return super.get(key);
+        } finally {
+            lock.readLock().unlock();
+        }
+    }
+
+    @Override
+    public V put(K key, V value) {
+        lock.writeLock().lock();
+        try {
+            return super.put(key, value);
+        } finally {
+            lock.writeLock().unlock();
+        }
+    }
+
+    @Override
+    public V remove(Object key) {
+        lock.writeLock().lock();
+        try {
+            return super.remove(key);
+        } finally {
+            lock.writeLock().unlock();
+        }
+    }
+
+    @Override
+    public void clear() {
+        lock.writeLock().lock();
+        try {
+            super.clear();
+        } finally {
+            lock.writeLock().unlock();
+        }
+    }
+
+    @Override
+    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
+        boolean remove = size() > maxEntries;
+        if (remove) {
+            handleRemovableEntry(eldest);
+        }
+        return remove;
+    }
+
+    protected void handleRemovableEntry(Map.Entry<K,V> entry) {
+
+    }
+
+    public void exclusiveLock() {
+        lock.writeLock().lock();
+    }
+
+    public void release() {
+        lock.writeLock().unlock();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/cache/URLMappingCache.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/cache/URLMappingCache.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/cache/URLMappingCache.java
new file mode 100644
index 0000000..3c23efc
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/cache/URLMappingCache.java
@@ -0,0 +1,47 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.cache;
+
+import org.apache.stratos.lb.common.util.DomainMapping;
+import java.util.Map;
+
+public class URLMappingCache {
+    private Map<String,DomainMapping> validMappings;
+
+    private static URLMappingCache instance = null;
+    protected URLMappingCache(int maxValidKeys) {
+        validMappings = new LRUCache<String, DomainMapping>(maxValidKeys);
+    }
+
+    public void addValidMapping(String hostName, DomainMapping mapping) {
+        validMappings.put(hostName, mapping);
+    }
+
+    public DomainMapping getMapping(String hostName) {
+        return validMappings.get(hostName);
+    }
+
+    public static URLMappingCache getInstance(int maxValidKeys) {
+      if(instance == null) {
+
+         instance = new URLMappingCache(maxValidKeys);
+      }
+      return instance;
+   }
+}


[40/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
deleted file mode 100644
index 05f987d..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
+++ /dev/null
@@ -1,524 +0,0 @@
-/*
- * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * WSO2 Inc. licenses this file to you under the Apache License,
- * Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License.
- * You may obtain a copy of the License at
- * 
- * http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.task;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.ClusteringFault;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.callables.InstanceCountCallable;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.ManagedLifecycle;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
-import org.apache.synapse.task.Task;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.mediator.autoscale.lbautoscale.callables.AppNodeSanityCheckCallable;
-import org.apache.stratos.mediator.autoscale.lbautoscale.callables.AutoscaleDeciderCallable;
-import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerOsgiClient;
-import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerStubClient;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
-import org.apache.stratos.lb.common.replication.RequestTokenReplicationCommand;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-
-/**
- * Service request in flight autoscaler task for Stratos service level auto-scaling
- */
-public class ServiceRequestsInFlightAutoscaler implements Task, ManagedLifecycle {
-
-    private static final Log log = LogFactory.getLog(ServiceRequestsInFlightAutoscaler.class);
-
-    /**
-     * This instance holds the loadbalancer configuration
-     */
-    private LoadBalancerConfiguration loadBalancerConfig;
-
-    /**
-     * Autoscaler service client instance
-     */
-    private CloudControllerClient autoscalerService;
-
-    /**
-     * AppDomainContexts for each domain
-     * Key - domain
-     * Value - Map of key - sub domain
-     * value - {@link AppDomainContext}
-     */
-    private Map<String, Map<String, ?>> appDomainContexts =
-        new HashMap<String, Map<String, ?>>();
-
-    /**
-     * LB Context for LB cluster
-     */
-    private final LoadBalancerContext lbContext = new LoadBalancerContext();
-
-    /**
-     * Attribute to keep track whether this instance is the primary load balancer.
-     */
-    private boolean isPrimaryLoadBalancer;
-
-    /**
-     * Keeps track whether this task is still running
-     */
-    private boolean isTaskRunning;
-    
-    /**
-     * Thread pool used in this task to execute parallel tasks.
-     */
-    private ExecutorService executor = Executors.newFixedThreadPool(100);
-
-    /**
-     * Check that all app nodes in all clusters meet the minimum configuration
-     */
-    private void appNodesSanityCheck() {
-        
-        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
-        
-        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
-            
-            String msg =
-                    "Sanity check is failed to run. No Appdomain context is generated for the" +
-                        " domain " + serviceDomain;
-            
-            // get the list of service sub_domains specified in loadbalancer config
-            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
-
-            for (String serviceSubDomain : serviceSubDomains) {
-                log.debug("Sanity check has started for: "+AutoscaleUtil.domainSubDomainString(serviceDomain, serviceSubDomain));
-                AppDomainContext appCtxt;
-                if (appDomainContexts.get(serviceDomain) != null) {
-                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
-                    
-                    if (appCtxt != null) {
-                        // Concurrently perform the application node sanity check.
-                        Callable<Boolean> worker =
-                            new AppNodeSanityCheckCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
-                        Future<Boolean> appNodeSanityCheck = executor.submit(worker);
-                        jobList.add(appNodeSanityCheck);
-
-                    } else{
-                        log.error(msg + " and sub domain " + serviceSubDomain + " combination.");
-                    }
-                } else{
-                    log.error(msg);
-                }
-            }
-        }
-        
-        // Retrieve the results of the concurrently performed sanity checks.
-        for (Future<Boolean> job : jobList) {
-            try {
-                job.get();
-            } catch (Exception ignore) {
-                log.error(ignore.getMessage(), ignore);
-                // no need to throw
-            } 
-        }
-
-    }
-
-    /**
-     * Autoscale the entire system, analyzing the requests in flight of each domain - sub domain
-     */
-    private void autoscale() {
-        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
-
-        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
-
-            String msg =
-                "Autoscaler check is failed to run. No Appdomain context is generated for the" +
-                    " domain " + serviceDomain;
-
-            // get the list of service sub_domains specified in loadbalancer config
-            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
-
-            for (String serviceSubDomain : serviceSubDomains) {
-
-                log.debug("Autoscaling analysis is starting to run for domain: " + serviceDomain +
-                    " and sub domain: " + serviceSubDomain);
-
-                AppDomainContext appCtxt;
-                if (appDomainContexts.get(serviceDomain) != null) {
-                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
-
-                    if (appCtxt != null) {
-
-                        // Concurrently make the auto-scaling decisions
-                        Callable<Boolean> worker =
-                            new AutoscaleDeciderCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
-                        Future<Boolean> autoscalerDeciderCheck = executor.submit(worker);
-                        jobList.add(autoscalerDeciderCheck);
-
-                    } else {
-                        log.error(msg + " and sub domain " + serviceSubDomain + " combination.");
-                    }
-                } else {
-                    log.error(msg);
-                }
-            }
-        }
-
-        // Retrieve the results of the concurrently performed sanity checks.
-        for (Future<Boolean> job : jobList) {
-            try {
-                job.get();
-            } catch (Exception ignore) {
-                log.error(ignore.getMessage(), ignore);
-                // no need to throw
-            }
-        }
-    }
-
-    /**
-     * We compute the number of running instances of a particular domain using clustering agent.
-     */
-    private void computeRunningAndPendingInstances() {
-
-        int runningInstances = 0, pendingInstances = 0;
-
-        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
-
-        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
-
-            // get the list of service sub_domains specified in loadbalancer config
-            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
-
-            for (String serviceSubDomain : serviceSubDomains) {
-
-                AppDomainContext appCtxt;
-                if (appDomainContexts.get(serviceDomain) != null) {
-                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
-                    
-                    log.debug("Values in App domain context: " +
-                        appCtxt.getPendingInstanceCount() +
-                            " - " +
-                            appCtxt.getRunningInstanceCount() +
-                            " - Ctxt: " +
-                            appCtxt.hashCode());
-
-                    if (appCtxt != null) {
-                        Callable<Boolean> worker =
-                            new InstanceCountCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
-                        Future<Boolean> countInstancesJob = executor.submit(worker);
-                        jobList.add(countInstancesJob);
-                    }
-                }
-            }
-        }
-
-        for (Future<Boolean> job : jobList) {
-            try {
-                job.get();
-            } catch (Exception ignore) {
-                log.error(ignore.getMessage(), ignore);
-                // no need to throw
-            }
-        }
-
-        /* Calculate running load balancer instances */
-
-        // count this LB instance in.
-        runningInstances = 1;
-
-        runningInstances += AutoscalerTaskDSHolder.getInstance().getAgent().getAliveMemberCount();
-
-        lbContext.setRunningInstanceCount(runningInstances);
-
-        if (AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("domain") == null) {
-            String msg = "Clustering Agent's domain parameter is null. Please specify a domain" +
-                " name in axis2.xml of Elastic Load Balancer.";
-            log.error(msg);
-            throw new RuntimeException(msg);
-        }
-
-        String lbDomain = AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("domain").getValue().toString();
-
-        String lbSubDomain = null;
-
-        if (AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("subDomain") != null) {
-            lbSubDomain =
-                AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("subDomain").getValue().toString();
-        }
-
-        // reset
-        pendingInstances = 0;
-        try {
-            pendingInstances = lbContext.getPendingInstanceCount();
-        } catch (Exception e) {
-            log.error(e.getMessage(), e);
-            // no need to throw
-        }
-
-        lbContext.setPendingInstanceCount(pendingInstances);
-
-        log.debug("Load Balancer members of domain: " +
-            lbDomain +
-            " and sub domain: " +
-            lbSubDomain +
-            " running instances (including this): " +
-            runningInstances +
-            " - pending instances: "
-            +
-            pendingInstances);
-
-    }
-
-    @Override
-    public void destroy() {
-        appDomainContexts.clear();
-        log.debug("Cleared AppDomainContext Map.");
-    }
-
-    /**
-     * This is method that gets called periodically when the task runs.
-     * <p/>
-     * The exact sequence of execution is shown in this method.
-     */
-    @Override
-    public void execute() {
-
-        appDomainContexts =
-            AutoscaleUtil.getAppDomainContexts(
-                AutoscalerTaskDSHolder.getInstance().getConfigCtxt(),
-                loadBalancerConfig);
-
-        if (isTaskRunning) {
-            log.debug("Task is already running!");
-            return;
-        }
-        try {
-            isTaskRunning = true;
-            setIsPrimaryLB();
-            if (!isPrimaryLoadBalancer) {
-                log.debug("This is not the primary load balancer, hence will not " +
-                        "perform any sanity check.");
-                return;
-            }
-            sanityCheck();
-            autoscale();
-        } finally {
-            // if there are any changes in the request length
-            if (Boolean.parseBoolean(System.getProperty(AutoscaleConstants.IS_TOUCHED))) {
-                // primary LB will send out replication message to all load balancers
-                sendReplicationMessage();
-            }
-            isTaskRunning = false;
-            log.debug("Task finished a cycle.");
-        }
-    }
-
-    @Override
-    public void init(final SynapseEnvironment synEnv) {
-
-        String msg = "Autoscaler Service initialization failed and cannot proceed.";
-
-        loadBalancerConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
-
-        if (loadBalancerConfig == null) {
-            log.error(msg + "Reason: Load balancer configuration is null.");
-            throw new RuntimeException(msg);
-        }
-
-        ConfigurationContext configCtx = ((Axis2SynapseEnvironment) synEnv).getAxis2ConfigurationContext();
-        AutoscalerTaskDSHolder.getInstance().setConfigCtxt(configCtx);
-
-        appDomainContexts = AutoscaleUtil.getAppDomainContexts(configCtx, loadBalancerConfig);
-        
-        AutoscalerTaskDSHolder.getInstance().setAgent(configCtx.getAxisConfiguration().getClusteringAgent());
-
-        boolean useEmbeddedAutoscaler = loadBalancerConfig.getLoadBalancerConfig().useEmbeddedAutoscaler();
-        
-        try {
-
-            if(useEmbeddedAutoscaler){
-                autoscalerService = new CloudControllerOsgiClient();
-            } else{
-                autoscalerService = new CloudControllerStubClient();
-            }
-            // let's initialize the auto-scaler service
-            autoscalerService.init();
-
-        }catch (Exception e) {
-            log.error(msg, e);
-            throw new RuntimeException(msg, e);
-        }
-
-        if (log.isDebugEnabled()) {
-
-            log.debug("Autoscaler task is initialized.");
-
-        }
-    }
-
-    /**
-     * Sanity check to see whether the number of LBs is the number specified in the LB config
-     */
-    private void loadBalancerSanityCheck() {
-
-        log.debug("Load balancer sanity check has started.");
-
-        // get current LB instance count
-        int currentLBInstances = lbContext.getInstances();
-
-        LoadBalancerConfiguration.LBConfiguration lbConfig =
-            loadBalancerConfig.getLoadBalancerConfig();
-
-        // get minimum requirement of LB instances
-        int requiredInstances = lbConfig.getInstances();
-
-        if (currentLBInstances < requiredInstances) {
-            log.debug("LB Sanity check failed. Running/Pending LB instances: " + currentLBInstances +
-                ". Required LB instances: " + requiredInstances);
-            int diff = requiredInstances - currentLBInstances;
-
-            // gets the domain of the LB
-            String lbDomain =
-                AutoscalerTaskDSHolder
-                    .getInstance()
-                    .getAgent()
-                    .getParameter("domain")
-                    .getValue()
-                    .toString();
-            String lbSubDomain =
-                AutoscalerTaskDSHolder
-                    .getInstance()
-                    .getAgent()
-                    .getParameter("subDomain")
-                    .getValue()
-                    .toString();
-
-            // Launch diff number of LB instances
-            log.debug("Launching " + diff + " LB instances.");
-
-            runInstances(lbContext, lbDomain, lbSubDomain, diff);
-        }
-    }
-
-    private int runInstances(final LoadBalancerContext context, final String domain,
-        final String subDomain,
-        int diff) {
-
-        int successfullyStartedInstanceCount = diff;
-
-        while (diff > 0) {
-            // call autoscaler service and ask to spawn an instance
-            // and increment pending instance count only if autoscaler service returns
-            // true.
-            try {
-                String ip = autoscalerService.startInstance(domain, subDomain);
-
-                if (ip == null || ip.isEmpty()) {
-                    log.debug("Instance start up failed. domain: " +
-                        domain +
-                            ", sub domain: " +
-                            subDomain);
-                    successfullyStartedInstanceCount--;
-                } else {
-                    log.debug("An instance of domain: " +
-                        domain +
-                            " and sub domain: " +
-                            subDomain +
-                            " is started up.");
-                    if (context != null) {
-                        context.incrementPendingInstances(1);
-                    }
-                }
-            } catch (Exception e) {
-                log.error("Failed to start an instance of sub domain: " + subDomain +
-                    " of domain : " + domain + ".\n", e);
-                successfullyStartedInstanceCount--;
-            }
-
-            diff--;
-        }
-
-        return successfullyStartedInstanceCount;
-    }
-
-    /**
-     * This method makes sure that the minimum configuration of the clusters in the system is
-     * maintained
-     */
-    private void sanityCheck() {
-
-        if (!isPrimaryLoadBalancer) {
-            log.debug("This is not the primary load balancer, hence will not " +
-                "perform any sanity check.");
-            return;
-        }
-
-        log.debug("This is the primary load balancer, starting to perform sanity checks.");
-
-        computeRunningAndPendingInstances();
-        loadBalancerSanityCheck();
-        appNodesSanityCheck();
-    }
-
-    /**
-     * Replicate information needed to take autoscaling decision for other ELBs
-     * in the cluster.
-     */
-    private void sendReplicationMessage() {
-
-        ClusteringAgent clusteringAgent = AutoscalerTaskDSHolder.getInstance().getAgent();
-        if (clusteringAgent != null) {
-            RequestTokenReplicationCommand msg = new RequestTokenReplicationCommand();
-            msg.setAppDomainContexts(appDomainContexts);
-            try {
-                clusteringAgent.sendMessage(msg, true);
-                System.setProperty(AutoscaleConstants.IS_TOUCHED, "false");
-                log.debug("Request token replication messages sent out successfully!!");
-
-            } catch (ClusteringFault e) {
-                log.error("Failed to send the request token replication message.", e);
-            }
-        }
-        else {
-            log
-                .debug("Clustering Agent is null. Hence, unable to send out the replication message.");
-        }
-    }
-
-    /**
-     * This method will check whether this LB is the primary LB or not and set
-     * attribute accordingly.
-     */
-    private void setIsPrimaryLB() {
-
-        ClusteringAgent clusteringAgent = AutoscalerTaskDSHolder.getInstance().getAgent();
-        if (clusteringAgent != null) {
-
-            isPrimaryLoadBalancer = clusteringAgent.isCoordinator();
-
-        }
-
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
deleted file mode 100644
index b97deb4..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.task;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.task.TaskDescription;
-import org.apache.synapse.task.TaskDescriptionRepository;
-import org.apache.synapse.task.TaskScheduler;
-import org.wso2.carbon.task.TaskManager;
-
-import java.util.Iterator;
-import java.util.Map;
-
-public class TaskSchedulingManager {
-
-    private static final Log log = LogFactory.getLog(TaskSchedulingManager.class);
-
-    private static TaskSchedulingManager thisInstance = new TaskSchedulingManager();
-
-    public static TaskSchedulingManager getInstance() {
-        return thisInstance;
-    }
-
-    /**
-     * This method adds a particular Task to the Task Description Repository and schedule it
-     * for the execution.
-     *
-     * @param taskDescription      TaskDescription
-     * @param resources            Map containing require meta data for the task execution.
-     * @param configurationContext ConfigurationContext
-     */
-    public void scheduleTask(TaskDescription taskDescription, Map<String, Object> resources,
-                             ConfigurationContext configurationContext) {
-        if (log.isDebugEnabled()) {
-            log.debug("Adding a Task Description to the Task Description Repository");
-        }
-
-        getTaskDescriptionRepository(configurationContext).addTaskDescription(taskDescription);
-        getTaskScheduler(configurationContext).scheduleTask(
-                taskDescription, resources, AutoscalingJob.class);
-
-        if (log.isDebugEnabled()) {
-            log.debug("Task Description " + taskDescription.getName() +
-                    " added to the Task Description Repository");
-        }
-    }
-
-    /**
-     * Returns a Task Description with a given name from the Task Description Repository.
-     *
-     * @param taskName             taskName
-     * @param configurationContext ConfigurationContext
-     * @return TaskDescription
-     */
-    public TaskDescription getTaskDescription(
-            String taskName, ConfigurationContext configurationContext) {
-        if (log.isDebugEnabled()) {
-            log.debug("Returning a Start up : " + taskName + " from the configuration");
-        }
-
-        TaskDescription taskDescription = getTaskDescriptionRepository(
-                configurationContext).getTaskDescription(taskName);
-
-        if (taskDescription != null) {
-            if (log.isDebugEnabled()) {
-                log.debug("Returning a Task Description : " + taskDescription);
-
-            }
-            return taskDescription;
-        } else {
-            if (log.isDebugEnabled()) {
-                log.debug("No Task Description can be found with name :" + taskName);
-            }
-            return null;
-        }
-    }
-
-    /**
-     * This method search for a given Task which has already been added to the Task Description
-     * Repository and removes it.
-     *
-     * @param taskDescription             TaskDescription
-     * @param configurationContext ConfigurationContext
-     */
-    public void deleteTaskDescription(TaskDescription taskDescription, ConfigurationContext configurationContext) {
-        String taskName = null;
-        if (taskDescription != null) {
-            taskName = taskDescription.getName();
-            getTaskDescriptionRepository(configurationContext).removeTaskDescription(taskName);
-            getTaskScheduler(configurationContext).deleteTask(taskName, taskDescription.getGroup());
-
-            if (log.isDebugEnabled()) {
-                log.debug("Deleted TaskDescription : " + taskName + " from the configuration");
-            }
-        } else {
-            log.warn("Unable to delete the Task " + taskName
-                    + ",as it doesn't exist in the Repository");
-        }
-    }
-
-    /**
-     * Retrieves all Task Descriptions added to the Task Description Repository at a given instance.
-     *
-     * @param configurationContext ConfigurationContext
-     * @return TaskDescription Iterator
-     */
-    public Iterator<TaskDescription> getAllTaskDescriptions(
-            ConfigurationContext configurationContext) {
-        if (log.isDebugEnabled()) {
-            log.debug("Returning a All TaskDescription from the configuration");
-        }
-        return getTaskDescriptionRepository(configurationContext).getAllTaskDescriptions();
-    }
-
-    /**
-     * This method checks whether a particular Task has already been added to the Task Description
-     * Repository associated with the context of this execution and returns a flag indicating the
-     * existence.
-     *
-     * @param taskName             Name of the task to be searched
-     * @param configurationContext ConfigurationContext
-     * @return a boolean depending on the existence of a task
-     */
-    public boolean isContains(String taskName, ConfigurationContext configurationContext) {
-        return !getTaskDescriptionRepository(configurationContext).isUnique(taskName);
-    }
-
-    /**
-     * Returns the Carbon TaskDescriptionRepository instance that carries details of the added
-     * tasks for execution.
-     *
-     * @param configurationContext ConfigurationContext
-     * @return TaskDescriptionRepository
-     */
-    private synchronized TaskDescriptionRepository getTaskDescriptionRepository(
-            ConfigurationContext configurationContext) {
-        if (log.isDebugEnabled()) {
-            log.debug("Retrieving access to Task Description Repository");
-        }
-        return (TaskDescriptionRepository) configurationContext.getProperty(
-                TaskManager.CARBON_TASK_REPOSITORY);
-    }
-
-    /**
-     * Returns the carbon TaskScheduler associated with the context of scheduling the task execution
-     *
-     * @param configurationContext ConfigurationContext
-     * @return TaskScheduler
-     */
-    private synchronized TaskScheduler getTaskScheduler(ConfigurationContext configurationContext) {
-        if (log.isDebugEnabled()) {
-            log.debug("Retrieving access to Task Scheduler");
-        }
-        return (TaskScheduler) configurationContext.getProperty(
-                TaskManager.CARBON_TASK_SCHEDULER);
-    }
-
-    public void shutDown(ConfigurationContext configurationContext) {
-        if (log.isDebugEnabled()) {
-            log.debug("Starting to shut down tasks");
-        }
-
-//        getTaskDescriptionRepository(configurationContext).addTaskDescription(taskDescription);
-        getTaskScheduler(configurationContext).shutDown();
-
-        if (log.isDebugEnabled()) {
-            log.debug("All tasks shut down");
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
deleted file mode 100644
index ed549c3..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.util;
-
-/**
- * Constants
- */
-public final class AutoscaleConstants {
-    public static final String REQUEST_ID = "request.id";
-    public static final String APP_DOMAIN_CONTEXTS = "autoscale.app.domain.contexts";
-    public static final String TARGET_DOMAIN = "autoscale.target.domain";
-    public static final String TARGET_SUB_DOMAIN = "autoscale.target.sub.domain";
-    public static final String LOAD_BALANCER_CONFIG = "loadbalancer.conf";
-    
-    /**
-     * we use this to track the changes happen to request token list lengths.
-     */
-    public static final String IS_TOUCHED = "is_touched";
-    
-    /**
-     * We'll check whether a server is started up in every this much of time.
-     * (in milliseconds)
-     */
-    public static final int SERVER_START_UP_CHECK_TIME = 30000;
-    
-    /**
-     * We'll check whether an instance is left the cluster in every this much of time.
-     * (in milliseconds)
-     */
-    public static final int INSTANCE_REMOVAL_CHECK_TIME = 5000;
-
-    /**
-     * Name of the EC2 instance tag which if set on an instance, the autoscaler will not
-     * terminate such instance
-     */
-    public static final String AVOID_TERMINATION = "avoidTermination";
-
-    public static enum InstanceState {
-        RUNNING("running"), PENDING("pending"), TERMINATED("terminated"), SHUTTING_DOWN("shutting-down");
-
-        private String state;
-
-        InstanceState(String state) {
-            this.state = state;
-        }
-
-        public String getState() {
-            return state;
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
deleted file mode 100644
index 747d3a2..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
+++ /dev/null
@@ -1,359 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.util;
-
-import org.apache.axiom.om.util.Base64;
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.http.protocol.HTTP;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
-import org.apache.stratos.mediator.autoscale.lbautoscale.state.check.PendingInstancesStateChecker;
-import org.apache.synapse.MessageContext;
-import org.apache.synapse.SynapseException;
-import org.apache.synapse.core.axis2.Axis2MessageContext;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Utility methods for Autoscale mediator
- */
-public final class AutoscaleUtil {
-
-    private static final Log log = LogFactory.getLog(AutoscaleUtil.class);
-
-    private AutoscaleUtil() {
-    }
-
-    /**
-     * handles the exception
-     *
-     * @param msg exception message
-     */
-    public static void handleException(String msg) {
-        log.error(msg);
-        throw new SynapseException(msg);
-    }
-
-    /**
-     * handles the exception
-     *
-     * @param msg exception message
-     * @param e   exception
-     */
-    public static void handleException(String msg, Exception e) {
-        log.error(msg, e);
-        throw new SynapseException(msg, e);
-    }
-
-    /**
-     * Returns the contents of the file in a byte array
-     *
-     * @param file - Input File
-     * @return Bytes from the file
-     * @throws java.io.IOException, if retrieving the file contents failed.
-     */
-    public static byte[] getBytesFromFile(File file) throws IOException {
-        if (!file.exists()) {
-            log.error("Payload file " + file.getAbsolutePath() + " does not exist");
-            return null;
-        }
-        InputStream is = new FileInputStream(file);
-        byte[] bytes;
-
-        try {
-            // Get the size of the file
-            long length = file.length();
-
-            // You cannot create an array using a long type.
-            // It needs to be an int type.
-            // Before converting to an int type, check
-            // to ensure that file is not larger than Integer.MAX_VALUE.
-            if (length > Integer.MAX_VALUE) {
-                if (log.isDebugEnabled()) {
-                    log.debug("File is too large");
-                }
-            }
-
-            // Create the byte array to hold the data
-            bytes = new byte[(int) length];
-
-            // Read in the bytes
-            int offset = 0;
-            int numRead;
-            while (offset < bytes.length
-                   && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
-                offset += numRead;
-            }
-
-            // Ensure all the bytes have been read in
-            if (offset < bytes.length) {
-                throw new IOException("Could not completely read file " + file.getName());
-            }
-        } finally {
-            // Close the input stream and return bytes
-            is.close();
-        }
-
-        return bytes;
-    }
-
-    /**
-     * Replaces the variables
-     *
-     * @param text input string
-     * @return output String
-     */
-    public static String replaceVariables(String text) {
-        int indexOfStartingChars;
-        int indexOfClosingBrace;
-
-        // The following condition deals with properties.
-        // Properties are specified as ${system.property},
-        // and are assumed to be System properties
-        if ((indexOfStartingChars = text.indexOf("${")) != -1 &&
-            (indexOfClosingBrace = text.indexOf("}")) != -1) { // Is a property used?
-            String var = text.substring(indexOfStartingChars + 2,
-                                        indexOfClosingBrace);
-
-            String propValue = System.getProperty(var);
-            if (propValue == null) {
-                propValue = System.getenv(var);
-            }
-            if (propValue != null) {
-                text = text.substring(0, indexOfStartingChars) + propValue +
-                       text.substring(indexOfClosingBrace + 1);
-            }
-        }
-        return text;
-    }
-
-/*    public static InstanceManager createEC2InstanceManager(String accessKey,
-                                                              String secretKey,
-                                                              String instanceMgtEPR) {
-        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
-        AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentials);
-        ec2Client.setEndpoint(instanceMgtEPR);
-        return new InstanceManager(ec2Client);
-    }*/
-
-    public static String getUserData(String payloadFileName) {
-        String userData = null;
-        try {
-            File file = new File(payloadFileName);
-            if (!file.exists()) {
-                handleException("Payload file " + payloadFileName + " does not exist");
-            }
-            if (!file.canRead()) {
-                handleException("Payload file " + payloadFileName + " does cannot be read");
-            }
-            byte[] bytes = AutoscaleUtil.getBytesFromFile(file);
-            if (bytes != null) {
-//                /BASE64.e encoder = new BASE64Encoder();
-                userData = Base64.encode(bytes);
-            }
-        } catch (IOException e) {
-            AutoscaleUtil.handleException("Cannot read data from payload file " + payloadFileName,
-                                          e);
-        }
-        return userData;
-    }
-
-    /*public static boolean areEqual(List<GroupIdentifier> securityGroups1, String[] sourceGroups2) {
-        for (String sourceGroup : sourceGroups2) {
-            boolean isSourceGroupFound = false;
-            for (GroupIdentifier securityGroup : securityGroups1) {
-                if (securityGroup.getGroupName().equals(sourceGroup)) {
-                    isSourceGroupFound = true;
-                }
-            }
-            if (!isSourceGroupFound) {
-                return false;
-            }
-        }
-        return true;
-    } */
-
-    /**
-     * TODO These methods should use to common place since these are using endpoints and mediators
-     */
-    public static int getTenantId(String url) {
-        String address = url;
-        String servicesPrefix = "/t/";
-        if (address != null && address.contains(servicesPrefix)) {
-            int domainNameStartIndex =
-                    address.indexOf(servicesPrefix) + servicesPrefix.length();
-            int domainNameEndIndex = address.indexOf('/', domainNameStartIndex);
-            String domainName = address.substring(domainNameStartIndex,
-                    domainNameEndIndex == -1 ? address.length() : domainNameEndIndex);
-            // return tenant id if domain name is not null
-            if (domainName != null) {
-                try {
-                    return AutoscalerTaskDSHolder.getInstance().getRealmService().getTenantManager().getTenantId(domainName);
-                } catch (org.wso2.carbon.user.api.UserStoreException e) {
-                    log.error("An error occurred while obtaining the tenant id.", e);
-                }
-            }
-        }
-        // return 0 if the domain name is null
-        return 0;
-    }
-
-    /**
-     * TODO These methods should use to common place since these are using endpoints and mediators
-     */
-    @SuppressWarnings("unchecked")
-    public static String getTargetHost(MessageContext synCtx) {
-        org.apache.axis2.context.MessageContext axis2MessageContext =
-                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
-        Map<String, String> headers =
-                (Map<String, String>) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
-        String address = headers.get(HTTP.TARGET_HOST);
-        if (address.contains(":")) {
-            address = address.substring(0, address.indexOf(":"));
-        }
-        return address;
-    }
-
-    @SuppressWarnings("unchecked")
-    public static Map<String, Map<String, ?>> getAppDomainContexts(ConfigurationContext configCtx,
- LoadBalancerConfiguration lbConfig) {
-        Map<String, Map<String, ?>> oldAppDomainContexts =
-        	(Map<String, Map<String, ?>>) configCtx.getPropertyNonReplicable(AutoscaleConstants.APP_DOMAIN_CONTEXTS);
-        Map<String, Map<String, ?>> newAppDomainContexts = new HashMap<String, Map<String, ?>>();
-        
-            ClusteringAgent clusteringAgent = configCtx.getAxisConfiguration().getClusteringAgent();
-
-            for (String domain : lbConfig.getServiceDomains()) {
-
-                for (String subDomain : lbConfig.getServiceSubDomains(domain)) {
-                    if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
-                        throw new SynapseException("Axis2 clustering GroupManagementAgent for domain: " + domain +
-                                                   ", sub-domain: " + subDomain +
-                                                   " has not been defined");
-                    }
-
-                    if(oldAppDomainContexts == null || oldAppDomainContexts.get(domain) == null || 
-                    		(oldAppDomainContexts.get(domain) != null && oldAppDomainContexts.get(domain).get(subDomain) == null)){
-                    	
-                    	AppDomainContext appCtxt = new AppDomainContext(lbConfig.getServiceConfig(domain,
-                                subDomain));
-
-                    	addAppDomainContext(newAppDomainContexts, domain, subDomain, appCtxt);
-                    	
-                    } else {
-                        addAppDomainContext(newAppDomainContexts, domain, subDomain, (AppDomainContext) oldAppDomainContexts.get(domain).get(subDomain));
-                    }
-                    
-                }
-
-            }
-//        }
-        configCtx.setNonReplicableProperty(AutoscaleConstants.APP_DOMAIN_CONTEXTS,
-                                           newAppDomainContexts);
-
-        return newAppDomainContexts;
-    }
-    
-    
-    private static void addAppDomainContext(Map<String, Map<String, ?>> appDomainContexts,
-                                     String domain, String subDomain, AppDomainContext appCtxt) {
-
-        Map<String, AppDomainContext> map ;
-        
-        if(appDomainContexts.containsKey(domain)){
-            map = (Map<String, AppDomainContext>) appDomainContexts.get(domain);
-        }
-        else{
-            map = new HashMap<String, AppDomainContext>();
-        }
-        // put this appDomainContext
-        map.put(subDomain, appCtxt);
-        
-        // update the parent map
-        appDomainContexts.put(domain, map);
-        
-    }
-    
-    public static String domainSubDomainString(String domain, String subDomain){
-        return "Domain: "+domain+" - Sub Domain: "+subDomain;
-    }
-    
-    public static int runInstances(final CloudControllerClient client, final LoadBalancerContext context, final String domain,
-        final String subDomain, int diff) {
-
-        int successfullyStartedInstanceCount = diff;
-
-        if(context == null){
-            // can't help
-            return 0;
-        }
-        
-        while (diff > 0) {
-            // call autoscaler service and ask to spawn an instance
-            // and increment pending instance count only if autoscaler service returns
-            // true.
-            try {
-                String ip = client.startInstance(domain, subDomain);
-
-                if (ip == null || ip.isEmpty()) {
-                    log.debug("Instance start up failed for " + domainSubDomainString(domain, subDomain));
-                    successfullyStartedInstanceCount--;
-                    
-                } else {
-                    log.debug("An instance of " + domainSubDomainString(domain, subDomain) +
-                        " is started up.");
-                    if (context != null) {
-                        context.incrementPendingInstances(1);
-                    }
-                }
-            } catch (Exception e) {
-                log.error("Failed to start an instance of " + domainSubDomainString(domain, subDomain) + ".\n", e);
-                successfullyStartedInstanceCount--;
-            }
-
-            diff--;
-        }
-
-        if (successfullyStartedInstanceCount > 0) {
-            
-            Thread stateChecker =
-                new Thread(new PendingInstancesStateChecker(
-                    context,
-                    domain,
-                    subDomain,
-                    successfullyStartedInstanceCount,
-                    context.getRunningInstanceCount(),
-                    client));
-            stateChecker.start();
-        }
-
-        return successfullyStartedInstanceCount;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
deleted file mode 100644
index 7e27b83..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale.util;
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.LBConfiguration;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-/**
- * Singleton class to hold Agent Management Service
- */
-public class AutoscalerTaskDSHolder {
-    
-    private ConfigurationContextService configurationContextService;
-    private LoadBalancerConfiguration wholeLbConfig;
-    private CloudControllerService cloudControllerService;  
-
-    private RealmService realmService;
-    private ClusteringAgent agent;
-    private ConfigurationContext configCtxt;
-    private UserRegistry configRegistry;
-    private UserRegistry governanceRegistry;
-
-    private static AutoscalerTaskDSHolder instance = new AutoscalerTaskDSHolder();
-
-    private AutoscalerTaskDSHolder(){
-
-    }
-
-    public static AutoscalerTaskDSHolder getInstance(){
-        return instance;
-    }
-
-    public ConfigurationContextService getConfigurationContextServiceService(){
-        return this.configurationContextService;
-    }
-
-    public void setConfigurationContextService(ConfigurationContextService cCtxService){
-        this.configurationContextService = cCtxService;
-    }
-    
-    public LoadBalancerConfiguration getWholeLoadBalancerConfig() {
-        return wholeLbConfig;
-    }
-    
-    public LBConfiguration getLoadBalancerConfig() {
-        return wholeLbConfig.getLoadBalancerConfig();
-    }
-
-    public ClusteringAgent getAgent() {
-        return agent;
-    }
-
-    public void setAgent(ClusteringAgent agent) {
-        this.agent = agent;
-    }
-
-
-    public void setRealmService(RealmService realmService) {
-        this.realmService = realmService;
-    }
-
-    public RealmService getRealmService() {
-        return realmService;
-    }
-    
-    public void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
-        if (lbConfigSer != null) {
-            this.wholeLbConfig = (LoadBalancerConfiguration) lbConfigSer.getLoadBalancerConfig();
-        } else {
-            this.wholeLbConfig = null;
-        }
-    }
-
-	public void setConfigCtxt(ConfigurationContext configCtxt) {
-		this.configCtxt = configCtxt;
-	}
-
-	public ConfigurationContext getConfigCtxt() {
-		return configCtxt;
-	}
-
-	public void setCloudControllerService(CloudControllerService cc) {
-        this.cloudControllerService = cc;
-    }
-	
-	public CloudControllerService getCloudControllerService() {
-        return cloudControllerService;
-    }
-
-	public UserRegistry getConfigRegistry() {
-        return configRegistry;
-    }
-
-    public void setConfigRegistry(UserRegistry configRegistry) {
-        this.configRegistry = configRegistry;
-    }
-    
-    public UserRegistry getGovernanceRegistry() {
-        return governanceRegistry;
-    }
-
-    public void setGovernanceRegistry(UserRegistry governanceRegistry) {
-        this.governanceRegistry = governanceRegistry;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
deleted file mode 100644
index 399d502..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
+++ /dev/null
@@ -1,2 +0,0 @@
-org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleInMediatorFactory
-org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleOutMediatorFactory

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
deleted file mode 100644
index 05fce78..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
+++ /dev/null
@@ -1,2 +0,0 @@
-org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleInMediatorSerializer
-org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleOutMediatorSerializer
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
deleted file mode 100644
index f8ecf6f..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
+++ /dev/null
@@ -1,138 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
-  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
-  ~
-  ~  WSO2 Inc. licenses this file to you under the Apache License,
-  ~  Version 2.0 (the "License"); you may not use this file except
-  ~  in compliance with the License.
-  ~  You may obtain a copy of the License at
-  ~
-  ~    http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~  Unless required by applicable law or agreed to in writing,
-  ~  software distributed under the License is distributed on an
-  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-  ~  KIND, either express or implied.  See the License for the
-  ~  specific language governing permissions and limitations
-  ~  under the License.
-  -->
-
-<!-- The default synapse configuration shipped with the WSO2 Load Balancer
-     This handles the load balancing and the autoscaling of the stratos services
- -->
-
-<definitions xmlns="http://ws.apache.org/ns/synapse">
-
-    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
-         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
-    -->
-
-
-    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
-         auto-scale your applications.
-    -->
-
-    <task class="org.wso2.carbon.mediator.autoscale2.LoadAverageBasedEC2LoadAnalyzerTask"
-          name="LoadAnalyzer">
-
-
-        <!--
-            The private key for the ec2
-        -->
-        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
-
-        <!--
-            The certificate for the ec2
-        -->
-        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
-
-        <!--
-            The amazon instance type for the load balanced service instances.
-            Recommended and the default is m1.large.
-        -->
-        <property name="instanceType" value="m1.large"/>
-
-        <!--
-            The amazon instance type for the instances of the load balancer itself.
-            Default is m1.large. Can be changed to m1.small too.
-        -->
-        <property name="loadBalancerInstanceType" value="m1.large"/>
-
-        <!--
-            The group of the service being load balanced.
-        -->
-        <property name="applicationGroup" value="as-2011-02-23,cloud-mysql,default"/>
-
-        <!--
-            The group of the load balancer.
-        -->
-        <property name="loadBalancerGroup" value="stratos-appserver-lb,cloud-mysql,default"/>
-
-        <!--
-            The Amazon availability zone for the instances. 1-c is given as the default
-        -->
-        <property name="availabilityZone" value="us-east-1c"/>
-
-        <!--
-            Additional information for the amazon instances
-        -->
-        <property name="instanceAdditionalInfo" value="EC2 autoscale instance"/>
-
-        <!--
-            The key pair
-        -->
-        <property name="key" value="stratos-1.0.0-keypair"/>
-
-        <!--
-            The service payload file which should be loaded to the bucket
-        -->
-        <property name="applicationPayload" value="resources/cluster_node.zip"/>
-
-        <!--
-            The load balancer payload file which should be loaded to the bucket
-        -->
-        <property name="loadBalancerPayload" value="/mnt/payload.zip"/>
-
-        <!--
-            The elasticIP property can be overriden by the ELASTIC_IP environment var,
-             which is set in the payload
-        -->
-        <property name="elasticIP" value="${ELASTIC_IP}"/>
-
-        <!--
-            The minimum and maximum limits of the load balanced service instances
-        -->
-        <property name="minAppInstances" value="1"/>
-        <property name="maxAppInstances" value="5"/>
-
-        <!--
-            The minimum and maximum limits of the load balancer instances
-        -->
-        <property name="minLoadBalancerInstances" value="1"/>
-
-        <property name="roundsToAverage" value="10"/>
-
-        <!--
-            The instances spawned at once, per scaling up decision.
-	    Default and the recommended value is 1
-        -->
-        <property name="instancesPerScaleUp" value="1"/>
-
-        <!--
-            The low and high limits of the load average
-        -->
-        <property name="loadAverageLowerLimit" value="2"/>
-        <property name="loadAverageHigherLimit" value="5"/>
-
-        <!--
-            The Load Balanced Service Ports
-        -->
-        <property name="serviceHttpPort" value="9763"/>
-        <property name="serviceHttpsPort" value="9443"/>
-
-        <!--
-            The interval to trigger the task in seconds
-        -->
-        <trigger interval="5"/>
-    </task>
-</definitions>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
deleted file mode 100644
index 3e66066..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
+++ /dev/null
@@ -1,135 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
-  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
-  ~
-  ~  WSO2 Inc. licenses this file to you under the Apache License,
-  ~  Version 2.0 (the "License"); you may not use this file except
-  ~  in compliance with the License.
-  ~  You may obtain a copy of the License at
-  ~
-  ~    http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~  Unless required by applicable law or agreed to in writing,
-  ~  software distributed under the License is distributed on an
-  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-  ~  KIND, either express or implied.  See the License for the
-  ~  specific language governing permissions and limitations
-  ~  under the License.
-  -->
-
-<!-- The default synapse configuration shipped with the WSO2 Load Balancer
-     This handles the load balancing and the autoscaling of the stratos services
- -->
-
-<definitions xmlns="http://ws.apache.org/ns/synapse">
-
-    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
-         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
-    -->
-
-
-    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
-         auto-scale your applications.
-    -->
-
-    <task class="org.wso2.carbon.mediator.autoscale2.MessagesInFlightBasedEC2LoadAnalyzerTask"
-          name="LoadAnalyzer">
-
-
-        <!--
-            The private key for the ec2
-        -->
-        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
-
-        <!--
-            The certificate for the ec2
-        -->
-        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
-
-        <!--
-            The amazon instance type for the load balanced service instances.
-            Recommended and the default is m1.large.
-        -->
-        <property name="instanceType" value="m1.large"/>
-
-        <!--
-            The amazon instance type for the instances of the load balancer itself.
-            Default is m1.large. Can be changed to m1.small too.
-        -->
-        <property name="loadBalancerInstanceType" value="m1.large"/>
-
-        <!--
-            The group of the service being load balanced.
-        -->
-        <property name="applicationGroup" value="as-2011-02-23,cloud-mysql,default"/>
-
-        <!--
-            The group of the load balancer.
-        -->
-        <property name="loadBalancerGroup" value="stratos-appserver-lb,cloud-mysql,default"/>
-
-        <!--
-            The Amazon availability zone for the instances. 1-c is given as the default
-        -->
-        <property name="availabilityZone" value="us-east-1c"/>
-
-        <!--
-            Additional information for the amazon instances
-        -->
-        <property name="instanceAdditionalInfo" value="EC2 autoscale instance"/>
-
-        <!--
-            The key pair
-        -->
-        <property name="key" value="stratos-1.0.0-keypair"/>
-
-        <!--
-            The service payload file which should be loaded to the bucket
-        -->
-        <property name="applicationPayload" value="resources/cluster_node.zip"/>
-
-        <!--
-            The load balancer payload file which should be loaded to the bucket
-        -->
-        <property name="loadBalancerPayload" value="/mnt/payload.zip"/>
-
-        <!--
-            The elasticIP property can be overriden by the ELASTIC_IP environment var,
-             which is set in the payload
-        -->
-        <property name="elasticIP" value="${ELASTIC_IP}"/>
-
-        <!--
-            The time in milliseconds which the message takes to expire
-        -->
-        <property name="messageExpiryTime" value="60000"/>
-
-        <!--
-            The minimum and maximum limits of the load balanced service instances
-        -->
-        <property name="minAppInstances" value="1"/>
-        <property name="maxAppInstances" value="5"/>
-
-        <!--
-            The number of load balancer instances
-        -->
-        <property name="loadBalancerInstances" value="1"/>
-
-        <!--
-            The given queue length per node, for the calculation in scaling up
-        -->
-        <property name="queueLengthPerNode" value="400"/>
-        <property name="roundsToAverage" value="10"/>
-
-        <!--
-            The instances spawned at once, per scaling up decision.
-	    Default and the recommended value is 1
-        -->
-        <property name="instancesPerScaleUp" value="1"/>
-
-        <!--
-            The interval to trigger the task in seconds
-        -->
-        <trigger interval="5"/>
-    </task>
-</definitions>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
deleted file mode 100644
index 7332d38..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
+++ /dev/null
@@ -1,108 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
-  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
-  ~
-  ~  WSO2 Inc. licenses this file to you under the Apache License,
-  ~  Version 2.0 (the "License"); you may not use this file except
-  ~  in compliance with the License.
-  ~  You may obtain a copy of the License at
-  ~
-  ~    http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~  Unless required by applicable law or agreed to in writing,
-  ~  software distributed under the License is distributed on an
-  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-  ~  KIND, either express or implied.  See the License for the
-  ~  specific language governing permissions and limitations
-  ~  under the License.
-  -->
-
-<!-- The default synapse configuration shipped with the WSO2 Load Balancer
-     This handles the load balancing and the autoscaling of the stratos services
- -->
-
-<definitions xmlns="http://ws.apache.org/ns/synapse">
-
-    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
-         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
-    -->
-
-
-    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
-         auto-scale your applications.
-    -->
-    <task class="org.wso2.carbon.mediator.autoscale.lbautoscale.ServiceRequestsInFlightAutoscaler"
-          name="LoadAnalyzer">
-
-        <!--
-            The private key for ec2
-        -->
-        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
-
-        <!--
-            The certificate for ec2
-        -->
-        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
-        <!--
-            The key pair
-        -->
-        <property name="sshKey" value="stratos-1.0.0-keypair"/>
-
-        <property name="loadBalancer">
-            <loadBalancer>
-                <property name="securityGroup" value="stratos-appserver-lb"/>
-                <property name="instanceType" value="m1.large"/>
-                <property name="instances" value="1"/>
-                <property name="elasticIP" value="${ELASTIC_IP}"/>
-                <property name="availabilityZone" value="us-east-1c"/>
-                <property name="payload" value="/mnt/payload.zip"/>
-            </loadBalancer>
-        </property>
-
-        <property name="services">
-            <services>
-                <defaults>
-                    <property name="payload" value="resources/cluster_node.zip"/>
-                    <property name="availabilityZone" value="us-east-1c"/>
-                    <property name="securityGroup" value="as-2011-02-23"/>
-                    <property name="instanceType" value="m1.large"/>
-                    <property name="minAppInstances" value="1"/>
-                    <property name="maxAppInstances" value="5"/>
-                    <property name="queueLengthPerNode" value="400"/>
-                    <property name="roundsToAverage" value="10"/>
-                    <property name="instancesPerScaleUp" value="1"/>
-                    <property name="messageExpiryTime" value="60000"/>
-                </defaults>
-                <service domain="wso2.as.domain">
-                    <property name="payload" value="resources/cluster_node.zip"/>
-                    <property name="availabilityZone" value="us-east-1c"/>
-                </service>
-                <service domain="wso2.ds.domain">
-                    <property name="payload" value="resources/cluster_node.zip"/>
-                    <property name="minAppInstances" value="1"/>
-                    <property name="maxAppInstances" value="5"/>
-                    <property name="queueLengthPerNode" value="400"/>
-                    <property name="roundsToAverage" value="10"/>
-                    <property name="instancesPerScaleUp" value="1"/>
-                    <property name="availabilityZone" value="us-east-1c"/>
-                    <property name="securityGroup" value="ds-2011-02-23"/>
-                </service>
-                <service domain="wso2.bps.domain">
-                    <property name="payload" value="resources/cluster_node.zip"/>
-                    <property name="minAppInstances" value="1"/>
-                    <property name="maxAppInstances" value="5"/>
-                    <property name="queueLengthPerNode" value="400"/>
-                    <property name="roundsToAverage" value="10"/>
-                    <property name="instancesPerScaleUp" value="1"/>
-                    <property name="availabilityZone" value="us-east-1c"/>
-                    <property name="securityGroup" value="bps-2011-02-23"/>
-                </service>
-            </services>
-        </property>
-
-        <!--
-            The interval to trigger the task in seconds
-        -->
-        <trigger interval="5"/>
-    </task>
-</definitions>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
deleted file mode 100644
index 7d0d9fa..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/java/org/apache/stratos/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.mediator.autoscale.lbautoscale;
-
-import java.io.File;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.tribes.TribesClusteringAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.context.ConfigurationContextFactory;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.apache.stratos.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
-import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-public class AppDomainContextsTest extends TestCase {
-
-    private static Map<String, Map<String, ?>> map;
-    private LoadBalancerConfiguration lbConfig;
-    ConfigurationContext configCtx;
-    ClusteringAgent clusteringAgent;
-    
-    protected void setUp() throws Exception {
-        super.setUp();
-        configCtx = ConfigurationContextFactory.createEmptyConfigurationContext();
-        clusteringAgent = new TribesClusteringAgent();
-        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
-                    "worker"),
-                    "wso2.as1.domain", "worker", -1);
-        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
-                "mgt"),
-                "wso2.as1.domain", "mgt", -1);
-        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
-                "mgt"),
-                "wso2.as2.domain", "mgt", -1);
-        configCtx.getAxisConfiguration().setClusteringAgent(clusteringAgent);
-        
-        File f = new File("src/test/resources/loadbalancer.conf");
-        System.setProperty("loadbalancer.conf", f.getAbsolutePath());
-        lbConfig = LoadBalancerConfiguration.getInstance();
-        
-        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
-        
-    }
-    
-    
-    public void testRemoval(){
-        // removing a cluster domain with only 1 sub domain 
-        lbConfig.removeServiceConfiguration("wso2.as2.domain", "mgt");
-        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
-        
-        Assert.assertEquals(true, !map.containsKey("wso2.as2.domain"));
-        
-        // removing a cluster domain with more than 1 sub domain
-        lbConfig.removeServiceConfiguration("wso2.as1.domain", "mgt");
-        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
-        
-        Assert.assertEquals(true, map.containsKey("wso2.as1.domain"));
-        Assert.assertEquals(true, map.get("wso2.as1.domain").get("mgt") == null);
-        Assert.assertEquals(true, map.get("wso2.as1.domain").get("worker") != null);
-    }
-    
-    public void testAddition(){
-        ServiceConfiguration config1 = lbConfig.new ServiceConfiguration();
-        config1.setDomain("wso2.as3.domain");
-        config1.setSub_domain("mgt");
-        lbConfig.addServiceConfiguration(config1);
-        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
-                "mgt"),
-                "wso2.as3.domain", "mgt", -1);
-        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
-        
-        Assert.assertEquals(true, map.containsKey("wso2.as3.domain"));
-        Assert.assertEquals(true, map.get("wso2.as3.domain").get("mgt") != null);
-    }
-
-    @Deprecated // use only for writing test cases
-    void printKeys(Map<?,?> map){
-        for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
-            Object type = iterator.next();
-            System.out.println(type);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf b/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
deleted file mode 100644
index 7b2a80a..0000000
--- a/components/autoscaler/org.apache.stratos.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
+++ /dev/null
@@ -1,50 +0,0 @@
-loadbalancer {
-    instances	1;
-    enable_autoscaler	true;
-    # interval between two task executions in milliseconds
-    autoscaler_task_interval	5000;
-    # after an instance booted up, task will wait till this much of time and let the server started up
-    server_startup_delay		15000; #default will be 60000ms
-}
-
-services {
-    defaults {
-        min_app_instances 1;
-        max_app_instances       5;
-        max_requests_per_second   400;
-        alarming_upper_rate 0.65;
-        alarming_lower_rate 0.2;
-        scale_down_factor 0.25;
-        rounds_to_average       10;
-        instances_per_scale_up  1;
-        message_expiry_time     60000;
-    }
-
-    appserver {
-        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
-        sub_domain      worker1;
-        domains   {
-            wso2.as1.domain {
-            	hosts as1.cloud-test.wso2.com;
-            	  min_app_instances   0;
-            	  sub_domain      worker;
-                tenant_range    1-5;
-            }
-            wso2.as1.domain {
-            	hosts mgt.as1.cloud-test.wso2.com;
-            	  min_app_instances   0;
-            	  sub_domain      mgt;
-                tenant_range    1-5;
-            }
-            wso2.as2.domain {
-            	hosts mgt.as2.cloud-test.wso2.com;
-            	  min_app_instances   0;
-            	  sub_domain      mgt;
-                tenant_range    1-5;
-            }
-            
-        }
-    }
-    
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/pom.xml b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/pom.xml
deleted file mode 100644
index 04b8e71..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/pom.xml
+++ /dev/null
@@ -1,116 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-     ~  Licensed to the Apache Software Foundation (ASF) under one
-     ~  or more contributor license agreements.  See the NOTICE file
-     ~  distributed with this work for additional information
-     ~  regarding copyright ownership.  The ASF licenses this file
-     ~  to you under the Apache License, Version 2.0 (the
-     ~  "License"); you may not use this file except in compliance
-     ~  with the License.  You may obtain a copy of the License at
-     ~
-     ~    http://www.apache.org/licenses/LICENSE-2.0
-     ~
-     ~  Unless required by applicable law or agreed to in writing,
-     ~  software distributed under the License is distributed on an
-     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-     ~  KIND, either express or implied.  See the License for the
-     ~  specific language governing permissions and limitations
-     ~  under the License.
-     ~
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <groupId>org.apache.stratos</groupId>
-    <artifactId>org.apache.stratos.lb.endpoint</artifactId>
-    <packaging>bundle</packaging>
-    <version>4.1.3</version>
-    <name>Apache Stratos - Tenant Aware LoadBalance Endpoint</name>
-    <url>http://apache.org</url>
-    
-    <dependencies>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.mediation.initializer</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.mediation.dependency.mgt</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.synapse</groupId>
-            <artifactId>synapse-core</artifactId>
-            <version>${synapse.core.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.logging</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.stratos</groupId>
-            <artifactId>org.apache.stratos.lb.common</artifactId>
-            <version>4.1.3</version>
-        </dependency>
-	<dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2</artifactId>
-            <version>${axis2.wso2.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.axis2</groupId>
-            <artifactId>axis2-kernel</artifactId>
-            <version>1.6.1-wso2v9</version>
-        </dependency>
-        <dependency>
-           <groupId>org.wso2.carbon</groupId>
-           <artifactId>org.wso2.carbon.cartridge.messages</artifactId>
-           <version>2.1.1</version>
-        </dependency>
-    </dependencies>
-
-    <build>
-        <plugins>
-
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Export-Package>
-                            org.apache.stratos.lb.endpoint.endpoint,
-                            org.apache.stratos.lb.endpoint,
-                            org.apache.stratos.lb.endpoint.util,
-                        </Export-Package>
-                        <Import-Package>
-                            !org.apache.stratos.lb.endpoint.endpoint,
-                            !org.apache.stratos.lb.endpoint,
-                            org.apache.stratos.lb.common.*; version=${project.version},
-                            org.apache.stratos.registry.core.service; version=1.0.1,
-                            *;resolution:=optional
-                        </Import-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java
----------------------------------------------------------------------
diff --git a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java b/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java
deleted file mode 100644
index 60efed5..0000000
--- a/components/lb-endpoint/org.apache.stratos.lb.endpoint/4.1.3/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.lb.endpoint;
-
-/**
- * The <code>EndpointConstants</code> class defined the endpoint constants.
- */
-public class EndpointConstants {
-
-    public static final String ADDRESS_ENDPOINT = "Address Endpoint";
-    public static final String WSDL_ENDPOINT = "WSDL Endpoint";
-    public static final String FAILOVER_ENDPOINT = "Failover Group";
-    public static final String LOADBALANCE_ENDPOINT = "Loadbalance Endpoint";
-}


[30/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
deleted file mode 100644
index 307ffe3..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
+++ /dev/null
@@ -1,853 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.utils;
-
-import java.io.File;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.crypto.Cipher;
-import javax.crypto.SecretKey;
-import javax.crypto.spec.SecretKeySpec;
-import javax.xml.namespace.QName;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.impl.builder.StAXOMBuilder;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.dao.CartridgeSubscription;
-import org.apache.stratos.adc.mgt.dao.DataCartridge;
-import org.apache.stratos.adc.mgt.dao.PortMapping;
-import org.apache.stratos.adc.mgt.dao.Repository;
-import org.apache.stratos.adc.mgt.dao.RepositoryCredentials;
-import org.wso2.carbon.utils.CarbonUtils;
-import org.wso2.securevault.SecretResolver;
-import org.wso2.securevault.SecretResolverFactory;
-
-/**
- * This class is responsible for handling persistence
- * 
- */
-public class PersistenceManager {
-
-	private static final Log log = LogFactory.getLog(PersistenceManager.class);
-
-	public static void persistCartridgeInstanceInfo(String instanceIp, String clusterDomain, String clusterSubDomain,
-			String cartridgeType, String state) throws Exception {
-
-		Connection con = null;
-		PreparedStatement statement = null;
-		PreparedStatement updateStatement = null;
-		ResultSet resultSet = null;
-
-		boolean isUpdate = false;
-		int instanceId = 0;
-		try {
-			con = StratosDBUtils.getConnection();
-
-			// First check whether Ip exists..
-			String sql = "SELECT ID FROM CARTRIDGE_INSTANCE where INSTANCE_IP=? AND CARTRIDGE_TYPE=? "
-					+ " AND CLUSTER_DOMAIN=? AND CLUSTER_SUBDOMAIN=?";
-			statement = con.prepareStatement(sql);
-			statement.setString(1, instanceIp);
-			statement.setString(2, cartridgeType);
-			statement.setString(3, clusterDomain);
-			statement.setString(4, clusterSubDomain);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = statement.executeQuery();
-			if (resultSet.next()) {
-				isUpdate = true;
-				instanceId = resultSet.getInt("ID");
-			}
-
-			String persistQuery = null;
-			if (isUpdate) {
-				persistQuery = "UPDATE CARTRIDGE_INSTANCE SET STATE=?" + " WHERE ID=?";
-				updateStatement = con.prepareStatement(persistQuery);
-				updateStatement.setString(1, state);
-				updateStatement.setInt(2, instanceId);
-			} else {
-				persistQuery = "INSERT INTO CARTRIDGE_INSTANCE (INSTANCE_IP, CARTRIDGE_TYPE, STATE, CLUSTER_DOMAIN, CLUSTER_SUBDOMAIN)"
-						+ " VALUES (?, ?, ?, ?, ?)";
-				updateStatement = con.prepareStatement(persistQuery);
-				updateStatement.setString(1, instanceIp);
-				updateStatement.setString(2, cartridgeType);
-				updateStatement.setString(3, state);
-				updateStatement.setString(4, clusterDomain);
-				updateStatement.setString(5, clusterSubDomain);
-			}
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + persistQuery);
-			}
-			updateStatement.executeUpdate();
-			con.commit();
-		} catch (Exception e) {
-			if (con != null) {
-				try {
-					con.rollback();
-				} catch (SQLException e1) {
-					log.error("Failed to rollback", e);
-				}
-			}
-			;
-			log.error("Error", e);
-			throw e;
-		} finally {
-			StratosDBUtils.closeResultSet(resultSet);
-			StratosDBUtils.closeAllConnections(con, statement, updateStatement);
-		}
-	}
-
-	public static boolean isAlreadySubscribed(String cartridgeType, int tenantId) throws Exception {
-
-		Connection con = null;
-		PreparedStatement preparedStatement = null;
-		ResultSet resultSet = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "SELECT C.ALIAS FROM CARTRIDGE_SUBSCRIPTION C WHERE TENANT_ID = ? AND C.CARTRIDGE = ? AND C.STATE != 'UNSUBSCRIBED'";
-			preparedStatement = con.prepareStatement(sql);
-			preparedStatement.setInt(1, tenantId);
-			preparedStatement.setString(2, cartridgeType);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = preparedStatement.executeQuery();
-			if (resultSet.next()) {
-				String alias = resultSet.getString("ALIAS");
-				if (log.isDebugEnabled()) {
-					log.debug("Already subscribed to " + cartridgeType + " with alias " + alias);
-				}
-				return true;
-			} else {
-				return false;
-			}
-		} catch (Exception s) {
-			String msg = "Error while sql connection :" + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, preparedStatement, resultSet);
-		}
-	}
-
-	public static List<CartridgeSubscription> retrieveSubscribedCartridges(int tenantId) throws Exception {
-
-		List<CartridgeSubscription> subscribedCartridgeList = new ArrayList<CartridgeSubscription>();
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "SELECT C.CARTRIDGE, C.ALIAS, C.CLUSTER_DOMAIN, C.CLUSTER_SUBDOMAIN, C.POLICY, C.STATE, "
-					+ "C.TENANT_ID, C.SUBSCRIPTION_ID, C.DATA_CARTRIDGE_ID, D.TYPE, D.USER_NAME, D.PASSWORD, "
-					+ "C.PROVIDER, C.HOSTNAME, C.MAPPED_DOMAIN, R.REPO_NAME FROM CARTRIDGE_SUBSCRIPTION C "
-					+ "LEFT JOIN DATA_CARTRIDGE D on D.DATA_CART_ID=C.DATA_CARTRIDGE_ID  "
-					+ "LEFT JOIN REPOSITORY R ON C.REPO_ID=R.REPO_ID WHERE TENANT_ID=? AND C.STATE != 'UNSUBSCRIBED' "
-					+ "ORDER BY C.SUBSCRIPTION_ID";
-			statement = con.prepareStatement(sql);
-			statement.setInt(1, tenantId);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = statement.executeQuery();
-			while (resultSet.next()) {
-				CartridgeSubscription cartridge = new CartridgeSubscription();
-				cartridge.setAlias(resultSet.getString("ALIAS"));
-				cartridge.setCartridge(resultSet.getString("CARTRIDGE"));
-				cartridge.setState(resultSet.getString("STATE"));
-				cartridge.setClusterDomain(resultSet.getString("CLUSTER_DOMAIN"));
-				cartridge.setClusterSubdomain(resultSet.getString("CLUSTER_SUBDOMAIN"));
-				cartridge.setProvider(resultSet.getString("PROVIDER"));
-				cartridge.setPolicy(resultSet.getString("POLICY"));
-				cartridge.setMappedDomain(resultSet.getString("MAPPED_DOMAIN"));
-				Repository repo = new Repository();
-				repo.setRepoName(resultSet.getString("REPO_NAME"));
-				cartridge.setRepository(repo);
-				cartridge.setHostName(resultSet.getString("HOSTNAME"));
-				int dataCartridgeId = resultSet.getInt("DATA_CARTRIDGE_ID");
-				if (dataCartridgeId != 0) {
-					DataCartridge dataCartridge = new DataCartridge();
-					dataCartridge.setDataCartridgeType(resultSet.getString("TYPE"));
-					dataCartridge.setPassword(resultSet.getString("PASSWORD"));
-					dataCartridge.setUserName(resultSet.getString("USER_NAME"));
-					cartridge.setDataCartridge(dataCartridge);
-				}
-				subscribedCartridgeList.add(cartridge);
-			}
-		} catch (Exception s) {
-			String msg = "Error while sql connection :" + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-		return subscribedCartridgeList;
-	}
-
-	public static String getRepoURL(int tenantId, String cartridge) throws Exception {
-
-		String repoUrl = null;
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "SELECT REPO_NAME FROM REPOSITORY R, CARTRIDGE_SUBSCRIPTION C "
-					+ "WHERE C.REPO_ID=R.REPO_ID AND C.TENANT_ID=? AND C.CARTRIDGE=? "
-					+ "AND C.STATE != 'UNSUBSCRIBED' ";
-			statement = con.prepareStatement(sql);
-			statement.setInt(1, tenantId);
-			statement.setString(2, cartridge);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = statement.executeQuery();
-			if (resultSet.next()) {
-				repoUrl = resultSet.getString("REPO_NAME");
-			}
-		} catch (Exception s) {
-			String msg = "Error while sql connection :" + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-		return repoUrl;
-	}
-
-	public static RepositoryCredentials getRepoCredentials(int tenantId, String cartridge, String alias)
-			throws Exception {
-
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-		RepositoryCredentials repoCredentials = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "SELECT REPO_NAME,REPO_USER_NAME,REPO_USER_PASSWORD FROM REPOSITORY R, CARTRIDGE_SUBSCRIPTION C "
-					+ "WHERE C.REPO_ID=R.REPO_ID AND C.TENANT_ID=? AND C.CARTRIDGE=? AND C.STATE != 'UNSUBSCRIBED' ";
-			if (alias != null) {
-				sql = sql + " AND C.ALIAS=?";
-			}
-			statement = con.prepareStatement(sql);
-			statement.setInt(1, tenantId);
-			statement.setString(2, cartridge);
-			if (alias != null) {
-				statement.setString(3, alias);
-			}
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = statement.executeQuery();
-			while (resultSet.next()) {
-				repoCredentials = new RepositoryCredentials();
-				repoCredentials.setUrl(resultSet.getString("REPO_NAME"));
-				repoCredentials.setUserName(resultSet.getString("REPO_USER_NAME"));
-				repoCredentials.setPassword(decryptPassword(resultSet.getString("REPO_USER_PASSWORD")));
-			}
-		} catch (Exception s) {
-			String msg = "Error while sql connection :" + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-		return repoCredentials;
-	}
-
-	public static boolean isAliasAlreadyTaken(String alias, String cartridgeType) throws Exception {
-		boolean aliasAlreadyTaken = false;
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "SELECT SUBSCRIPTION_ID FROM CARTRIDGE_SUBSCRIPTION where ALIAS=? AND CARTRIDGE=? AND STATE != 'UNSUBSCRIBED'";
-			statement = con.prepareStatement(sql);
-			statement.setString(1, alias);
-			statement.setString(2, cartridgeType);
-			statement.setMaxRows(1);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = statement.executeQuery();
-			if (resultSet.next()) {
-				log.info("Already taken..");
-				aliasAlreadyTaken = true;
-			}
-		} catch (Exception s) {
-			String msg = "Error while sql connection :" + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-		return aliasAlreadyTaken;
-	}
-
-	public static int persistSubscription(CartridgeSubscription cartridgeSubscription) throws Exception {
-
-		int cartridgeSubscriptionId = 0;
-		int repoId = 0;
-		int dataCartridgeId = 0;
-		ResultSet res = null;
-		PreparedStatement insertSubscriptionStmt = null;
-		PreparedStatement insertRepoStmt = null;
-		PreparedStatement insertDataCartStmt = null;
-
-		Connection con = null;
-
-		// persist cartridge_subscription
-		try {
-			con = StratosDBUtils.getConnection();
-			// persist repo
-			if (cartridgeSubscription.getRepository() != null) {
-				String encryptedRepoUserPassword = encryptPassword(cartridgeSubscription.getRepository()
-						.getRepoUserPassword());
-				String insertRepo = "INSERT INTO REPOSITORY (REPO_NAME,STATE,REPO_USER_NAME,REPO_USER_PASSWORD)"
-						+ " VALUES (?,?,?,?)";
-
-				insertRepoStmt = con.prepareStatement(insertRepo, Statement.RETURN_GENERATED_KEYS);
-				insertRepoStmt.setString(1, cartridgeSubscription.getRepository().getRepoName());
-				insertRepoStmt.setString(2, "ACTIVE");
-				insertRepoStmt.setString(3, cartridgeSubscription.getRepository().getRepoUserName());
-				insertRepoStmt.setString(4, encryptedRepoUserPassword);
-				if (log.isDebugEnabled()) {
-					log.debug("Executing insert: " + insertRepo);
-				}
-				insertRepoStmt.executeUpdate();
-				res = insertRepoStmt.getGeneratedKeys();
-				if (res.next()) {
-					repoId = res.getInt(1);
-				}
-				StratosDBUtils.closeResultSet(res);
-			}
-
-			// persist data cartridge
-			if (cartridgeSubscription.getDataCartridge() != null) {
-				String insertDataCartridge = "INSERT INTO DATA_CARTRIDGE (TYPE,USER_NAME,PASSWORD,STATE)"
-						+ " VALUES (?,?,?,?)";
-				insertDataCartStmt = con.prepareStatement(insertDataCartridge, Statement.RETURN_GENERATED_KEYS);
-				insertDataCartStmt.setString(1, cartridgeSubscription.getDataCartridge().getDataCartridgeType());
-				insertDataCartStmt.setString(2, cartridgeSubscription.getDataCartridge().getUserName());
-				insertDataCartStmt.setString(3, cartridgeSubscription.getDataCartridge().getPassword());
-				insertDataCartStmt.setString(4, "ACTIVE");
-				if (log.isDebugEnabled()) {
-					log.debug("Executing insert: " + insertDataCartridge);
-				}
-				insertDataCartStmt.executeUpdate();
-				res = insertDataCartStmt.getGeneratedKeys();
-				if (res.next()) {
-					dataCartridgeId = res.getInt(1);
-				}
-				StratosDBUtils.closeResultSet(res);
-			}
-
-			String insertSubscription = "INSERT INTO CARTRIDGE_SUBSCRIPTION (TENANT_ID, CARTRIDGE, PROVIDER,"
-					+ "HOSTNAME, POLICY, CLUSTER_DOMAIN, " + "CLUSTER_SUBDOMAIN, MGT_DOMAIN, MGT_SUBDOMAIN, STATE, "
-					+ "ALIAS, TENANT_DOMAIN, BASE_DIR, REPO_ID, DATA_CARTRIDGE_ID)"
-					+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
-
-			insertSubscriptionStmt = con.prepareStatement(insertSubscription, Statement.RETURN_GENERATED_KEYS);
-			insertSubscriptionStmt.setInt(1, cartridgeSubscription.getTenantId());
-			insertSubscriptionStmt.setString(2, cartridgeSubscription.getCartridge());
-			insertSubscriptionStmt.setString(3, cartridgeSubscription.getProvider());
-			insertSubscriptionStmt.setString(4, cartridgeSubscription.getHostName());
-			insertSubscriptionStmt.setString(5, cartridgeSubscription.getPolicy());
-			insertSubscriptionStmt.setString(6, cartridgeSubscription.getClusterDomain());
-			insertSubscriptionStmt.setString(7, cartridgeSubscription.getClusterSubdomain());
-			insertSubscriptionStmt.setString(8, cartridgeSubscription.getMgtClusterDomain());
-			insertSubscriptionStmt.setString(9, cartridgeSubscription.getMgtClusterSubDomain());
-			insertSubscriptionStmt.setString(10, cartridgeSubscription.getState());
-			insertSubscriptionStmt.setString(11, cartridgeSubscription.getAlias());
-			insertSubscriptionStmt.setString(12, cartridgeSubscription.getTenantDomain());
-			insertSubscriptionStmt.setString(13, cartridgeSubscription.getBaseDirectory());
-			insertSubscriptionStmt.setInt(14, repoId);
-			insertSubscriptionStmt.setInt(15, dataCartridgeId);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing insert: " + insertSubscription);
-			}
-			insertSubscriptionStmt.executeUpdate();
-			res = insertSubscriptionStmt.getGeneratedKeys();
-			if (res.next()) {
-				cartridgeSubscriptionId = res.getInt(1);
-			}
-
-			List<PortMapping> portMapping = cartridgeSubscription.getPortMappings();
-			// persist port map
-			if (portMapping != null && !portMapping.isEmpty()) {
-				for (PortMapping portMap : portMapping) {
-					String insertPortMapping = "INSERT INTO PORT_MAPPING (SUBSCRIPTION_ID, TYPE, PRIMARY_PORT, PROXY_PORT, STATE)"
-							+ " VALUES (?,?,?,?,?)";
-
-					PreparedStatement insertPortsStmt = con.prepareStatement(insertPortMapping);
-					insertPortsStmt.setInt(1, cartridgeSubscriptionId);
-					insertPortsStmt.setString(2, portMap.getType());
-					insertPortsStmt.setString(3, portMap.getPrimaryPort());
-					insertPortsStmt.setString(4, portMap.getProxyPort());
-					insertPortsStmt.setString(5, "ACTIVE");
-					if (log.isDebugEnabled()) {
-						log.debug("Executing insert: " + insertPortMapping);
-					}
-					insertPortsStmt.executeUpdate();
-					StratosDBUtils.closeStatement(insertPortsStmt);
-				}
-			}
-			con.commit(); // Commit manually
-		} catch (Exception e) {
-			if (con != null) {
-				try {
-					con.rollback();
-				} catch (SQLException e1) {
-					log.error("Failed to rollback", e);
-				}
-			}
-			;
-			log.error(e.getMessage());
-			String msg = "Exception : " + e.getMessage();
-			log.error(msg, e);
-			throw new Exception("Subscription failed!", e);
-		} finally {
-			StratosDBUtils.closeResultSet(res);
-			StratosDBUtils.closeAllConnections(con, insertRepoStmt, insertDataCartStmt, insertSubscriptionStmt);
-		}
-		return cartridgeSubscriptionId;
-	}
-
-	public static String getHostNameForCartridgeName(int tenantId, String alias) throws Exception {
-
-		String hostName = null;
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "SELECT HOSTNAME FROM CARTRIDGE_SUBSCRIPTION where TENANT_ID=?"
-					+ " AND ALIAS=? AND STATE != 'UNSUBSCRIBED'";
-			statement = con.prepareStatement(sql);
-			statement.setInt(1, tenantId);
-			statement.setString(2, alias);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = statement.executeQuery();
-			if (resultSet.next()) {
-				hostName = resultSet.getString("HOSTNAME");
-			}
-		} catch (Exception s) {
-			String msg = "Error while sql connection :" + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-		return hostName;
-	}
-
-	public static CartridgeSubscription getSubscription(String tenantDomain, String alias) throws Exception {
-
-		CartridgeSubscription cartridgeSubscription = null;
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "SELECT * FROM CARTRIDGE_SUBSCRIPTION C left join REPOSITORY R on "
-					+ "C.REPO_ID=R.REPO_ID left join DATA_CARTRIDGE D on "
-					+ "D.DATA_CART_ID=C.DATA_CARTRIDGE_ID WHERE ALIAS=? AND TENANT_DOMAIN=? AND C.STATE != 'UNSUBSCRIBED'";
-			statement = con.prepareStatement(sql);
-			statement.setString(1, alias);
-			statement.setString(2, tenantDomain);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = statement.executeQuery();
-			if (resultSet.next()) {
-				cartridgeSubscription = new CartridgeSubscription();
-				populateSubscription(cartridgeSubscription, resultSet);
-			}
-		} catch (Exception s) {
-			String msg = "Error while sql connection :" + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-
-		return cartridgeSubscription;
-	}
-
-	private static void populateSubscription(CartridgeSubscription cartridgeSubscription, ResultSet resultSet)
-			throws Exception {
-		String repoName = resultSet.getString("REPO_NAME");
-		if (repoName != null) {
-			Repository repo = new Repository();
-			repo.setRepoName(repoName);
-			cartridgeSubscription.setRepository(repo);
-		}
-
-		int dataCartridgeId = resultSet.getInt("DATA_CARTRIDGE_ID");
-		if (dataCartridgeId != 0) {
-			DataCartridge dataCartridge = new DataCartridge();
-			dataCartridge.setDataCartridgeType(resultSet.getString("TYPE"));
-			dataCartridge.setPassword(resultSet.getString("PASSWORD"));
-			dataCartridge.setUserName(resultSet.getString("USER_NAME"));
-			cartridgeSubscription.setDataCartridge(dataCartridge);
-		}
-		cartridgeSubscription.setPortMappings(getPortMappings(resultSet.getInt("SUBSCRIPTION_ID")));
-		cartridgeSubscription.setTenantId(resultSet.getInt("TENANT_ID"));
-		cartridgeSubscription.setState(resultSet.getString("STATE"));
-		cartridgeSubscription.setPolicy(resultSet.getString("POLICY"));
-		cartridgeSubscription.setCartridge(resultSet.getString("CARTRIDGE"));
-		cartridgeSubscription.setAlias(resultSet.getString("ALIAS"));
-		cartridgeSubscription.setClusterDomain(resultSet.getString("CLUSTER_DOMAIN"));
-		cartridgeSubscription.setClusterSubdomain(resultSet.getString("CLUSTER_SUBDOMAIN"));
-		cartridgeSubscription.setMgtClusterDomain(resultSet.getString("MGT_DOMAIN"));
-		cartridgeSubscription.setMgtClusterSubDomain(resultSet.getString("MGT_SUBDOMAIN"));
-		cartridgeSubscription.setProvider(resultSet.getString("PROVIDER"));
-		cartridgeSubscription.setHostName(resultSet.getString("HOSTNAME"));
-		cartridgeSubscription.setTenantDomain(resultSet.getString("TENANT_DOMAIN"));
-		cartridgeSubscription.setBaseDirectory(resultSet.getString("BASE_DIR"));
-		cartridgeSubscription.setSubscriptionId(resultSet.getInt("SUBSCRIPTION_ID"));
-		cartridgeSubscription.setMappedDomain(resultSet.getString("MAPPED_DOMAIN"));
-	}
-
-	private static List<PortMapping> getPortMappings(int subscriptionId) throws Exception {
-
-		List<PortMapping> portMappingList = new ArrayList<PortMapping>();
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "SELECT * FROM PORT_MAPPING WHERE SUBSCRIPTION_ID = ?";
-			statement = con.prepareStatement(sql);
-			statement.setInt(1, subscriptionId);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = statement.executeQuery();
-			while (resultSet.next()) {
-				PortMapping portMapping = new PortMapping();
-				portMapping.setPrimaryPort(resultSet.getString("PRIMARY_PORT"));
-				portMapping.setProxyPort(resultSet.getString("PROXY_PORT"));
-				portMapping.setType(resultSet.getString("TYPE"));
-				portMappingList.add(portMapping);
-			}
-		} catch (Exception s) {
-			String msg = "Error while sql connection :" + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-		return portMappingList;
-	}
-
-	public static void updateDomainMapping(int tenantId, String cartridgeAlias, String domain) throws Exception {
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "UPDATE CARTRIDGE_SUBSCRIPTION SET MAPPED_DOMAIN = ? WHERE TENANT_ID = ? AND ALIAS = ?";
-			statement = con.prepareStatement(sql);
-			statement.setString(1, domain);
-			statement.setInt(2, tenantId);
-			statement.setString(3, cartridgeAlias);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing update: " + sql);
-			}
-			statement.executeUpdate();
-			con.commit();
-		} catch (Exception s) {
-			if (con != null) {
-				try {
-					con.rollback();
-				} catch (SQLException e) {
-					log.error("Failed to rollback", e);
-				}
-			}
-			String msg = "Error: " + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-	}
-
-	public static List<CartridgeSubscription> getSubscription(String repositoryURL) throws Exception {
-
-		List<CartridgeSubscription> subscriptionList = new ArrayList<CartridgeSubscription>();
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "SELECT * from CARTRIDGE_SUBSCRIPTION C, REPOSITORY R "
-					+ "where R.REPO_NAME LIKE ? AND C.REPO_ID = R.REPO_ID AND C.STATE != 'UNSUBSCRIBED'";
-			statement = con.prepareStatement(sql);
-			statement.setString(1, repositoryURL + "%");
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = statement.executeQuery();
-			while (resultSet.next()) {
-				CartridgeSubscription cartridgeSubscription = new CartridgeSubscription();
-				populateSubscription(cartridgeSubscription, resultSet);
-				subscriptionList.add(cartridgeSubscription);
-			}
-		} catch (Exception s) {
-			String msg = "Error while sql connection :" + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-		return subscriptionList;
-	}
-
-	public static void updateSubscriptionState(int subscriptionId, String state) throws Exception {
-
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-
-		try {
-			con = StratosDBUtils.getConnection();
-			String sql = "UPDATE CARTRIDGE_SUBSCRIPTION SET STATE=? WHERE SUBSCRIPTION_ID=?";
-			statement = con.prepareStatement(sql);
-			statement.setString(1, state);
-			statement.setInt(2, subscriptionId);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing update: " + sql);
-			}
-			statement.executeUpdate();
-			con.commit();
-		} catch (Exception s) {
-			if (con != null) {
-				try {
-					con.rollback();
-				} catch (SQLException e) {
-					log.error("Failed to rollback", e);
-				}
-			}
-			;
-			String msg = "Error: " + s.getMessage();
-			log.error(msg, s);
-			throw s;
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-	}
-
-	public static Map<String, String> getCartridgeInstanceInfo(String[] ips, String clusterDomain, String clusterSubdomain)
-            throws Exception {
-		Map<String, String> instanceIpToStateMap = new HashMap<String, String>();
-		
-		Connection con = null;
-		PreparedStatement statement = null;
-		ResultSet resultSet = null;
-		
-		try {
-			con = StratosDBUtils.getConnection();
-			StringBuilder sqlBuilder = new StringBuilder(
-					"SELECT INSTANCE_IP, STATE FROM CARTRIDGE_INSTANCE WHERE INSTANCE_IP IN (");
-			for (int i = 0; i < ips.length; i++) {
-				if (i > 0) {
-					sqlBuilder.append(", ");
-				}
-				sqlBuilder.append("?");
-			}
-			sqlBuilder.append(") AND CLUSTER_DOMAIN=? AND CLUSTER_SUBDOMAIN=?");
-			String sql = sqlBuilder.toString();
-			
-			statement = con.prepareStatement(sql);
-			int i = 1;
-			for (int j = 0; j < ips.length; j++, i++) {
-				String ip = ips[j];
-				statement.setString(i, ip);
-			}
-			statement.setString(i++, clusterDomain);
-			statement.setString(i, clusterSubdomain);
-			if (log.isDebugEnabled()) {
-				log.debug("Executing query: " + sql);
-			}
-			resultSet = statement.executeQuery();
-			while (resultSet.next()) {
-				instanceIpToStateMap.put(resultSet.getString("INSTANCE_IP"), resultSet.getString("STATE"));
-			}
-		} catch (Exception s) {
-			String msg = "Error while sql connection :" + s.getMessage();
-			log.error(msg, s);
-			throw new Exception("Ann error occurred while listing cartridge information.");
-		} finally {
-			StratosDBUtils.closeAllConnections(con, statement, resultSet);
-		}
-		return instanceIpToStateMap;
-	}
-
-	public static String getSecurityKey() {
-		String securityKey = CartridgeConstants.DEFAULT_SECURITY_KEY;
-		OMElement documentElement = null;
-		File xmlFile = new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "conf"
-				+ File.separator + CartridgeConstants.SECURITY_KEY_FILE);
-
-		if (xmlFile.exists()) {
-			try {
-				documentElement = new StAXOMBuilder(xmlFile.getPath()).getDocumentElement();
-			} catch (Exception ex) {
-				String msg = "Error occurred when parsing the " + xmlFile.getPath() + ".";
-				log.error(msg, ex);
-				ex.printStackTrace();
-			}
-			if (documentElement != null) {
-				Iterator<?> it = documentElement.getChildrenWithName(new QName(CartridgeConstants.SECURITY_KEY));
-				if (it.hasNext()) {
-					OMElement securityKeyElement = (OMElement) it.next();
-					SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
-					String alias = securityKeyElement.getAttributeValue(new QName(CartridgeConstants.ALIAS_NAMESPACE,
-							CartridgeConstants.ALIAS_LOCALPART, CartridgeConstants.ALIAS_PREFIX));
-
-					if (secretResolver != null && secretResolver.isInitialized()
-							&& secretResolver.isTokenProtected(alias)) {
-						securityKey = "";
-						securityKey = secretResolver.resolve(alias);
-						// TODO : a proper testing on the secure vault protected
-						// user defined encryption key
-					}
-				}
-			}
-		} else {
-			System.out.println("No such file ezoxists");
-		}
-		return securityKey;
-	}
-
-	public static void updateInstanceState(String state, String[] ips, String clusterDomain, String clusterSubDomain, String cartridgeType)
-			throws Exception {
-
-		Connection con = null;
-		PreparedStatement statement = null;
-
-		if (ips != null && ips.length > 0) {
-			try {
-				con = StratosDBUtils.getConnection();
-				StringBuilder sqlBuilder = new StringBuilder(
-						"UPDATE CARTRIDGE_INSTANCE SET STATE=? WHERE INSTANCE_IP IN (");
-				for (int i = 0; i < ips.length; i++) {
-					if (i > 0) {
-						sqlBuilder.append(", ");
-					}
-					sqlBuilder.append("?");
-				}
-				sqlBuilder.append(") AND CLUSTER_DOMAIN=? AND CLUSTER_SUBDOMAIN=? AND CARTRIDGE_TYPE=?");
-				String sql = sqlBuilder.toString();
-				statement = con.prepareStatement(sql);
-				statement.setString(1, state);
-				int i = 2;
-				for (int j = 0; j < ips.length; j++, i++) {
-					String ip = ips[j];
-					statement.setString(i, ip);
-				}
-				statement.setString(i++, clusterDomain);
-				statement.setString(i++, clusterSubDomain);
-				statement.setString(i, cartridgeType);
-				if (log.isDebugEnabled()) {
-					log.debug("Executing query: " + sql);
-				}
-				statement.executeUpdate();
-				con.commit();
-			} catch (Exception s) {
-				if (con != null) {
-					try {
-						con.rollback();
-					} catch (SQLException e) {
-						log.error("Failed to rollback", e);
-					}
-				}
-				String msg = "Error: " + s.getMessage();
-				log.error(msg, s);
-				throw s;
-			} finally {
-				StratosDBUtils.closeAllConnections(con, statement);
-			}
-		}
-
-	}
-
-	private static String encryptPassword(String repoUserPassword) {
-		String encryptPassword = "";
-		String secret = getSecurityKey(); // secret key length must be 16
-		SecretKey key;
-		Cipher cipher;
-		Base64 coder;
-		key = new SecretKeySpec(secret.getBytes(), "AES");
-		try {
-			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
-			coder = new Base64();
-			cipher.init(Cipher.ENCRYPT_MODE, key);
-			byte[] cipherText = cipher.doFinal(repoUserPassword.getBytes());
-			encryptPassword = new String(coder.encode(cipherText));
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		return encryptPassword;
-	}
-
-	private static String decryptPassword(String repoUserPassword) {
-		String decryptPassword = "";
-		String secret = getSecurityKey(); // secret key length must be 16
-		SecretKey key;
-		Cipher cipher;
-		Base64 coder;
-		key = new SecretKeySpec(secret.getBytes(), "AES");
-		try {
-			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
-			coder = new Base64();
-			byte[] encrypted = coder.decode(repoUserPassword.getBytes());
-			cipher.init(Cipher.DECRYPT_MODE, key);
-			byte[] decrypted = cipher.doFinal(encrypted);
-			decryptPassword = new String(decrypted);
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		return decryptPassword;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java
deleted file mode 100644
index 3a83a54..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.utils;
-
-import java.io.File;
-import java.io.IOException;
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.XMLConstants;
-import javax.xml.namespace.QName;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.transform.Source;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.validation.Schema;
-import javax.xml.validation.SchemaFactory;
-import javax.xml.validation.Validator;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.OMFactory;
-import org.apache.axiom.om.OMNode;
-import org.apache.axiom.om.impl.builder.StAXOMBuilder;
-import org.apache.axiom.om.impl.dom.DOOMAbstractFactory;
-import org.apache.axiom.om.impl.dom.ElementImpl;
-import org.apache.axiom.om.xpath.AXIOMXPath;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.dto.Policy;
-import org.apache.stratos.adc.mgt.dto.PolicyDefinition;
-import org.jaxen.JaxenException;
-import org.w3c.dom.Element;
-import org.wso2.carbon.utils.CarbonUtils;
-import org.xml.sax.SAXException;
-
-import com.google.gson.Gson;
-
-public class PolicyHolder {
-
-	private static Log log = LogFactory.getLog(PolicyHolder.class);
-
-	private static final String POLICIES_ELEMENT = "policies";
-	private static final String POLICY_ELEMENT = "policy";
-
-	private static final String POLICIES_ELEMENT_XPATH = "/" + POLICIES_ELEMENT + "/" + POLICY_ELEMENT;
-
-	private static final String NAME_ATTR = "name";
-	private static final String IS_DEFAULT_ATTR = "isDefault";
-	private static final String DESCRIPTION_ELEMENT = "description";
-	private static final String MIN_APP_INSTANCES_ELEMENT = "min_app_instances";
-	private static final String MAX_APP_INSTANCES_ELEMENT = "max_app_instances";
-	private static final String MAX_REQUESTS_PER_SECOND_ELEMENT = "max_requests_per_second";
-	private static final String ALARMING_UPPER_RATE_ELEMENT = "alarming_upper_rate";
-	private static final String ALARMING_LOWER_RATE_ELEMENT = "alarming_lower_rate";
-	private static final String SCALE_DOWN_FACTOR_ELEMENT = "scale_down_factor";
-	private static final String ROUNDS_TO_AVERAGE_ELEMENT = "rounds_to_average";
-
-	private Map<String, Policy> policyMap = new HashMap<String, Policy>();
-
-	private Policy defaultPolicy;
-
-	private List<PolicyDefinition> policyDefinitions = new ArrayList<PolicyDefinition>();
-
-	private PolicyHolder(File policiesSchema, File policiesXML) {
-		try {
-			readPolicies(policiesSchema, policiesXML);
-		} catch (Exception e) {
-			log.error("Error reading policies", e);
-		}
-	}
-
-	private static class SingletonHolder {
-		private final static PolicyHolder INSTANCE = new PolicyHolder(new File(CarbonUtils.getCarbonConfigDirPath()
-				+ File.separator + "etc" + File.separator, "policies.xsd"), new File(
-				CarbonUtils.getCarbonConfigDirPath(), "policies.xml"));
-	}
-
-	public static PolicyHolder getInstance() {
-		return SingletonHolder.INSTANCE;
-	}
-
-	public Policy getPolicy(String policyName) {
-		return policyMap.get(policyName);
-	}
-
-	public Policy getDefaultPolicy() {
-		return defaultPolicy;
-	}
-
-	public List<PolicyDefinition> getPolicyDefinitions() {
-		return policyDefinitions;
-	}
-
-	private void readPolicies(File policiesSchema, File policiesXML) throws XMLStreamException, JaxenException,
-			SAXException, IOException {
-		if (log.isDebugEnabled()) {
-			log.debug("Policies schema: " + policiesSchema.getPath());
-			log.debug("Loading policies from file: " + policiesXML.getPath());
-		}
-		OMElement documentElement;
-		if (policiesXML.exists()) {
-			documentElement = new StAXOMBuilder(policiesXML.getPath()).getDocumentElement();
-		} else {
-			throw new IllegalStateException("Policies file cannot be found : " + policiesXML.getPath());
-		}
-
-		// Validate XML
-		validate(documentElement, policiesSchema);
-		
-		String xpath = POLICIES_ELEMENT_XPATH;
-
-		AXIOMXPath axiomXpath;
-		axiomXpath = new AXIOMXPath(xpath);
-		@SuppressWarnings("unchecked")
-		List<OMNode> policyNodes = axiomXpath.selectNodes(documentElement);
-
-		if (policyNodes == null || policyNodes.isEmpty()) {
-			log.warn("No policies found in the file : " + policiesXML.getPath());
-			return;
-		}
-
-		for (OMNode policyNode : policyNodes) {
-
-			if (policyNode.getType() == OMNode.ELEMENT_NODE) {
-
-				OMElement policyElement = (OMElement) policyNode;
-
-				try {
-					readPolicy(policyElement);
-				} catch (Exception e) {
-					log.error("Error reading policy", e);
-				}
-			}
-		}
-	}
-
-	private void readPolicy(OMElement policyElement) {
-		// retrieve attributes
-		String name = policyElement.getAttributeValue(new QName(NAME_ATTR));
-		boolean isDefault = Boolean.valueOf(policyElement.getAttributeValue(new QName(IS_DEFAULT_ATTR)));
-
-		Policy policy = new Policy();
-		policy.setName(name);
-		policy.setDefaultPolicy(isDefault);
-
-		// read description
-		Iterator<?> it = policyElement.getChildrenWithName(new QName(DESCRIPTION_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement element = (OMElement) it.next();
-			policy.setDescription(element.getText());
-		}
-
-		// read min_app_instances
-		it = policyElement.getChildrenWithName(new QName(MIN_APP_INSTANCES_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement element = (OMElement) it.next();
-			policy.setMinAppInstances(Integer.parseInt(element.getText()));
-		}
-
-		// read max_app_instances
-		it = policyElement.getChildrenWithName(new QName(MAX_APP_INSTANCES_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement element = (OMElement) it.next();
-			policy.setMaxAppInstances(Integer.parseInt(element.getText()));
-		}
-
-		// read max_requests_per_second
-		it = policyElement.getChildrenWithName(new QName(MAX_REQUESTS_PER_SECOND_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement element = (OMElement) it.next();
-			policy.setMaxRequestsPerSecond(Integer.parseInt(element.getText()));
-		}
-
-		// read rounds_to_average
-		it = policyElement.getChildrenWithName(new QName(ROUNDS_TO_AVERAGE_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement element = (OMElement) it.next();
-			policy.setRoundsToAverage(Integer.parseInt(element.getText()));
-		}
-
-		// read alarming_upper_rate
-		it = policyElement.getChildrenWithName(new QName(ALARMING_UPPER_RATE_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement element = (OMElement) it.next();
-			policy.setAlarmingUpperRate(new BigDecimal(element.getText()));
-		}
-
-		// read alarming_lower_rate
-		it = policyElement.getChildrenWithName(new QName(ALARMING_LOWER_RATE_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement element = (OMElement) it.next();
-			policy.setAlarmingLowerRate(new BigDecimal(element.getText()));
-		}
-
-		// read scale_down_factor
-		it = policyElement.getChildrenWithName(new QName(SCALE_DOWN_FACTOR_ELEMENT));
-
-		if (it.hasNext()) {
-			OMElement element = (OMElement) it.next();
-			policy.setScaleDownFactor(new BigDecimal(element.getText()));
-		}
-		if (log.isDebugEnabled()) {
-			log.debug("Policy: " + new Gson().toJson(policy));
-		}
-
-		policyMap.put(policy.getName(), policy);
-		PolicyDefinition policyDefinition = new PolicyDefinition();
-		policyDefinition.setName(policy.getName());
-		policyDefinition.setDescription(policy.getDescription());
-		policyDefinition.setDefaultPolicy(policy.isDefaultPolicy());
-		policyDefinitions.add(policyDefinition);
-		
-		// Set first default policy
-		if (defaultPolicy == null && policy.isDefaultPolicy()) {
-			defaultPolicy = policy;
-		}
-	}
-	
-	// TODO Following code is copied from
-	// org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser
-	// There should be a common util to validate XML using a schema.
-	public void validate(final OMElement omElement, final File schemaFile) throws SAXException, IOException {
-
-		Element sourceElement;
-
-		// if the OMElement is created using DOM implementation use it
-		if (omElement instanceof ElementImpl) {
-			sourceElement = (Element) omElement;
-		} else { // else convert from llom to dom
-			sourceElement = getDOMElement(omElement);
-		}
-
-		// Create a SchemaFactory capable of understanding WXS schemas.
-
-		// Load a WXS schema, represented by a Schema instance.
-		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
-		Source source = new StreamSource(schemaFile);
-
-		// Create a Validator object, which can be used to validate
-		// an instance document.
-		Schema schema = factory.newSchema(source);
-		Validator validator = schema.newValidator();
-
-		// Validate the DOM tree.
-		validator.validate(new DOMSource(sourceElement));
-	}
-
-	private Element getDOMElement(final OMElement omElement) {
-
-		// Get the StAX reader from the created element
-		XMLStreamReader llomReader = omElement.getXMLStreamReader();
-
-		// Create the DOOM OMFactory
-		OMFactory doomFactory = DOOMAbstractFactory.getOMFactory();
-
-		// Create the new builder
-		StAXOMBuilder doomBuilder = new StAXOMBuilder(doomFactory, llomReader);
-
-		// Get the document element
-		OMElement newElem = doomBuilder.getDocumentElement();
-
-		return newElem instanceof Element ? (Element) newElem : null;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java
deleted file mode 100644
index 30f8149..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java
+++ /dev/null
@@ -1,266 +0,0 @@
-package org.apache.stratos.adc.mgt.utils;
-
-import com.gitblit.Constants;
-import com.gitblit.models.RepositoryModel;
-import com.gitblit.utils.RpcUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.dao.Repository;
-import org.apache.stratos.adc.mgt.exception.ADCException;
-import org.apache.stratos.adc.mgt.service.RepositoryInfoBean;
-import org.eclipse.jgit.api.*;
-import org.eclipse.jgit.storage.file.FileRepository;
-import org.eclipse.jgit.transport.CredentialsProvider;
-import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.Iterator;
-import java.util.UUID;
-
-public class RepositoryCreator implements Runnable {
-
-	private static final Log log = LogFactory.getLog(RepositoryCreator.class);
-	private RepositoryInfoBean repoInfoBean;
-
-	public RepositoryCreator(RepositoryInfoBean repoInfoBean) {
-		this.repoInfoBean = repoInfoBean;
-	}
-
-	@Override
-	public void run() {
-
-		if (repoInfoBean != null) {
-			try {
-				createRepository(repoInfoBean.getCartridgeAlias(), repoInfoBean.getTenantDomain(),
-				                 repoInfoBean.getUserName(), repoInfoBean.getPassword());
-				createGitFolderStructure(repoInfoBean.getTenantDomain(),
-				                         repoInfoBean.getCartridgeAlias(),
-				                         repoInfoBean.getDirArray());
-
-			} catch (Exception e) {
-				log.error(e);
-			}
-		}
-	}
-
-    //Creating the internal repo in the same thread as subscribe()
-    public void createInternalRepository () throws Exception {
-
-        if (repoInfoBean != null) {
-            try {
-                createRepository(repoInfoBean.getCartridgeAlias(), repoInfoBean.getTenantDomain(),
-                        repoInfoBean.getUserName(), repoInfoBean.getPassword());
-                
-				if (repoInfoBean.getDirArray() != null && repoInfoBean.getDirArray().length > 0) {
-					createGitFolderStructure(repoInfoBean.getTenantDomain(),
-					                         repoInfoBean.getCartridgeAlias(),
-					                         repoInfoBean.getDirArray());
-				}
-
-            } catch (Exception e) {
-                String errorMsg = "Creating an internal repository failed for tenant " + repoInfoBean.getTenantDomain();
-                log.error(errorMsg, e);
-                throw new Exception(errorMsg, e);
-            }
-        }
-    }
-
-	private Repository createRepository(String cartridgeName, String tenantDomain, String userName, String password)
-	                                                                                               throws Exception {
-
-		Repository repository = new Repository();
-		String repoName = tenantDomain + "/" + cartridgeName;
-
-		try {
-			
-			log.info("Creating internal repo ["+repoName+"] ");
-
-			RepositoryModel model = new RepositoryModel();
-			model.name = repoName;
-			model.accessRestriction = Constants.AccessRestrictionType.VIEW;
-
-			char[] passwordArr = password.toCharArray();
-
-			boolean isSuccess =
-			                    RpcUtils.createRepository(model,
-			                                              "https://localhost:8443/",
-			                                              userName, passwordArr);
-			if (!isSuccess) {
-				throw new Exception("Exception is occurred when creating an internal git repo. ");
-			}
-		} catch (Exception e) {
-			log.error(" Exception is occurred when creating an internal git repo. Reason :" +
-			          e.getMessage());
-			handleException(e.getMessage(), e);
-		}
-
-		return repository;
-
-	}
-
-	private void createGitFolderStructure(String tenantDomain, String cartridgeName,
-	                                      String[] dirArray) throws Exception {
-		
-		if (log.isDebugEnabled()) {
-			log.debug("Creating git repo folder structure  ");
-		}		
-		
-		String parentDirName = "/tmp/" + UUID.randomUUID().toString();
-		CredentialsProvider credentialsProvider =
-		                                          new UsernamePasswordCredentialsProvider(
-		                                                                                  System.getProperty(CartridgeConstants.INTERNAL_GIT_USERNAME),
-		                                                                                  System.getProperty(CartridgeConstants.INTERNAL_GIT_PASSWORD).toCharArray());
-		// Clone
-		// --------------------------
-		FileRepository localRepo = null;
-		try {
-			localRepo = new FileRepository(new File(parentDirName + "/.git"));
-		} catch (IOException e) {
-			log.error("Exception occurred in creating a new file repository. Reason: " + e.getMessage());
-			throw e;
-		}
-
-		Git git = new Git(localRepo);
-
-		CloneCommand cloneCmd =
-		                        git.cloneRepository()
-		                           .setURI("https://localhost:8443/git/" + tenantDomain + "/" +
-		                                           cartridgeName + ".git")
-		                           .setDirectory(new File(parentDirName));
-
-		cloneCmd.setCredentialsProvider(credentialsProvider);
-		try {
-			log.debug("Clonning git repo");
-			cloneCmd.call();
-		} catch (Exception e1) {
-			log.error("Exception occurred in cloning Repo. Reason: " + e1.getMessage());
-			throw e1;
-		}
-		// ------------------------------------
-
-		// --- Adding directory structure --------
-
-		File parentDir = new File(parentDirName);
-		parentDir.mkdir();
-
-		for (String string : dirArray) {
-			String[] arr = string.split("=");
-			if (log.isDebugEnabled()) {
-				log.debug("Creating dir: " + arr[0]);
-			}
-			File parentFile = new File(parentDirName + "/" + arr[0]);
-			parentFile.mkdirs();
-
-			File filess = new File(parentFile, "README");
-			String content = "Content goes here";
-
-			filess.createNewFile();
-			FileWriter fw = new FileWriter(filess.getAbsoluteFile());
-			BufferedWriter bw = new BufferedWriter(fw);
-			bw.write(content);
-			bw.close();
-		}
-		// ----------------------------------------------------------
-
-		// ---- Git status ---------------
-		StatusCommand s = git.status();
-		Status status = null;
-		try {
-			log.debug("Getting git repo status");
-			status = s.call();
-		} catch (Exception e) {
-			log.error("Exception occurred in git status check. Reason: " + e.getMessage());
-			throw e;
-		}
-		// --------------------------------
-
-		// ---------- Git add ---------------
-		AddCommand addCmd = git.add();
-		Iterator<String> it = status.getUntracked().iterator();
-
-		while (it.hasNext()) {
-			addCmd.addFilepattern(it.next());
-		}
-
-		try {
-			log.debug("Adding files to git repo");
-			addCmd.call();
-		} catch (Exception e) {
-			log.error("Exception occurred in adding files. Reason: " + e.getMessage());
-			throw e;
-		}
-		// -----------------------------------------
-
-		// ------- Git commit -----------------------
-
-		CommitCommand commitCmd = git.commit();
-		commitCmd.setMessage("Adding directories");
-
-		try {
-			log.debug("Committing git repo");
-			commitCmd.call();
-		} catch (Exception e) {
-			log.error("Exception occurred in committing . Reason: " + e.getMessage());
-			throw e;
-		}
-		// --------------------------------------------
-
-		// --------- Git push -----------------------
-		PushCommand pushCmd = git.push();
-		pushCmd.setCredentialsProvider(credentialsProvider);
-		try {
-			log.debug("Git repo push");
-			pushCmd.call();
-		} catch (Exception e) {
-			log.error("Exception occurred in Git push . Reason: " + e.getMessage());
-			throw e;
-		}
-
-		try {
-			deleteDirectory(new File(parentDirName));
-		} catch (Exception e) {
-			log.error("Exception occurred in deleting temp files. Reason: " + e.getMessage());
-			throw e;
-		}
-
-		log.info(" Folder structure  is created ..... ");
-
-	}
-
-	private void handleException(String msg, Exception e) throws Exception {
-		log.error(msg, e);
-		throw new Exception(msg, e);
-	}
-
-	private void deleteDirectory(File file) throws IOException {
-
-		if (file.isDirectory()) {
-			// directory is empty, then delete it
-			if (file.list().length == 0) {
-				file.delete();
-
-			} else {
-				// list all the directory contents
-				String files[] = file.list();
-
-				for (String temp : files) {
-					// construct the file structure
-					File fileDelete = new File(file, temp);
-					// recursive delete
-					deleteDirectory(fileDelete);
-				}
-				// check the directory again, if empty then delete it
-				if (file.list().length == 0) {
-					file.delete();
-				}
-			}
-
-		} else {
-			// if file, then delete it
-			file.delete();
-		}
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java
deleted file mode 100644
index d0dd919..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.utils;
-
-import java.io.File;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.dao.Repository;
-import org.apache.stratos.adc.mgt.service.ApplicationManagementService;
-import org.wso2.carbon.utils.CarbonUtils;
-
-/**
- * @author wso2
- * 
- */
-public class RepositoryFactory {
-
-	private static final Log log = LogFactory.getLog(ApplicationManagementService.class);
-
-	/*public synchronized Repository createRepository(String cartridgeName, String tenantDomain,
-	                                          String userName) throws Exception {
-
-		Repository repository = new Repository();
-		String repoName = tenantDomain + "/" + cartridgeName; // removed .git part
-		String repoUserName = userName + "@" + tenantDomain;
-
-		Process proc;
-		try {
-
-			String command =
-			                 CarbonUtils.getCarbonHome() + File.separator + "bin" + File.separator +
-			                         "manage-git-repo.sh " + "create " + repoUserName + " " +
-			                         tenantDomain + " " + cartridgeName + " " +
-			                         System.getProperty(CartridgeConstants.REPO_NOTIFICATION_URL) + " " +
-			                         System.getProperty(CartridgeConstants.GIT_HOST_NAME) +
-			                         " /";
-			proc = Runtime.getRuntime().exec(command);
-			log.info("executing manage-git-repo script..... command :" + command);
-			proc.waitFor();
-			log.info(" Repo is created ..... for user: " + userName + ", tenantName: " +
-			         tenantDomain + " ");
-			repository.setRepoName("git@" + System.getProperty(CartridgeConstants.GIT_HOST_NAME) + ":" +repoName);
-		} catch (Exception e) {
-			log.error(" Exception is occurred when executing manage-git-repo script. Reason :" +
-			          e.getMessage());
-			handleException(e.getMessage(), e);
-		}
-
-		return repository;
-
-	}*/
-
-	/*public synchronized void createGitFolderStructure(String tenantDomain, String cartridgeName,
-	                                            String[] dirArray) throws Exception {
-
-		log.info("In create Git folder structure...!");
-
-		StringBuffer dirBuffer = new StringBuffer();
-		for (String dir : dirArray) {
-			dirBuffer.append(dir).append(" ");
-		}
-
-		Process proc;
-		try {
-			String command =
-			                 CarbonUtils.getCarbonHome() + File.separator + "bin" + File.separator +
-			                         "git-folder-structure.sh " + tenantDomain + " " +
-			                         cartridgeName + " " + dirBuffer.toString() + " /";
-			proc = Runtime.getRuntime().exec(command);
-			log.info("executing manage-git-repo script..... command : " + command);
-			proc.waitFor();
-
-		} catch (Exception e) {
-			log.error(" Exception is occurred when executing manage-git-repo script. Reason :" +
-			          e.getMessage());
-			handleException(e.getMessage(), e);
-		}
-
-		log.info(" Folder structure  is created ..... ");
-
-	}*/
-	
-	public synchronized void destroyRepository(String cartridgeName, String tenantDomain,
-	                                          String userName) throws Exception {
-
-		String repoUserName = userName + "@" + tenantDomain;
-
-		Process proc;
-		try {
-
-			String command =
-			                 CarbonUtils.getCarbonHome() + File.separator + "bin" + File.separator +
-			                         "manage-git-repo.sh " + "destroy " + repoUserName + " " +
-			                         tenantDomain + " " + cartridgeName + 
-			                         " /";
-			proc = Runtime.getRuntime().exec(command);
-			log.info("executing manage-git-repo script (destroy)..... command :" + command);
-			proc.waitFor();
-			log.info(" Repo is destroyed ..... for user: " + userName + ", tenantName: " +
-			         tenantDomain + " ");
-		} catch (Exception e) {
-			log.error(" Exception is occurred when destroying git repo. Reason :" +
-			          e.getMessage());
-			handleException(e.getMessage(), e);
-		}
-
-	}
-
-	private void handleException(String msg, Exception e) throws Exception {
-		log.error(msg, e);
-		throw new Exception(msg, e);
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java
deleted file mode 100644
index 7a4736d..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.utils;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.tomcat.jdbc.pool.DataSource;
-import org.apache.tomcat.jdbc.pool.PoolProperties;
-
-public final class StratosDBUtils {
-
-	private static final Log log = LogFactory.getLog(StratosDBUtils.class);
-
-	private static volatile javax.sql.DataSource dataSource = null;
-
-	/**
-	 * Initializes the data source
-	 * 
-	 * @throws RuntimeException
-	 *             if an error occurs while loading DB configuration
-	 */
-	public static void initialize() throws Exception {
-		if (dataSource != null) {
-			return;
-		}
-
-		synchronized (StratosDBUtils.class) {
-			if (dataSource == null) {
-
-				String datasourceName = System.getProperty(CartridgeConstants.DB_DATASOURCE);
-
-				if (datasourceName != null && datasourceName.trim().length() > 0) {
-					if (log.isInfoEnabled()) {
-						log.info("Initializing data source: " + datasourceName);
-					}
-					try {
-						Context ctx = new InitialContext();
-						dataSource = (DataSource) ctx.lookup(datasourceName);
-						if (dataSource != null && log.isInfoEnabled()) {
-							log.info("Found data source: " + datasourceName + ", " + dataSource.getClass().getName());
-						}
-					} catch (NamingException e) {
-						throw new RuntimeException("Error while looking up the data source: " + datasourceName, e);
-					}
-				} else {
-					// FIXME Should we use system properties to get database
-					// details?
-					String dbUrl = System.getProperty(CartridgeConstants.DB_URL);
-					String driver = System.getProperty(CartridgeConstants.DB_DRIVER);
-					String username = System.getProperty(CartridgeConstants.DB_USERNAME);
-					String password = System.getProperty(CartridgeConstants.DB_PASSWORD);
-
-					if (dbUrl == null || driver == null || username == null || password == null) {
-						String msg = "Required DB configuration parameters are not specified.";
-						log.warn(msg);
-						throw new RuntimeException(msg);
-					}
-					
-					if (log.isInfoEnabled()) {
-						log.info("Initializing data source for JDBC URL: " + dbUrl);
-					}
-
-					PoolProperties p = new PoolProperties();
-					p.setUrl(dbUrl);
-					p.setDriverClassName(driver);
-					p.setUsername(username);
-					p.setPassword(password);
-					p.setJmxEnabled(true);
-					p.setTestWhileIdle(false);
-					p.setTestOnBorrow(true);
-					p.setValidationQuery("SELECT 1");
-					p.setTestOnReturn(false);
-					p.setValidationInterval(30000);
-					p.setTimeBetweenEvictionRunsMillis(30000);
-					p.setMaxActive(100);
-					p.setInitialSize(10);
-					p.setMaxWait(10000);
-					p.setRemoveAbandonedTimeout(60);
-					p.setMinEvictableIdleTimeMillis(30000);
-					p.setMinIdle(10);
-					p.setLogAbandoned(true);
-					p.setRemoveAbandoned(true);
-					p.setDefaultAutoCommit(false);
-					p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
-							+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
-					DataSource tomcatDatasource = new DataSource();
-					tomcatDatasource.setPoolProperties(p);
-
-					dataSource = tomcatDatasource;
-				}
-
-			}
-		}
-	}
-
-	/**
-	 * Utility method to get a new database connection
-	 * 
-	 * @return Connection
-	 * @throws java.sql.SQLException
-	 *             if failed to get Connection
-	 */
-	public static Connection getConnection() throws SQLException {
-		if (dataSource != null) {
-			return dataSource.getConnection();
-		}
-		throw new SQLException("Datasource is not configured properly.");
-	}
-
-	/**
-	 * Utility method to close the connection streams.
-	 * 
-	 * @param connection
-	 *            Connection
-	 * @param preparedStatement
-	 *            PreparedStatement
-	 * @param resultSet
-	 *            ResultSet
-	 */
-	public static void closeAllConnections(Connection connection, PreparedStatement preparedStatement,
-			ResultSet resultSet) {
-		closeResultSet(resultSet);
-		closeStatement(preparedStatement);
-		closeConnection(connection);
-	}
-
-	public static void closeAllConnections(Connection connection, PreparedStatement... preparedStatements) {
-		for (PreparedStatement preparedStatement : preparedStatements) {
-			closeStatement(preparedStatement);
-		}
-		closeConnection(connection);
-	}
-
-	/**
-	 * Close Connection
-	 * 
-	 * @param dbConnection
-	 *            Connection
-	 */
-	public static void closeConnection(Connection dbConnection) {
-		if (dbConnection != null) {
-			try {
-				dbConnection.close();
-			} catch (SQLException e) {
-				log.warn(
-						"Database error. Could not close database connection. Continuing with " + "others. - "
-								+ e.getMessage(), e);
-			}
-		}
-	}
-
-	/**
-	 * Close ResultSet
-	 * 
-	 * @param resultSet
-	 *            ResultSet
-	 */
-	public static void closeResultSet(ResultSet resultSet) {
-		if (resultSet != null) {
-			try {
-				resultSet.close();
-			} catch (SQLException e) {
-				log.warn("Database error. Could not close ResultSet  - " + e.getMessage(), e);
-			}
-		}
-
-	}
-
-	/**
-	 * Close PreparedStatement
-	 * 
-	 * @param preparedStatement
-	 *            PreparedStatement
-	 */
-	public static void closeStatement(PreparedStatement preparedStatement) {
-		if (preparedStatement != null) {
-			try {
-				preparedStatement.close();
-			} catch (SQLException e) {
-				log.warn(
-						"Database error. Could not close PreparedStatement. Continuing with" + " others. - "
-								+ e.getMessage(), e);
-			}
-		}
-
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java
deleted file mode 100644
index 6905a51..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.utils;
-
-import org.apache.axis2.clustering.ClusteringCommand;
-import org.apache.axis2.clustering.ClusteringFault;
-import org.apache.axis2.clustering.ClusteringMessage;
-import org.apache.axis2.clustering.management.GroupManagementCommand;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.engine.AxisConfigurator;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.util.tracker.ServiceTracker;
-import org.wso2.carbon.core.CarbonAxisConfigurator;
-import org.wso2.carbon.core.internal.CarbonCoreDataHolder;
-import org.wso2.carbon.core.multitenancy.TenantAxisConfigurator;
-import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
-import org.wso2.carbon.utils.CarbonUtils;
-import org.wso2.carbon.utils.deployment.GhostDeployerUtils;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
-
-import java.util.UUID;
-
-/**
- * ClusterMessage for sending a deployment repository synchronization request
- */
-public class SynchronizeRepositoryRequest extends GroupManagementCommand {
-
-	/**
-     * 
-     */
-	private static final long serialVersionUID = 8717694086109561127L;
-
-	private transient static final Log log = LogFactory.getLog(SynchronizeRepositoryRequest.class);
-	private int tenantId;
-	private String tenantDomain;
-	private UUID messageId;
-
-	public SynchronizeRepositoryRequest() {
-	}
-
-	public SynchronizeRepositoryRequest(int tenantId, String tenantDomain, UUID messageId) {
-		this.tenantId = tenantId;
-		this.tenantDomain = tenantDomain;
-		this.messageId = messageId;
-	}
-
-	public void setTenantId(int tenantId) {
-		this.tenantId = tenantId;
-	}
-
-	public void execute(ConfigurationContext configContext) throws ClusteringFault {
-		log.info("Received  [" + this + "] ");
-		// Run only if the tenant is loaded
-		if (tenantId == MultitenantConstants.SUPER_TENANT_ID ||
-		    TenantAxisUtils.getTenantConfigurationContexts(configContext).get(tenantDomain) != null) {
-			updateDeploymentRepository(configContext);
-			doDeployment(configContext);
-		}
-	}
-
-	private void doDeployment(ConfigurationContext configContext) {
-		AxisConfigurator axisConfigurator = configContext.getAxisConfiguration().getConfigurator();
-		if (axisConfigurator instanceof CarbonAxisConfigurator) {
-			((CarbonAxisConfigurator) axisConfigurator).runDeployment();
-		} else if (axisConfigurator instanceof TenantAxisConfigurator) {
-			((TenantAxisConfigurator) axisConfigurator).runDeployment();
-		}
-	}
-
-	private void updateDeploymentRepository(ConfigurationContext configContext) {
-
-		log.info(" Update Deployment Repo...");
-		/*
-		 * BundleContext bundleContext =
-		 * CarbonCoreDataHolder.getInstance().getBundleContext();
-		 * ServiceReference reference =
-		 * bundleContext.getServiceReference(DeploymentSynchronizer.class.getName
-		 * ());
-		 * if (reference != null) {
-		 * ServiceTracker serviceTracker =
-		 * new ServiceTracker(bundleContext,
-		 * DeploymentSynchronizer.class.getName(), null);
-		 * try {
-		 * serviceTracker.open();
-		 * for (Object obj : serviceTracker.getServices()) {
-		 * // if the update is for worker node with ghost ON, then we will
-		 * update the
-		 * // whole repo for now. See CARBON-13899
-		 * if (GhostDeployerUtils.isGhostOn() && CarbonUtils.isWorkerNode() &&
-		 * tenantId > 0) {
-		 * String repoPath = MultitenantUtils.getAxis2RepositoryPath(tenantId);
-		 * ((DeploymentSynchronizer) obj).update(repoPath, repoPath, 3);
-		 * } else {
-		 * ((DeploymentSynchronizer) obj).update(tenantId);
-		 * }
-		 * }
-		 * } catch (Exception e) {
-		 * log.error("Repository update failed for tenant " + tenantId, e);
-		 * setRepoUpdateFailed(configContext);
-		 * } finally {
-		 * serviceTracker.close();
-		 * }
-		 * }
-		 */
-	}
-
-	private void setRepoUpdateFailed(ConfigurationContext configContext) {
-		AxisConfigurator axisConfigurator = configContext.getAxisConfiguration().getConfigurator();
-		if (axisConfigurator instanceof CarbonAxisConfigurator) {
-			((CarbonAxisConfigurator) axisConfigurator).setRepoUpdateFailed();
-		} else if (axisConfigurator instanceof TenantAxisConfigurator) {
-			((TenantAxisConfigurator) axisConfigurator).setRepoUpdateFailed();
-		}
-	}
-
-	public ClusteringCommand getResponse() {
-		return null;
-	}
-
-	@Override
-	public String toString() {
-		return "SynchronizeRepositoryRequest{" + "tenantId=" + tenantId + ", tenantDomain='" +
-		       tenantDomain + '\'' + ", messageId=" + messageId + '}';
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml
deleted file mode 100644
index a7ddc11..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,86 +0,0 @@
-<!-- ~ Copyright WSO2 Inc. (http://www.wso2.com) All Rights
-	Reserved. ~ ~ WSO2 Inc. licenses this file to you under the Apache License, 
-	~ Version 2.0 (the "License"); you may not use this file except ~ in compliance 
-	with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 
-	~ ~ Unless required by applicable law or agreed to in writing, ~ software 
-	distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT 
-	WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the 
-	License for the ~ specific language governing permissions and limitations 
-	~ under the License. -->
-<serviceGroup>
-	<service name="ApplicationManagementService" scope="transportsession">
-		<transports>
-			<transport>https</transport>
-		</transports>
-		<description>
-			Admin service for ADC activities
-		</description>
-		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.ApplicationManagementService
-        </parameter>
-		<parameter name="enableMTOM">true</parameter>
-		<parameter name="adminService" locked="true">true</parameter>
-		<parameter name="hiddenService" locked="true">true</parameter>
-		<parameter name="AuthorizationAction" locked="true">
-			/permission/admin/manage/modify/webapp    </parameter>
-		<parameter name="DoAuthentication" locked="true">true</parameter>
-	</service>
-
-	<service name="RepoNotificationService" scope="transportsession">
-		<schema schemaNamespace="http://org.apache.axis2/xsd"
-			elementFormDefaultQualified="true" />
-		<transports>
-			<transport>https</transport>
-		</transports>
-		<description>
-			Admin service for receiving git repo update notifications
-		</description>
-		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.RepoNotificationService
-		</parameter>
-		<parameter name="enableMTOM">true</parameter>
-		<parameter name="adminService" locked="true">false</parameter>
-		<parameter name="hiddenService" locked="true">false</parameter>
-		<parameter name="AuthorizationAction" locked="false">
-			/permission/admin/manage/modify/webapp
-    </parameter>
-	</service>
-
-	<service name="RepositoryInformationService" scope="transportsession">
-		<schema schemaNamespace="http://org.apache.axis2/xsd"
-			elementFormDefaultQualified="true" />
-		<transports>
-			<transport>https</transport>
-		</transports>
-		<description>
-			Exposes information related to internally created
-			repositories
-        </description>
-		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.RepositoryInformationService
-		</parameter>
-		<parameter name="enableMTOM">true</parameter>
-		<parameter name="adminService" locked="true">false</parameter>
-		<parameter name="hiddenService" locked="true">false</parameter>
-		<parameter name="AuthorizationAction" locked="false">
-			/permission/admin/manage/modify/webapp
-    	</parameter>
-	</service>
-
-	<service name="InstanceInformationManagementService" scope="transportsession">
-		<schema schemaNamespace="http://org.apache.axis2/xsd"
-			elementFormDefaultQualified="true" />
-		<transports>
-			<transport>https</transport>
-		</transports>
-		<description>
-			Exposes information related to internally created
-			repositories
-        </description>
-		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.InstanceInformationManagementService</parameter>
-		<parameter name="enableMTOM">true</parameter>
-		<parameter name="adminService" locked="true">false</parameter>
-		<parameter name="hiddenService" locked="true">false</parameter>
-		<parameter name="AuthorizationAction" locked="false">
-			/permission/admin/manage/modify/webapp
-    	</parameter>
-	</service>
-
-</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/policies.xsd
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/policies.xsd b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/policies.xsd
deleted file mode 100644
index 87f7b58..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/policies.xsd
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<xs:schema attributeFormDefault="unqualified"
-	elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
-	<xs:element name="policies">
-		<xs:annotation>
-			<xs:documentation>Use below section to specify auto-scaling policies
-				for cartridges.
-			</xs:documentation>
-		</xs:annotation>
-		<xs:complexType>
-			<xs:sequence>
-				<xs:element name="policy" maxOccurs="unbounded"
-					minOccurs="1">
-					<xs:annotation>
-						<xs:documentation>You can have 1..n policy elements.
-						</xs:documentation>
-					</xs:annotation>
-					<xs:complexType>
-						<xs:sequence>
-							<xs:element type="xs:string" name="description" />
-							<xs:element type="xs:integer" name="min_app_instances" />
-							<xs:element type="xs:integer" name="max_app_instances" />
-							<xs:element type="xs:integer" name="max_requests_per_second" />
-							<xs:element type="xs:decimal" name="alarming_upper_rate" />
-							<xs:element type="xs:decimal" name="alarming_lower_rate" />
-							<xs:element type="xs:decimal" name="scale_down_factor" />
-							<xs:element type="xs:integer" name="rounds_to_average" />
-						</xs:sequence>
-						<xs:attribute type="xs:string" name="name" use="required" />
-						<xs:attribute type="xs:boolean" name="isDefault" use="required" />
-					</xs:complexType>
-				</xs:element>
-			</xs:sequence>
-		</xs:complexType>
-	</xs:element>
-</xs:schema>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/scripts/append_zone_file.sh
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/scripts/append_zone_file.sh b/components/org.apache.stratos.adc.mgt/2.1.3/src/scripts/append_zone_file.sh
deleted file mode 100755
index 45491df..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/scripts/append_zone_file.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/bash
-echo "subdomain $1 and ip $2 added to $3"
-appending_file=$3
-subdomain=$1
-ip=$2
-
-#appending the zone file
-echo $subdomain'\t'IN'\t'A'\t'$ip>> $appending_file
-
-#increasing the count
-for file in $appending_file;
-do
-  if [ -f $file ];
-  then
-    OLD=`egrep -ho "2010-9[0-9]*" $file`
-    NEW=$(($OLD + 1))
-    sed -i "s/$OLD/$NEW/g" $file
-    echo "fixed $file" 
-  fi
-done
-
-
-#reloading bind server
-/etc/init.d/bind9 reload

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java
deleted file mode 100644
index ba350aa..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package org.apache.stratos.adc.mgt.test;
-
-import java.io.File;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-
-import junit.framework.TestCase;
-
-import org.apache.stratos.adc.mgt.utils.PolicyHolder;
-
-public class PolicyHolderTest extends TestCase {
-
-	private PolicyHolder getPolicyHolder(String policiesXMLFile) {
-		File policiesXmlSchema = new File("src/main/resources/policies.xsd");
-		String dir = "src/test/resources/";
-
-		Class<PolicyHolder> clazz = PolicyHolder.class;
-
-		Constructor<PolicyHolder> c;
-		try {
-			c = clazz.getDeclaredConstructor(File.class, File.class);
-			c.setAccessible(true);
-		} catch (NoSuchMethodException e) {
-			throw new RuntimeException(e);
-		} catch (SecurityException e) {
-			throw new RuntimeException(e);
-		}
-		PolicyHolder policyHolder;
-		try {
-			policyHolder = c.newInstance(policiesXmlSchema, new File(dir, policiesXMLFile));
-		} catch (InstantiationException e) {
-			throw new RuntimeException(e);
-		} catch (IllegalAccessException e) {
-			throw new RuntimeException(e);
-		} catch (IllegalArgumentException e) {
-			throw new RuntimeException(e);
-		} catch (InvocationTargetException e) {
-			throw new RuntimeException(e);
-		}
-		return policyHolder;
-	}
-
-	public void testDefaultPolicy() {
-		PolicyHolder policyHolder = getPolicyHolder("policies-1.xml");
-		assertNotNull(policyHolder);
-		assertNotNull(policyHolder.getDefaultPolicy());
-	}
-	
-	
-	public void testSinglePolicy() {
-		PolicyHolder policyHolder = getPolicyHolder("policies-1.xml");
-		assertNotNull(policyHolder);
-		assertNotNull(policyHolder.getPolicy("single"));
-		assertEquals("single", policyHolder.getPolicy("single").getName());
-	}
-	
-	public void testElasticPolicy() {
-		PolicyHolder policyHolder = getPolicyHolder("policies-1.xml");
-		assertNotNull(policyHolder);
-		assertNotNull(policyHolder.getPolicy("elastic"));
-		assertEquals("elastic", policyHolder.getPolicy("elastic").getName());
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/log4j.properties b/components/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/log4j.properties
deleted file mode 100644
index d30536d..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/log4j.properties
+++ /dev/null
@@ -1,8 +0,0 @@
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-log4j.appender.console.Target=System.out
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} [%t] %n%m%n
-
-#Loggers
-log4j.rootLogger=info, console
-log4j.logger.org.apache.stratos.adc.mgt=trace
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/policies-1.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/policies-1.xml b/components/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/policies-1.xml
deleted file mode 100644
index 7dd37d5..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/policies-1.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<policies>
-	<policy name="single" isDefault="true">
-		<description>Single - Instances: Min 1, Max 1</description>
-		<min_app_instances>1</min_app_instances>
-		<max_app_instances>1</max_app_instances>
-		<max_requests_per_second>5</max_requests_per_second>
-		<alarming_upper_rate>0.7</alarming_upper_rate>
-		<alarming_lower_rate>0.2</alarming_lower_rate>
-		<scale_down_factor>0.25</scale_down_factor>
-		<rounds_to_average>2</rounds_to_average>
-	</policy>
-	<policy name="elastic" isDefault="false">
-		<description>Elastic - Instances: Min 1, Max 4</description>
-		<min_app_instances>1</min_app_instances>
-		<max_app_instances>4</max_app_instances>
-		<max_requests_per_second>5</max_requests_per_second>
-		<alarming_upper_rate>0.7</alarming_upper_rate>
-		<alarming_lower_rate>0.2</alarming_lower_rate>
-		<scale_down_factor>0.25</scale_down_factor>
-		<rounds_to_average>2</rounds_to_average>
-	</policy>
-</policies>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/pom.xml b/components/org.apache.stratos.adc.mgt/pom.xml
new file mode 100644
index 0000000..4ef0984
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/pom.xml
@@ -0,0 +1,142 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+	<parent>
+		<groupId>org.apache.stratos</groupId>
+		<artifactId>stratos-components-parent</artifactId>
+		<version>3.0.0-SNAPSHOT</version>
+	</parent>
+
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>org.apache.stratos.adc.mgt</artifactId>
+	<packaging>bundle</packaging>
+	<name>Apache Stratos - ADC BE</name>
+	<description>BE functionalities of ADC</description>
+	<url>http://apache.org</url>
+
+	<dependencies>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.registry.ws.client</artifactId>
+		</dependency>
+		<!--<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> 
+			</dependency> -->
+		<dependency>
+			<groupId>org.apache.stratos</groupId>
+			<artifactId>org.apache.stratos.load.balance.cartridge.autoscaler.service.stub</artifactId>
+			<version>${apache.stratos.version}</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.apache.stratos</groupId>
+			<artifactId>org.apache.stratos.adc.topology.mgt</artifactId>
+			<version>${apache.stratos.version}</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.utils</artifactId>
+			<version>${wso2carbon.version}</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.cartridge.agent.stub</artifactId>
+			<version>4.1.1</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.apache.tomcat.wso2</groupId>
+			<artifactId>jdbc-pool</artifactId>
+			<version>${version.tomcat}.wso2v1</version>
+		</dependency>
+
+		<dependency>
+			<groupId>com.gitblit</groupId>
+			<artifactId>gitblit</artifactId>
+			<version>1.2.0.wso2v1</version>
+		</dependency>
+		<dependency>
+			<groupId>com.google.code.gson</groupId>
+			<artifactId>gson</artifactId>
+			<version>2.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.jgit</groupId>
+            <artifactId>org.eclipse.jgit</artifactId>
+            <version>2.1.0.wso2v1</version>
+        </dependency>
+        <dependency>
+            <groupId>com.jcraft</groupId>
+            <artifactId>jsch</artifactId>
+            <version>0.1.49.wso2v1</version>
+        </dependency>
+		<dependency>
+			<groupId>junit</groupId>
+			<artifactId>junit</artifactId>
+			<scope>test</scope>
+		</dependency>
+	</dependencies>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.felix</groupId>
+				<artifactId>maven-scr-plugin</artifactId>
+			</plugin>
+			<plugin>
+				<groupId>org.apache.felix</groupId>
+				<artifactId>maven-bundle-plugin</artifactId>
+
+				<extensions>true</extensions>
+				<configuration>
+					<instructions>
+						<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+						<Bundle-Name>${project.artifactId}</Bundle-Name>
+						<Bundle-Activator>
+							org.apache.stratos.adc.mgt.internal.HostingManagementActivator
+                                                </Bundle-Activator>
+						<Private-Package>org.apache.stratos.adc.mgt.internal.*</Private-Package>
+						<Export-Package>
+							org.apache.stratos.adc.mgt.utils*,
+							org.apache.stratos.adc.mgt.service.*,
+							org.apache.stratos.adc.mgt.*
+                        			</Export-Package>
+						<Import-Package>
+							org.apache.axis2.*; version="1.6.1.wso2v6",
+							org.apache.axiom.*;
+							version="1.2.11.wso2v2",
+							org.apache.neethi.*;
+							version="2.0.4.wso2v4",
+							javax.xml.stream.*; version="1.0.1",
+							javax.wsdl.*; version="1.6.2",
+							org.osgi.framework.*,
+							*;resolution:=optional
+                        			</Import-Package>
+						<DynamicImport-Package>*</DynamicImport-Package>
+					</instructions>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+</project>


[20/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentServiceComponent.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentServiceComponent.java
new file mode 100644
index 0000000..b31cc7a
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentServiceComponent.java
@@ -0,0 +1,142 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+
+package org.apache.stratos.cartridge.agent.internal;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cartridge.agent.ClusteringClient;
+import org.apache.stratos.cartridge.agent.ELBMembershipListener;
+import org.apache.stratos.cartridge.agent.registrant.RegistrantDatabase;
+import org.apache.stratos.cartridge.agent.registrant.RegistrantHealthChecker;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.Properties;
+
+/**
+ * @scr.component name="org.wso2.carbon.cartridge.agent" immediate="true"
+ *
+ * @scr.reference name="config.context.service"
+ *                interface="org.wso2.carbon.utils.ConfigurationContextService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setConfigurationContextService"
+ *                unbind="unsetConfigurationContextService"
+ */
+public class CartridgeAgentServiceComponent {
+    private static final Log log = LogFactory.getLog(CartridgeAgentServiceComponent.class);
+
+    protected void activate(ComponentContext ctx) {
+        RegistrantHealthChecker healthChecker;
+        ConfigurationContext configurationContext = DataHolder.getServerConfigContext();
+
+        FileInputStream confFileIPStream = null;
+        try {
+            long start = System.currentTimeMillis();
+            log.info("Starting WSO2 Cartridge Agent...");
+            Properties conf = new Properties();
+            confFileIPStream = new FileInputStream(CarbonUtils.getCarbonConfigDirPath() +
+                    File.separator + "agent.properties");
+            conf.load(confFileIPStream);            
+            for (String name : conf.stringPropertyNames()) {
+    			String value = conf.getProperty(name);
+    			System.setProperty(name, value);
+    		}
+            
+            RegistrantDatabase registrantDatabase = new RegistrantDatabase();
+//            AxisServer axisServer = new AxisServer();
+//            ConfigurationContext configurationContext = axisServer.getConfigurationContext();
+            ClusteringClient clusteringClient = new ClusteringClient(registrantDatabase);
+            configurationContext.setProperty(CartridgeAgentConstants.CLUSTERING_CLIENT, clusteringClient);
+
+            String healthCheckInterval = conf.getProperty("registrant.heathCheckInterval");
+            String threadPoolSize = conf.getProperty("registrant.healthCheckThreadPoolSize");
+            int healthCheckIntervalInt =
+                    (healthCheckInterval == null) ? 2000 : Integer.parseInt(healthCheckInterval);
+            int threadPoolSizeInt =
+                    (threadPoolSize == null) ? 10 : Integer.parseInt(healthCheckInterval);
+            log.info("Registrant health check interval: " + healthCheckIntervalInt + "s");
+            healthChecker = new RegistrantHealthChecker(registrantDatabase,
+                    clusteringClient,
+                    configurationContext,
+                    healthCheckIntervalInt,
+                    threadPoolSizeInt
+            );
+            clusteringClient.init(conf,
+                    configurationContext,
+                    new ELBMembershipListener(clusteringClient,
+                            configurationContext,
+                            registrantDatabase,
+                            healthChecker));
+            healthChecker.startAll();
+            DataHolder.setHealthChecker(healthChecker);
+            /*configurationContext.deployService(AxisService.createService(CartridgeAgentService.class.getName().toString(),
+                     configurationContext.getAxisConfiguration()));*/
+//            axisServer.deployService(CartridgeAgentService.class.getName());
+
+
+            // Starting cliet..
+//            String trustStorePath = conf.getProperty("wso2.carbon.truststore");
+//            System.setProperty("javax.net.ssl.trustStore", trustStorePath);
+//            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
+//            // new InstanceStateNotificationClient().notify(null, null);
+//
+//            System.setProperty("adc.host",  conf.getProperty("adc.host"));
+//            System.setProperty("adc.port",  conf.getProperty("adc.port"));
+            // ----------------------
+
+            Runtime.getRuntime().addShutdownHook(new Thread(){
+
+                @Override
+                public void run() {
+                    log.info("Shutting down WSO2 Cartridge Agent...");
+                }
+            });
+            log.info("Started Cartridge Agent in " + (System.currentTimeMillis() - start) + "ms");
+        } catch (Exception e) {
+            log.fatal("Could not start Cartridge Agent", e);
+            //System.exit(1);
+        } finally {
+            if (confFileIPStream != null) {
+                try {
+                    confFileIPStream.close();
+                } catch (IOException e) {
+                    log.error("Cannot close agent.properties file", e);
+                }
+            }
+        }
+
+    }
+
+    protected void deactivate(ComponentContext ctx) {
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        DataHolder.setServerConfigContext(contextService.getServerConfigContext());
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/DataHolder.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/DataHolder.java
new file mode 100644
index 0000000..955c931
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/DataHolder.java
@@ -0,0 +1,45 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+
+package org.apache.stratos.cartridge.agent.internal;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.cartridge.agent.registrant.RegistrantHealthChecker;
+
+public class DataHolder {
+    private static ConfigurationContext serverConfigContext;
+    private static RegistrantHealthChecker healthChecker;
+
+    public static void setServerConfigContext(ConfigurationContext serverConfigContext) {
+        DataHolder.serverConfigContext = serverConfigContext;
+    }
+
+    public static void setHealthChecker(RegistrantHealthChecker healthChecker) {
+        DataHolder.healthChecker = healthChecker;
+    }
+
+    public static ConfigurationContext getServerConfigContext() {
+        return serverConfigContext;
+    }
+
+    public static RegistrantHealthChecker getHealthChecker() {
+        return healthChecker;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/PortMapping.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/PortMapping.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/PortMapping.java
new file mode 100644
index 0000000..3d1bc8b
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/PortMapping.java
@@ -0,0 +1,90 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent.registrant;
+
+import java.io.Serializable;
+
+/**
+ * This class provides the mapping between the actual port &amp; proxy port of a {@link org.apache.stratos.cartridge.agent.registrant.Registrant}
+ *
+ * e.g. if the Registrant is serving HTTP requests on port 9763, and the requests to that port have
+ * to be proxied via port 80 on the ELB, the <code>primaryPort</code> has to be specified as 9763
+ * &amp; <code>proxyPort</code> has to be specified as 80.
+ *
+ * @see org.apache.stratos.cartridge.agent.registrant.Registrant
+ */
+@SuppressWarnings("unused")
+public class PortMapping implements Serializable {
+
+    private static final long serialVersionUID = 8020727939469156788L;
+    public static final String PORT_TYPE_HTTP = "http";
+    public static final String PORT_TYPE_HTTPS = "https";
+
+    private int primaryPort;
+    private int proxyPort;
+    private String type;
+
+    public PortMapping() {
+    }
+
+    public int getPrimaryPort() {
+        return primaryPort;
+    }
+
+    public int getProxyPort() {
+        return proxyPort;
+    }
+
+    public void setPrimaryPort(int primaryPort) {
+        this.primaryPort = primaryPort;
+    }
+
+    public void setProxyPort(int proxyPort) {
+        this.proxyPort = proxyPort;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        if (type.equalsIgnoreCase(PORT_TYPE_HTTP) && type.equalsIgnoreCase(PORT_TYPE_HTTPS)) {
+            throw new RuntimeException("Invalid port type " + type);
+        }
+        this.type = type;
+    }
+
+    public boolean equals (Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        PortMapping that = (PortMapping) o;
+        return (type.equalsIgnoreCase(that.type) &&
+               (primaryPort == that.primaryPort) &&
+               (proxyPort == that.proxyPort));
+    }
+
+    @Override
+    public int hashCode() {
+        return type.hashCode() +
+                Integer.toString(primaryPort).hashCode() +
+                Integer.toString(proxyPort).hashCode();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/Registrant.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/Registrant.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/Registrant.java
new file mode 100644
index 0000000..a6ed860
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/Registrant.java
@@ -0,0 +1,199 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent.registrant;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.ClusteringFault;
+
+import java.io.Serializable;
+import java.util.Arrays;
+
+/**
+ * This class represents a process which registers itself with this Cartridge Agent
+ */
+@SuppressWarnings("unused")
+public class Registrant implements Serializable {
+
+    private static final long serialVersionUID = 1026289225178520964L;
+
+    private String key;
+    //private int tenantId;
+    private String tenantRange;
+    private String service;
+    private String hostName;
+    private PortMapping[] portMappings;
+    private String remoteHost;
+    private transient ClusteringAgent clusteringAgent;
+    private int minInstanceCount;
+    private int maxInstanceCount;
+    private int maxRequestsPerSecond;
+	private int roundsToAverage;
+	private double alarmingUpperRate;
+	private double alarmingLowerRate;
+	private double scaleDownFactor;
+   
+
+	public String getService() {
+        return service;
+    }
+
+    public String getTenantRange() {
+    	return tenantRange;
+    }
+
+	public void setTenantRange(String tenantRange) {
+    	this.tenantRange = tenantRange;
+    }
+
+	public void setService(String service) {
+        this.service = service;
+    }
+
+    public String getHostName() {
+        return hostName;
+    }
+
+    public void setHostName(String hostName) {
+        this.hostName = hostName;
+    }
+
+    public PortMapping[] getPortMappings() {
+        return Arrays.copyOf(portMappings, portMappings.length);
+    }
+
+    public void setPortMappings(PortMapping[] portMappings) {
+        this.portMappings = Arrays.copyOf(portMappings, portMappings.length);
+    }
+
+    public String getKey() {
+        return key;
+    }
+
+    public void setKey(String key) {
+        this.key = key;
+    }    
+    
+    public int getMinInstanceCount() {
+		return minInstanceCount;
+	}
+
+	public void setMinInstanceCount(int minInstanceCount) {
+		this.minInstanceCount = minInstanceCount;
+	}
+
+	public int getMaxInstanceCount() {
+		return maxInstanceCount;
+	}
+
+	public void setMaxInstanceCount(int maxInstanceCount) {
+		this.maxInstanceCount = maxInstanceCount;
+	}
+
+	public String retrieveClusterDomain() {
+		// alias.hostname.php.domain
+		return hostName+"."+service+".domain";
+    }
+
+    public void start(ClusteringAgent clusteringAgent) throws ClusteringFault {
+        this.clusteringAgent = clusteringAgent;
+        clusteringAgent.init();
+    }
+
+    public void stop() {
+        if (clusteringAgent != null) {
+            clusteringAgent.stop();
+        }
+        clusteringAgent = null;
+    }
+
+    public boolean running() {
+        return clusteringAgent != null;
+    }
+
+    public String getRemoteHost() {
+        return remoteHost;
+    }
+
+    public void setRemoteHost(String remoteHost) {
+        this.remoteHost = remoteHost;
+    }    
+    
+    public int getMaxRequestsPerSecond() {
+    	return maxRequestsPerSecond;
+    }
+
+	public void setMaxRequestsPerSecond(int maxRequestsPerSecond) {
+    	this.maxRequestsPerSecond = maxRequestsPerSecond;
+    }
+
+	public int getRoundsToAverage() {
+    	return roundsToAverage;
+    }
+
+	public void setRoundsToAverage(int roundsToAverage) {
+    	this.roundsToAverage = roundsToAverage;
+    }
+
+	public double getAlarmingUpperRate() {
+    	return alarmingUpperRate;
+    }
+
+	public void setAlarmingUpperRate(double alarmingUpperRate) {
+    	this.alarmingUpperRate = alarmingUpperRate;
+    }
+
+	public double getAlarmingLowerRate() {
+    	return alarmingLowerRate;
+    }
+
+	public void setAlarmingLowerRate(double alarmingLowerRate) {
+    	this.alarmingLowerRate = alarmingLowerRate;
+    }
+
+	public double getScaleDownFactor() {
+    	return scaleDownFactor;
+    }
+
+	public void setScaleDownFactor(double scaleDownFactor) {
+    	this.scaleDownFactor = scaleDownFactor;
+    }
+
+	@Override
+    public String toString() {
+        return "Registrant{" +
+               "key='" + key + '\'' +
+               ", remoteHost='" + remoteHost + '\'' +
+               '}';
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        Registrant that = (Registrant) o;
+        return key.equals(that.key);
+    }
+
+    @Override
+    public int hashCode() {
+        return key.hashCode();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantDatabase.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantDatabase.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantDatabase.java
new file mode 100644
index 0000000..dc511dc
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantDatabase.java
@@ -0,0 +1,143 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent.registrant;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cartridge.agent.InstanceStateNotificationClientThread;
+import org.apache.stratos.cartridge.agent.exception.CartridgeAgentException;
+
+import java.io.*;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * This class represents a database for {@link Registrant}s. Registrants added to this database will be
+ * persisted, so that when the Cartridge Agent is restarted, the Registrants can be restored.
+ *
+ * @see Registrant
+ */
+public class RegistrantDatabase {
+    private static final Log log = LogFactory.getLog(RegistrantDatabase.class);
+
+    private List<Registrant> registrants = new CopyOnWriteArrayList<Registrant>();
+
+    public void add(Registrant registrant) throws CartridgeAgentException {
+        if (registrants.contains(registrant) && registrant.running()) {
+            throw new CartridgeAgentException("Active registrant with key " +
+                                              registrant.getKey() + " already exists");
+        }
+        synchronized (registrant) {
+            if (!isAlreadyAdded(registrant)) {
+                persist(registrant);
+                registrants.add(registrant);
+                log.info("Added registrant " + registrant);
+
+            } else {
+                log.info("Registrant " + registrant + "has been already added");
+            }
+        }
+    }
+
+    private void persist(Registrant registrant) throws CartridgeAgentException {
+        try {
+            ObjectOutput out = null;
+            try {
+                // Serialize to a file
+                if (!new File("registrants").exists() && !new File("registrants").mkdirs()) {
+                    throw new IOException("Cannot create registrants directory");
+                }
+                out = new ObjectOutputStream(new FileOutputStream("registrants" + File.separator +
+                                                                  registrant.getKey() + ".ser"));
+                out.writeObject(registrant);
+                out.close();
+            } finally {
+                if (out != null) {
+                    out.close();
+                }
+            }
+        } catch (IOException e) {
+            log.error("Could not serialize registrant " + registrant, e);
+        }
+    }
+
+    public void stopAll() {
+        for (Registrant registrant : registrants) {
+        	new Thread(new InstanceStateNotificationClientThread(registrant, "INACTIVE")).start();
+            registrant.stop();
+        }
+    }
+
+    public boolean containsActive(Registrant registrant) {
+        return registrants.contains(registrant) &&
+               registrants.get(registrants.indexOf(registrant)).running();
+    }
+
+    public List<Registrant> getRegistrants() {
+        return Collections.unmodifiableList(registrants);
+    }
+
+    public boolean isAlreadyAdded(Registrant registrant) {
+
+        boolean alreadyAdded = false;
+        for (Registrant registrantFromDb : registrants) {
+            if(registrantFromDb.getRemoteHost().equals(registrant.getRemoteHost())) {
+
+                PortMapping[] portMappingofRegistrantOfDB = registrantFromDb.getPortMappings();
+                PortMapping[] portMappingofRegistrant = registrant.getPortMappings();
+
+                if(portMappingofRegistrant.length != portMappingofRegistrantOfDB.length) {
+                    continue;
+
+                } else {
+                    alreadyAdded = checkPortMappings(registrant, registrantFromDb);
+                }
+
+            } else {
+                continue;
+            }
+        }
+        return alreadyAdded;
+    }
+
+    private boolean checkPortMappings (Registrant newRegistrant, Registrant existingRegistrant) {
+
+        PortMapping[] portMappingsOfNewRegistrant = newRegistrant.getPortMappings();
+        PortMapping[] portMappingsOfExistingRegistrant = existingRegistrant.getPortMappings();
+
+        for (PortMapping portMappingOfNewRegistrant : portMappingsOfNewRegistrant) {
+            boolean matchFound = false;
+            for (PortMapping portMappingOfExistingRegistrant : portMappingsOfExistingRegistrant) {
+                if(portMappingOfExistingRegistrant.equals(portMappingOfNewRegistrant)) {
+                    matchFound = true;
+                    break;
+                }
+            }
+            if(!matchFound) {
+                return false;
+            }
+        }
+        if(log.isDebugEnabled()) {
+            log.debug("***********************************Found matching registrant for " + newRegistrant + " in the Registrant database");
+        }
+        return true;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantHealthChecker.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantHealthChecker.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantHealthChecker.java
new file mode 100644
index 0000000..2f8a227
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantHealthChecker.java
@@ -0,0 +1,115 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent.registrant;
+
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cartridge.agent.ClusteringClient;
+import org.apache.stratos.cartridge.agent.InstanceStateNotificationClientThread;
+
+/**
+ * This health checker periodically checks the health of the {@link Registrant}s
+ *
+ * If a registrant is found to be unhealthy, then it is stopped. This task will also try to
+ * connect to reactivate a registrant which was previously found to be unhealthy.
+ *
+ * If the Elastic Load Balancer (ELB) is not running, this health checker will not continue with
+ * registrant health checks since it is futile to try to connect the registrants to the
+ * unavailable ELB.
+ */
+public class RegistrantHealthChecker {
+    private static final Log log = LogFactory.getLog(RegistrantHealthChecker.class);
+
+    private RegistrantDatabase database;
+    private ClusteringClient clusteringClient;
+    private ConfigurationContext configurationContext;
+    private ScheduledExecutorService scheduler;
+    private volatile boolean isELBRunning;
+    private int healthCheckInterval;
+
+    public RegistrantHealthChecker(RegistrantDatabase database,
+                                   ClusteringClient clusteringClient,
+                                   ConfigurationContext configurationContext,
+                                   int healthCheckInterval,
+                                   int threadPoolSize) {
+        this.database = database;
+        this.clusteringClient = clusteringClient;
+        this.configurationContext = configurationContext;
+        this.healthCheckInterval = healthCheckInterval;
+        scheduler = Executors.newScheduledThreadPool(threadPoolSize);
+    }
+
+    public void startAll() {
+        List<Registrant> registrants = database.getRegistrants();
+        for (Registrant registrant : registrants) {
+            scheduler.scheduleWithFixedDelay(new HealthCheckerTask(registrant), 45,
+                                 healthCheckInterval, TimeUnit.SECONDS);
+            if (log.isDebugEnabled()) {
+                log.debug("Started a health checker for " + registrant + " ...");
+            }
+        }
+    }
+
+    public void start(Registrant registrant){
+        scheduler.scheduleWithFixedDelay(new HealthCheckerTask(registrant), 45,
+                             healthCheckInterval, TimeUnit.SECONDS);
+        if (log.isDebugEnabled()) {
+            log.debug("Added a health checker for " + registrant + " ...");
+        }
+    }
+
+    public void setELBRunning(boolean ELBRunning) {
+        isELBRunning = ELBRunning;
+    }
+
+    private final class HealthCheckerTask implements Runnable {
+        Registrant registrant;
+        public HealthCheckerTask(Registrant registrant){
+            this.registrant = registrant;
+        }
+        public void run() {
+            if(!isELBRunning){
+                return;
+            }
+            try {
+                boolean healthyRegistrant = RegistrantUtil.isHealthy(registrant);
+                if (!healthyRegistrant && registrant.running()) {
+                    registrant.stop();
+                    new Thread(new InstanceStateNotificationClientThread(registrant, "INACTIVE")).start();
+                    log.warn("Stopped registrant " + registrant + " since it is unhealthy." );
+                } else if (healthyRegistrant && !registrant.running()) {
+                    registrant.stop();
+                    new Thread(new InstanceStateNotificationClientThread(registrant, "INACTIVE")).start();
+                    clusteringClient.joinGroup(registrant, configurationContext);
+                    log.info("Restarted registrant " + registrant + " after it became active");
+                }
+            } catch (Exception e) {
+                log.error("Error occurred while running registrant health check", e);
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantUtil.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantUtil.java
new file mode 100644
index 0000000..60208b4
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantUtil.java
@@ -0,0 +1,177 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent.registrant;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cartridge.agent.ClusteringClient;
+import org.apache.stratos.cartridge.agent.exception.CartridgeAgentException;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.net.*;
+
+/**
+ * Utility method collection for handling {@link Registrant}s
+ *
+ * @see Registrant
+ */
+public class RegistrantUtil {
+    private static final Log log = LogFactory.getLog(RegistrantUtil.class);
+    private static boolean registrantsReloaded = false;
+    /**
+     * Before adding a member, we will try to verify whether we can connect to it
+     *
+     * @param registrant The member whose connectvity needs to be verified
+     * @return true, if the member can be contacted; false, otherwise.
+     */
+    public static boolean isHealthy(Registrant registrant) {
+        if (log.isDebugEnabled()) {
+            log.debug("Trying to connect to registrant " + registrant + "...");
+        }
+        if(log.isDebugEnabled()) {
+            log.debug("***********************************************isHealthy() method for registrant " + registrant);
+        }
+        String registrantRemoteHost = registrant.getRemoteHost();
+        log.debug("remote host : " + registrantRemoteHost);
+        if(registrantRemoteHost == null){
+            registrantRemoteHost = "localhost";
+        }
+        InetAddress addr;
+        try {
+            addr = InetAddress.getByName(registrantRemoteHost);
+            if(log.isDebugEnabled()) {
+                log.debug("***********************************************Host resolved for registrant " + registrant);
+            }
+        } catch (UnknownHostException e) {
+            log.error("Registrant " + registrant + " is unhealthy");
+            return false;
+        }
+        PortMapping[] portMappings = registrant.getPortMappings();
+
+        int maxRetries = Integer.parseInt(System.getProperty("clustering.maxRetries"));
+
+        for (int retries = maxRetries; retries > 0; retries--) {
+            try {
+                for (PortMapping portMapping : portMappings) {
+                    int port = portMapping.getPrimaryPort();
+                    if(log.isDebugEnabled()) {
+                        log.debug("***********************************************primary port" + port + " registrant " + registrant);
+                    }
+                    if (port != -1 && port != 0) {
+                        if(log.isDebugEnabled()) {
+                            log.debug("***********************************************connecting to " + registrant +
+                                    " re-try: " + retries);
+                        }
+                        SocketAddress httpSockaddr = new InetSocketAddress(addr, port);
+                        new Socket().connect(httpSockaddr, 10000);
+                        if(log.isDebugEnabled()) {
+                            log.debug("***********************************************connected successfully to port: " + port);
+                        }
+                    }
+                }
+                return true;
+            } catch (IOException e) {
+				if (log.isDebugEnabled()) {
+					log.debug("Error occurred.. " + e.getMessage());
+				}
+                String msg = e.getMessage();
+                if (!msg.contains("Connection refused") && !msg.contains("connect timed out")) {
+                    String msg2 = "Cannot connect to registrant " + registrant;
+                    log.error(msg2, e);
+                }
+                try {
+                    Thread.sleep(1000);
+                } catch (InterruptedException ignored) {
+                }
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Reload all the registrants persisted in the file system
+     * @param clusteringClient ClusteringClient
+     * @param configurationContext   ConfigurationContext
+     * @param registrantDatabase  RegistrantDatabase
+     * @throws CartridgeAgentException If reloading registrants fails
+     */
+    public static void reloadRegistrants(ClusteringClient clusteringClient,
+                                         ConfigurationContext configurationContext,
+                                         RegistrantDatabase registrantDatabase) throws CartridgeAgentException {
+
+        if(registrantsReloaded) {
+            log.info("Registrants already re-loaded, therefore not re-loading again");
+            return;
+        }
+
+        File registrants = new File("registrants");
+        if (!registrants.exists()) {
+            log.info("Registrant information doesn't exist in the file system");
+            return;
+        }
+        File[] files = registrants.listFiles();
+        if (files == null) {
+            log.error("Directory 'Registrants' is invalid");
+            return;
+
+        } else if (files.length == 0) {
+            log.info("No registrant information found in the Registrants directory");
+            return;
+        }
+
+        for (File file : files) {
+            try {
+                Registrant registrant =
+                        deserializeRegistrant("registrants" + File.separator + file.getName());
+                if (!registrantDatabase.containsActive(registrant)) {
+                    clusteringClient.joinGroup(registrant, configurationContext);
+                }
+            } catch (IOException e) {
+                log.error("Cannot deserialize registrant file " + file.getName(), e);
+            }
+        }
+        registrantsReloaded = true;
+    }
+
+    private static Registrant deserializeRegistrant(String fileName) throws IOException {
+        Registrant registrant = null;
+        ObjectInputStream in = null;
+
+        try {
+            // Deserialize from a file
+            File file = new File(fileName);
+            in = new ObjectInputStream(new FileInputStream(file));
+            // Deserialize the object
+            registrant = (Registrant) in.readObject();
+        } catch (ClassNotFoundException ignored) {
+        } finally {
+            if (in != null) {
+                in.close();
+            }
+        }
+        return registrant;
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/service/CartridgeAgentService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/service/CartridgeAgentService.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/service/CartridgeAgentService.java
new file mode 100644
index 0000000..2136164
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/service/CartridgeAgentService.java
@@ -0,0 +1,68 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.cartridge.agent.service;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cartridge.agent.ClusteringClient;
+import org.apache.stratos.cartridge.agent.exception.CartridgeAgentException;
+import org.apache.stratos.cartridge.agent.internal.CartridgeAgentConstants;
+import org.apache.stratos.cartridge.agent.internal.DataHolder;
+import org.apache.stratos.cartridge.agent.registrant.Registrant;
+
+/**
+ * Web service used for allowing {@link Registrant}s to register themselves with the Cartridge Agent
+ *
+ * @see Registrant
+ */
+@SuppressWarnings("unused")
+public class CartridgeAgentService {
+    private static final Log log = LogFactory.getLog(CartridgeAgentService.class);
+
+    public boolean register(Registrant registrant) throws CartridgeAgentException {
+
+        MessageContext messageContext = MessageContext.getCurrentMessageContext();
+        ConfigurationContext configurationContext = messageContext.getConfigurationContext();
+        ClusteringClient clusteringClient =
+                (ClusteringClient) configurationContext.getProperty(CartridgeAgentConstants.CLUSTERING_CLIENT);
+        if (registrant.getRemoteHost() == null || registrant.getRemoteHost().isEmpty()) {
+            String remoteAddr = (String) messageContext.getProperty("REMOTE_ADDR");
+            registrant.setRemoteHost(remoteAddr);
+        }
+        log.info("Trying to add new registrant " + registrant + "...");
+        clusteringClient.joinGroup(registrant, configurationContext);
+//        Main.getHealthChecker().start(registrant);
+        DataHolder.getHealthChecker().start(registrant);
+        return true;
+
+    }
+
+    public boolean unregister(String domain, String subDomain, String hostName) throws CartridgeAgentException {
+
+        MessageContext messageContext = MessageContext.getCurrentMessageContext();
+        ConfigurationContext configurationContext = messageContext.getConfigurationContext();
+        ClusteringClient clusteringClient =
+                (ClusteringClient) configurationContext.getProperty(CartridgeAgentConstants.CLUSTERING_CLIENT);
+        clusteringClient.removeClusterDomain(domain, subDomain, hostName, configurationContext);
+        return true;
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.cartridge.agent/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..1eb8777
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/resources/META-INF/services.xml
@@ -0,0 +1,37 @@
+<!-- 
+     ~  Licensed to the Apache Software Foundation (ASF) under one
+     ~  or more contributor license agreements.  See the NOTICE file
+     ~  distributed with this work for additional information
+     ~  regarding copyright ownership.  The ASF licenses this file
+     ~  to you under the Apache License, Version 2.0 (the
+     ~  "License"); you may not use this file except in compliance
+     ~  with the License.  You may obtain a copy of the License at
+     ~
+     ~    http://www.apache.org/licenses/LICENSE-2.0
+     ~
+     ~  Unless required by applicable law or agreed to in writing,
+     ~  software distributed under the License is distributed on an
+     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+     ~  KIND, either express or implied.  See the License for the
+     ~  specific language governing permissions and limitations
+     ~  under the License.
+     ~
+ -->
+<serviceGroup>
+    <service name="CartridgeAgentService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <description>
+            Admin service for ADC activities
+        </description>
+        <parameter name="ServiceClass">org.wso2.carbon.cartridge.agent.service.CartridgeAgentService
+        </parameter>
+        <parameter name="enableMTOM">true</parameter>
+        <parameter name="adminService" locked="true">false</parameter>
+        <parameter name="hiddenService" locked="true">false</parameter>
+        <parameter name="AuthorizationAction" locked="true">
+            /permission/admin/manage/modify/webapp    </parameter>
+        <parameter name="DoAuthentication" locked="true">true</parameter>
+    </service>
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.messages/2.1.1/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.messages/2.1.1/pom.xml b/components/org.apache.stratos.cartridge.messages/2.1.1/pom.xml
deleted file mode 100644
index ee78a78..0000000
--- a/components/org.apache.stratos.cartridge.messages/2.1.1/pom.xml
+++ /dev/null
@@ -1,77 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-     ~  Licensed to the Apache Software Foundation (ASF) under one
-     ~  or more contributor license agreements.  See the NOTICE file
-     ~  distributed with this work for additional information
-     ~  regarding copyright ownership.  The ASF licenses this file
-     ~  to you under the Apache License, Version 2.0 (the
-     ~  "License"); you may not use this file except in compliance
-     ~  with the License.  You may obtain a copy of the License at
-     ~
-     ~    http://www.apache.org/licenses/LICENSE-2.0
-     ~
-     ~  Unless required by applicable law or agreed to in writing,
-     ~  software distributed under the License is distributed on an
-     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-     ~  KIND, either express or implied.  See the License for the
-     ~  specific language governing permissions and limitations
-     ~  under the License.
-     ~
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.cartridge.messages</artifactId>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos Cartridge Agent - Messages</name>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2</artifactId>
-            <version>${axis2.wso2.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>commons-logging</groupId>
-            <artifactId>commons-logging</artifactId>
-        </dependency>
-    </dependencies>
-
-    <build>
-        <plugins>
-             <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                <version>1.4.0</version>
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Export-Package>
-                            org.apache.stratos.cartridge.messages.*
-                        </Export-Package>
-                        <Import-Package>
-                            !org.apache.commons.logging,
-                            org.apache.commons.logging; version=0.0.0,
-                            *; resolution:=optional
-                        </Import-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomain.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomain.java b/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomain.java
deleted file mode 100644
index d70d131..0000000
--- a/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomain.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.cartridge.messages;
-
-public class ClusterDomain {
-
-	private String domain;
-	private String subDomain;
-	private String hostName;
-	//private int tenantId;
-	private String tenantRange;
-	private int minInstances;
-	private int maxInstances;
-	private String serviceName;
-	private int maxRequestsPerSecond;
-	private int roundsToAverage;
-	private double alarmingUpperRate;
-	private double alarmingLowerRate;
-	private double scaleDownFactor;
-	
-	public String getDomain() {
-		return domain;
-	}
-	public void setDomain(String domain) {
-		this.domain = domain;
-	}
-	public String getSubDomain() {
-		return subDomain;
-	}
-	public void setSubDomain(String subDomain) {
-		this.subDomain = subDomain;
-	}
-	public String getHostName() {
-		return hostName;
-	}
-	public void setHostName(String hostName) {
-		this.hostName = hostName;
-	}
-	/*public int getTenantId() {
-		return tenantId;
-	}
-	public void setTenantId(int tenantId) {
-		this.tenantId = tenantId;
-	}*/
-	public int getMinInstances() {
-		return minInstances;
-	}
-	public void setMinInstances(int minInstances) {
-		this.minInstances = minInstances;
-	}
-	public int getMaxInstances() {
-		return maxInstances;
-	}
-	public void setMaxInstances(int maxInstances) {
-		this.maxInstances = maxInstances;
-	}
-	public String getServiceName() {
-		return serviceName;
-	}
-	public void setServiceName(String serviceName) {
-		this.serviceName = serviceName;
-	}
-	public String getTenantRange() {
-    	return tenantRange;
-    }
-	public void setTenantRange(String tenantRange) {
-    	this.tenantRange = tenantRange;
-    }
-	public int getMaxRequestsPerSecond() {
-    	return maxRequestsPerSecond;
-    }
-	public void setMaxRequestsPerSecond(int maxRequestsPerSecond) {
-    	this.maxRequestsPerSecond = maxRequestsPerSecond;
-    }
-	public int getRoundsToAverage() {
-    	return roundsToAverage;
-    }
-	public void setRoundsToAverage(int roundsToAverage) {
-    	this.roundsToAverage = roundsToAverage;
-    }
-	public double getAlarmingUpperRate() {
-    	return alarmingUpperRate;
-    }
-	public void setAlarmingUpperRate(double alarmingUpperRate) {
-    	this.alarmingUpperRate = alarmingUpperRate;
-    }
-	public double getAlarmingLowerRate() {
-    	return alarmingLowerRate;
-    }
-	public void setAlarmingLowerRate(double alarmingLowerRate) {
-    	this.alarmingLowerRate = alarmingLowerRate;
-    }
-	public double getScaleDownFactor() {
-    	return scaleDownFactor;
-    }
-	public void setScaleDownFactor(double scaleDownFactor) {
-    	this.scaleDownFactor = scaleDownFactor;
-    }
-	
-	
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomainManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomainManager.java b/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomainManager.java
deleted file mode 100644
index cdea820..0000000
--- a/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomainManager.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.cartridge.messages;
-
-/**
- * TODO: class description
- */
-public interface ClusterDomainManager {
-
-    void addClusterDomain(ClusterDomain clusterDomain);
-    
-    /**
-     * This will remove the corresponding ServiceConfiguration.
-     * @param domain
-     * @param subDomain
-     * @param hostName
-     */
-    void removeClusterDomain(String domain, String subDomain, String hostName);
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/CreateClusterDomainMessage.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/CreateClusterDomainMessage.java b/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/CreateClusterDomainMessage.java
deleted file mode 100644
index 7c54a8d..0000000
--- a/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/CreateClusterDomainMessage.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.cartridge.messages;
-
-import org.apache.axis2.clustering.ClusteringCommand;
-import org.apache.axis2.clustering.ClusteringFault;
-import org.apache.axis2.clustering.ClusteringMessage;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * TODO: class description
- */
-public class CreateClusterDomainMessage extends ClusteringMessage {
-    private static final Log log = LogFactory.getLog(CreateClusterDomainMessage.class);
-    public static final String CLUSTER_DOMAIN_MANAGER = "cluster.domain.manager";
-    private String service;
-    private String clusterDomain;
-    private String hostName;
-    //private int tenantId;
-    private String tenantRange;
-    private int minInstances;
-    private int maxInstances;
-	private int maxRequestsPerSecond;
-	private int roundsToAverage;
-	private double alarmingUpperRate;
-	private double alarmingLowerRate;
-	private double scaleDownFactor;
-    
-
-    public CreateClusterDomainMessage(String service, String clusterDomain,
-                                      String hostName, String tenantRange,
-                                      int minInstances, int maxInstances,
-                                      int maxRequestsPerSecond, int roundsToAverage,
-                                      double alarmingUpperRate, double alarmingLowerRate,
-                                      double scaleDownFactor) {
-        this.service = service;
-        this.clusterDomain = clusterDomain;
-        this.hostName = hostName;
-        this.tenantRange = tenantRange;
-        this.minInstances = minInstances;
-        this.maxInstances = maxInstances;
-        this.maxRequestsPerSecond = maxRequestsPerSecond;
-        this.roundsToAverage = roundsToAverage;
-        this.alarmingUpperRate = alarmingUpperRate;
-        this.alarmingLowerRate = alarmingLowerRate;
-        this.scaleDownFactor = scaleDownFactor;
-    }
-
-    @Override
-    public ClusteringCommand getResponse() {
-        return new ClusteringCommand() {
-            @Override
-            public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
-                log.info("Received response to CreateClusterDomainMessage");
-            }
-        };
-    }
-
-    @Override
-    public void execute(final ConfigurationContext configurationContext) throws ClusteringFault {
-        log.info("Received ***" + this);
-        Runnable runnable = new Runnable() {
-            public void run() {
-                try {
-                    Thread.sleep(2000);
-                } catch (InterruptedException ignored) {
-                }
-                ClusterDomainManager clusterDomainManager =
-                        (ClusterDomainManager) configurationContext.getProperty(CLUSTER_DOMAIN_MANAGER);
-                if (clusterDomainManager != null) {
-                    clusterDomainManager.addClusterDomain(createClusterDomain());
-                } else {
-                    log.warn(CLUSTER_DOMAIN_MANAGER + " has not been defined in ConfigurationContext");
-                }
-            }
-
-			private ClusterDomain createClusterDomain() {
-				
-				ClusterDomain clusterDomainObj = new ClusterDomain();
-				clusterDomainObj.setDomain(clusterDomain);
-				clusterDomainObj.setHostName(hostName);
-				clusterDomainObj.setMaxInstances(maxInstances);
-				clusterDomainObj.setMinInstances(minInstances);
-				clusterDomainObj.setSubDomain(null); // TODO subdomain
-				clusterDomainObj.setTenantRange(tenantRange);
-				clusterDomainObj.setServiceName(service);
-				clusterDomainObj.setMaxRequestsPerSecond(maxRequestsPerSecond);
-				clusterDomainObj.setRoundsToAverage(roundsToAverage);
-				clusterDomainObj.setAlarmingUpperRate(alarmingUpperRate);
-				clusterDomainObj.setAlarmingLowerRate(alarmingLowerRate);
-				clusterDomainObj.setScaleDownFactor(scaleDownFactor);
-				
-				if(log.isDebugEnabled())
-					log.debug("Cluster Domain is created with minInstances:" + minInstances + ", maxInstances: " + maxInstances);
-				
-				return clusterDomainObj;
-			}
-        };
-        new Thread(runnable).start();
-    }
-
-    @Override
-    public String toString() {
-        return "CreateClusterDomainMessage{" +
-               "service='" + service + '\'' +
-               ", clusterDomain='" + clusterDomain + '\'' +
-               ", hostName='" + hostName + '\'' +
-               ", tenantId=" + tenantRange +
-               '}';
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/CreateRemoveClusterDomainMessage.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/CreateRemoveClusterDomainMessage.java b/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/CreateRemoveClusterDomainMessage.java
deleted file mode 100644
index b154424..0000000
--- a/components/org.apache.stratos.cartridge.messages/2.1.1/src/main/java/org/apache/stratos/cartridge/messages/CreateRemoveClusterDomainMessage.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.cartridge.messages;
-
-import org.apache.axis2.clustering.ClusteringCommand;
-import org.apache.axis2.clustering.ClusteringFault;
-import org.apache.axis2.clustering.ClusteringMessage;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class CreateRemoveClusterDomainMessage extends ClusteringMessage{
-	
-	private static final Log log = LogFactory.getLog(CreateClusterDomainMessage.class);
-	public static final String CLUSTER_DOMAIN_MANAGER = "cluster.domain.manager";
-	private String domain;
-	private String subDomain;
-	private String hostName;
-	
-	
-	
-	public CreateRemoveClusterDomainMessage(String domain, String subDomain, String hostName) {
-	    this.domain = domain;
-	    this.subDomain = subDomain;
-	    this.hostName = hostName;
-    }
-
-	@Override
-    public ClusteringCommand getResponse() {
-		return new ClusteringCommand() {
-            @Override
-            public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
-                log.info("Received response to CreateRemoveClusterDomainMessage");
-            }
-        };
-    }
-
-	@Override
-    public void execute(final ConfigurationContext configurationContext) throws ClusteringFault {
-	    
-		log.info("Received ***" + this);
-        Runnable runnable = new Runnable() {
-            public void run() {
-                try {
-                    Thread.sleep(2000);
-                } catch (InterruptedException ignored) {
-                }
-                ClusterDomainManager clusterDomainManager =
-                        (ClusterDomainManager) configurationContext.getProperty(CLUSTER_DOMAIN_MANAGER);
-                log.info(" ***** Received clusterDomain Manager ** " + clusterDomainManager);
-                if (clusterDomainManager != null) {
-                    clusterDomainManager.removeClusterDomain(domain, subDomain, hostName);
-                } else {
-                    log.warn(CLUSTER_DOMAIN_MANAGER + " has not been defined in ConfigurationContext");
-                }
-            }
-        };
-        new Thread(runnable).start();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.messages/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.messages/pom.xml b/components/org.apache.stratos.cartridge.messages/pom.xml
new file mode 100644
index 0000000..9c0c332
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.messages/pom.xml
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     ~  Licensed to the Apache Software Foundation (ASF) under one
+     ~  or more contributor license agreements.  See the NOTICE file
+     ~  distributed with this work for additional information
+     ~  regarding copyright ownership.  The ASF licenses this file
+     ~  to you under the Apache License, Version 2.0 (the
+     ~  "License"); you may not use this file except in compliance
+     ~  with the License.  You may obtain a copy of the License at
+     ~
+     ~    http://www.apache.org/licenses/LICENSE-2.0
+     ~
+     ~  Unless required by applicable law or agreed to in writing,
+     ~  software distributed under the License is distributed on an
+     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+     ~  KIND, either express or implied.  See the License for the
+     ~  specific language governing permissions and limitations
+     ~  under the License.
+     ~
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.cartridge.messages</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos Cartridge Agent - Messages</name>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+            <version>${axis2.wso2.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+             <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.apache.stratos.cartridge.messages.*
+                        </Export-Package>
+                        <Import-Package>
+                            !org.apache.commons.logging,
+                            org.apache.commons.logging; version=0.0.0,
+                            *; resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomain.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomain.java b/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomain.java
new file mode 100644
index 0000000..d70d131
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomain.java
@@ -0,0 +1,117 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.cartridge.messages;
+
+public class ClusterDomain {
+
+	private String domain;
+	private String subDomain;
+	private String hostName;
+	//private int tenantId;
+	private String tenantRange;
+	private int minInstances;
+	private int maxInstances;
+	private String serviceName;
+	private int maxRequestsPerSecond;
+	private int roundsToAverage;
+	private double alarmingUpperRate;
+	private double alarmingLowerRate;
+	private double scaleDownFactor;
+	
+	public String getDomain() {
+		return domain;
+	}
+	public void setDomain(String domain) {
+		this.domain = domain;
+	}
+	public String getSubDomain() {
+		return subDomain;
+	}
+	public void setSubDomain(String subDomain) {
+		this.subDomain = subDomain;
+	}
+	public String getHostName() {
+		return hostName;
+	}
+	public void setHostName(String hostName) {
+		this.hostName = hostName;
+	}
+	/*public int getTenantId() {
+		return tenantId;
+	}
+	public void setTenantId(int tenantId) {
+		this.tenantId = tenantId;
+	}*/
+	public int getMinInstances() {
+		return minInstances;
+	}
+	public void setMinInstances(int minInstances) {
+		this.minInstances = minInstances;
+	}
+	public int getMaxInstances() {
+		return maxInstances;
+	}
+	public void setMaxInstances(int maxInstances) {
+		this.maxInstances = maxInstances;
+	}
+	public String getServiceName() {
+		return serviceName;
+	}
+	public void setServiceName(String serviceName) {
+		this.serviceName = serviceName;
+	}
+	public String getTenantRange() {
+    	return tenantRange;
+    }
+	public void setTenantRange(String tenantRange) {
+    	this.tenantRange = tenantRange;
+    }
+	public int getMaxRequestsPerSecond() {
+    	return maxRequestsPerSecond;
+    }
+	public void setMaxRequestsPerSecond(int maxRequestsPerSecond) {
+    	this.maxRequestsPerSecond = maxRequestsPerSecond;
+    }
+	public int getRoundsToAverage() {
+    	return roundsToAverage;
+    }
+	public void setRoundsToAverage(int roundsToAverage) {
+    	this.roundsToAverage = roundsToAverage;
+    }
+	public double getAlarmingUpperRate() {
+    	return alarmingUpperRate;
+    }
+	public void setAlarmingUpperRate(double alarmingUpperRate) {
+    	this.alarmingUpperRate = alarmingUpperRate;
+    }
+	public double getAlarmingLowerRate() {
+    	return alarmingLowerRate;
+    }
+	public void setAlarmingLowerRate(double alarmingLowerRate) {
+    	this.alarmingLowerRate = alarmingLowerRate;
+    }
+	public double getScaleDownFactor() {
+    	return scaleDownFactor;
+    }
+	public void setScaleDownFactor(double scaleDownFactor) {
+    	this.scaleDownFactor = scaleDownFactor;
+    }
+	
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomainManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomainManager.java b/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomainManager.java
new file mode 100644
index 0000000..cdea820
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/ClusterDomainManager.java
@@ -0,0 +1,35 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.cartridge.messages;
+
+/**
+ * TODO: class description
+ */
+public interface ClusterDomainManager {
+
+    void addClusterDomain(ClusterDomain clusterDomain);
+    
+    /**
+     * This will remove the corresponding ServiceConfiguration.
+     * @param domain
+     * @param subDomain
+     * @param hostName
+     */
+    void removeClusterDomain(String domain, String subDomain, String hostName);
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/CreateClusterDomainMessage.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/CreateClusterDomainMessage.java b/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/CreateClusterDomainMessage.java
new file mode 100644
index 0000000..7c54a8d
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/CreateClusterDomainMessage.java
@@ -0,0 +1,129 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.cartridge.messages;
+
+import org.apache.axis2.clustering.ClusteringCommand;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.clustering.ClusteringMessage;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * TODO: class description
+ */
+public class CreateClusterDomainMessage extends ClusteringMessage {
+    private static final Log log = LogFactory.getLog(CreateClusterDomainMessage.class);
+    public static final String CLUSTER_DOMAIN_MANAGER = "cluster.domain.manager";
+    private String service;
+    private String clusterDomain;
+    private String hostName;
+    //private int tenantId;
+    private String tenantRange;
+    private int minInstances;
+    private int maxInstances;
+	private int maxRequestsPerSecond;
+	private int roundsToAverage;
+	private double alarmingUpperRate;
+	private double alarmingLowerRate;
+	private double scaleDownFactor;
+    
+
+    public CreateClusterDomainMessage(String service, String clusterDomain,
+                                      String hostName, String tenantRange,
+                                      int minInstances, int maxInstances,
+                                      int maxRequestsPerSecond, int roundsToAverage,
+                                      double alarmingUpperRate, double alarmingLowerRate,
+                                      double scaleDownFactor) {
+        this.service = service;
+        this.clusterDomain = clusterDomain;
+        this.hostName = hostName;
+        this.tenantRange = tenantRange;
+        this.minInstances = minInstances;
+        this.maxInstances = maxInstances;
+        this.maxRequestsPerSecond = maxRequestsPerSecond;
+        this.roundsToAverage = roundsToAverage;
+        this.alarmingUpperRate = alarmingUpperRate;
+        this.alarmingLowerRate = alarmingLowerRate;
+        this.scaleDownFactor = scaleDownFactor;
+    }
+
+    @Override
+    public ClusteringCommand getResponse() {
+        return new ClusteringCommand() {
+            @Override
+            public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
+                log.info("Received response to CreateClusterDomainMessage");
+            }
+        };
+    }
+
+    @Override
+    public void execute(final ConfigurationContext configurationContext) throws ClusteringFault {
+        log.info("Received ***" + this);
+        Runnable runnable = new Runnable() {
+            public void run() {
+                try {
+                    Thread.sleep(2000);
+                } catch (InterruptedException ignored) {
+                }
+                ClusterDomainManager clusterDomainManager =
+                        (ClusterDomainManager) configurationContext.getProperty(CLUSTER_DOMAIN_MANAGER);
+                if (clusterDomainManager != null) {
+                    clusterDomainManager.addClusterDomain(createClusterDomain());
+                } else {
+                    log.warn(CLUSTER_DOMAIN_MANAGER + " has not been defined in ConfigurationContext");
+                }
+            }
+
+			private ClusterDomain createClusterDomain() {
+				
+				ClusterDomain clusterDomainObj = new ClusterDomain();
+				clusterDomainObj.setDomain(clusterDomain);
+				clusterDomainObj.setHostName(hostName);
+				clusterDomainObj.setMaxInstances(maxInstances);
+				clusterDomainObj.setMinInstances(minInstances);
+				clusterDomainObj.setSubDomain(null); // TODO subdomain
+				clusterDomainObj.setTenantRange(tenantRange);
+				clusterDomainObj.setServiceName(service);
+				clusterDomainObj.setMaxRequestsPerSecond(maxRequestsPerSecond);
+				clusterDomainObj.setRoundsToAverage(roundsToAverage);
+				clusterDomainObj.setAlarmingUpperRate(alarmingUpperRate);
+				clusterDomainObj.setAlarmingLowerRate(alarmingLowerRate);
+				clusterDomainObj.setScaleDownFactor(scaleDownFactor);
+				
+				if(log.isDebugEnabled())
+					log.debug("Cluster Domain is created with minInstances:" + minInstances + ", maxInstances: " + maxInstances);
+				
+				return clusterDomainObj;
+			}
+        };
+        new Thread(runnable).start();
+    }
+
+    @Override
+    public String toString() {
+        return "CreateClusterDomainMessage{" +
+               "service='" + service + '\'' +
+               ", clusterDomain='" + clusterDomain + '\'' +
+               ", hostName='" + hostName + '\'' +
+               ", tenantId=" + tenantRange +
+               '}';
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/CreateRemoveClusterDomainMessage.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/CreateRemoveClusterDomainMessage.java b/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/CreateRemoveClusterDomainMessage.java
new file mode 100644
index 0000000..b154424
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.messages/src/main/java/org/apache/stratos/cartridge/messages/CreateRemoveClusterDomainMessage.java
@@ -0,0 +1,77 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.cartridge.messages;
+
+import org.apache.axis2.clustering.ClusteringCommand;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.clustering.ClusteringMessage;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class CreateRemoveClusterDomainMessage extends ClusteringMessage{
+	
+	private static final Log log = LogFactory.getLog(CreateClusterDomainMessage.class);
+	public static final String CLUSTER_DOMAIN_MANAGER = "cluster.domain.manager";
+	private String domain;
+	private String subDomain;
+	private String hostName;
+	
+	
+	
+	public CreateRemoveClusterDomainMessage(String domain, String subDomain, String hostName) {
+	    this.domain = domain;
+	    this.subDomain = subDomain;
+	    this.hostName = hostName;
+    }
+
+	@Override
+    public ClusteringCommand getResponse() {
+		return new ClusteringCommand() {
+            @Override
+            public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
+                log.info("Received response to CreateRemoveClusterDomainMessage");
+            }
+        };
+    }
+
+	@Override
+    public void execute(final ConfigurationContext configurationContext) throws ClusteringFault {
+	    
+		log.info("Received ***" + this);
+        Runnable runnable = new Runnable() {
+            public void run() {
+                try {
+                    Thread.sleep(2000);
+                } catch (InterruptedException ignored) {
+                }
+                ClusterDomainManager clusterDomainManager =
+                        (ClusterDomainManager) configurationContext.getProperty(CLUSTER_DOMAIN_MANAGER);
+                log.info(" ***** Received clusterDomain Manager ** " + clusterDomainManager);
+                if (clusterDomainManager != null) {
+                    clusterDomainManager.removeClusterDomain(domain, subDomain, hostName);
+                } else {
+                    log.warn(CLUSTER_DOMAIN_MANAGER + " has not been defined in ConfigurationContext");
+                }
+            }
+        };
+        new Thread(runnable).start();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cloud.controller/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cloud.controller/pom.xml b/components/org.apache.stratos.cloud.controller/pom.xml
index 11f4834..85bc531 100644
--- a/components/org.apache.stratos.cloud.controller/pom.xml
+++ b/components/org.apache.stratos.cloud.controller/pom.xml
@@ -22,7 +22,6 @@
        <groupId>org.apache.stratos</groupId>
        <artifactId>stratos-components-parent</artifactId>
        <version>3.0.0-SNAPSHOT</version>
-       <relativePath>../pom.xml</relativePath>
     </parent>
 
     <modelVersion>4.0.0</modelVersion>
@@ -142,7 +141,7 @@
         <dependency>
             <groupId>org.apache.stratos</groupId>
             <artifactId>org.apache.stratos.lb.common</artifactId>
-            <version>4.1.3</version>
+            <version>${apache.stratos.version}</version>
         </dependency>
 
 


[24/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/internal/TopologyMgtDSComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/internal/TopologyMgtDSComponent.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/internal/TopologyMgtDSComponent.java
new file mode 100644
index 0000000..2500485
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/internal/TopologyMgtDSComponent.java
@@ -0,0 +1,290 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.stratos.adc.topology.mgt.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.topology.mgt.builder.TopologySyncher;
+import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
+import org.apache.stratos.adc.topology.mgt.service.impl.TopologyManagementServiceImpl;
+import org.apache.stratos.adc.topology.mgt.subscriber.TopologySubscriber;
+import org.apache.stratos.adc.topology.mgt.util.ConfigHolder;
+import org.apache.stratos.adc.topology.mgt.util.TopologyConstants;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.utils.ConfigurationContextService;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.ntask.core.service.TaskService;
+
+//* @scr.reference name="synapse.config.service"
+//* interface="org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService"
+//* cardinality="1..1" policy="dynamic" bind="setSynapseConfigurationService"
+//* unbind="unsetSynapseConfigurationService"
+//* @scr.reference name="registry.service"
+//* interface="org.wso2.carbon.registry.core.service.RegistryService"
+//* cardinality="1..1" policy="dynamic"
+//* bind="setRegistryService" unbind="unsetRegistryService"
+//* @scr.reference name="dependency.mgt.service"
+//* interface="org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService"
+//* cardinality="0..1" policy="dynamic"
+//* bind="setDependencyManager" unbind="unsetDependencyManager"
+//* @scr.reference name="user.realmservice.default"
+//* interface="org.wso2.carbon.user.core.service.RealmService"
+//* cardinality="1..1" policy="dynamic" bind="setRealmService"
+//* unbind="unsetRealmService"
+
+/**
+ * @scr.component name="topology.mgt.service" immediate="true"
+ * @scr.reference name="configuration.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
+ * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
+ * @scr.reference name="org.apache.stratos.lb.common"
+ * interface="org.apache.stratos.lb.common.service.LoadBalancerConfigurationService"
+ * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
+ * unbind="unsetLoadBalancerConfigurationService"
+ * @scr.reference name="ntask.component" interface="org.wso2.carbon.ntask.core.service.TaskService"
+ * cardinality="1..1" policy="dynamic" bind="setTaskService" unbind="unsetTaskService"
+ */
+@SuppressWarnings({"UnusedDeclaration", "JavaDoc"})
+public class TopologyMgtDSComponent {
+
+    private static final Log log = LogFactory.getLog(TopologyMgtDSComponent.class);
+
+//    private boolean activated = false;
+
+    protected void activate(ComponentContext ctxt) {
+    	try {
+    		// start consumer
+    		// initialize TopologyBuilder Consumer
+            if (System.getProperty("mb.server.ip") != null) {
+                Thread topologyConsumer = new Thread(new TopologySyncher(ConfigHolder.getInstance().getSharedTopologyDiffQueue()));
+                // start consumer
+                topologyConsumer.start();
+
+                TopologySubscriber.subscribe(TopologyConstants.TOPIC_NAME);
+            }
+
+    		
+            BundleContext bundleContext = ctxt.getBundleContext();
+            bundleContext.registerService(TopologyManagementService.class.getName(),
+                                          new TopologyManagementServiceImpl(), null);
+
+            log.debug("******* Topology Mgt Service bundle is activated ******* ");
+        } catch (Throwable e) {
+            log.error("******* Topology Mgt Service Service bundle is failed to activate ****", e);
+        }
+//    	log.info("**************************************");
+//    	for (String str : ConfigHolder.getInstance().getLbConfig().getServiceDomains()) {
+//	        log.info(str);
+//        }
+//    	log.info("**************************************");
+    	
+//    	if(!activated){
+//    		GroupMgtAgentBuilder.createGroupMgtAgents();
+//    		activated = true;
+//    	}
+    	
+    	
+    	// topology synching task activation
+//    	TaskManager tm = null;
+//		try {
+//			// topology sync
+//			ConfigHolder.getInstance().getTaskService()
+//			          .registerTaskType(TopologyConstants.TOPOLOGY_SYNC_TASK_TYPE);
+//
+//			tm =
+//					ConfigHolder.getInstance().getTaskService()
+//			               .getTaskManager(TopologyConstants.TOPOLOGY_SYNC_TASK_TYPE);
+//
+//			TriggerInfo triggerInfo = new TriggerInfo(TopologyConstants.TOPOLOGY_SYNC_CRON);
+//			TaskInfo taskInfo =
+//			                    new TaskInfo(TopologyConstants.TOPOLOGY_SYNC_TASK_NAME,
+//			                                 TopologySubscriberTask.class.getName(),
+//			                                 new HashMap<String, String>(), triggerInfo);
+//			tm.registerTask(taskInfo);
+//
+//			// start consumer
+//			// initialize TopologyBuilder Consumer
+//	        Thread topologyConsumer = new Thread(new TopologyBuilder(ConfigHolder.getInstance().getSharedTopologyDiffQueue()));
+//	        // start consumer
+//	        topologyConsumer.start();
+//			
+//		} catch (Exception e) {
+//			String msg = "Error scheduling task: " + TopologyConstants.TOPOLOGY_SYNC_TASK_NAME;
+//			log.error(msg, e);
+//			if (tm != null) {
+//				try {
+//					tm.deleteTask(TopologyConstants.TOPOLOGY_SYNC_TASK_NAME);
+//				} catch (TaskException e1) {
+//					log.error(e1);
+//				}
+//			}
+//			throw new TopologyMgtException(msg, e);
+//		}
+    }
+
+    protected void deactivate(ComponentContext context) {}
+
+    protected void setConfigurationContextService(ConfigurationContextService cfgCtxService) {
+        ConfigHolder.getInstance().setAxisConfiguration(
+                cfgCtxService.getServerConfigContext().getAxisConfiguration());
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService cfgCtxService) {
+        ConfigHolder.getInstance().setAxisConfiguration(null);
+    }
+
+//    protected void setSynapseConfigurationService(
+//            SynapseConfigurationService synapseConfigurationService) {
+//
+//        ConfigHolder.getInstance().setSynapseConfiguration(
+//                synapseConfigurationService.getSynapseConfiguration());
+//    }
+//
+//    protected void unsetSynapseConfigurationService(
+//            SynapseConfigurationService synapseConfigurationService) {
+//
+//        ConfigHolder.getInstance().setSynapseConfiguration(null);
+//    }
+
+    /**
+     * Here we receive an event about the creation of a SynapseEnvironment. If this is
+     * SuperTenant we have to wait until all the other constraints are met and actual
+     * initialization is done in the activate method. Otherwise we have to do the activation here.
+     *
+     * @param synapseEnvironmentService SynapseEnvironmentService which contains information
+     *                                  about the new Synapse Instance
+     */
+//    protected void setSynapseEnvironmentService(
+//            SynapseEnvironmentService synapseEnvironmentService) {
+//        boolean alreadyCreated = ConfigHolder.getInstance().getSynapseEnvironmentServices().
+//                containsKey(synapseEnvironmentService.getTenantId());
+//
+//        ConfigHolder.getInstance().addSynapseEnvironmentService(
+//                synapseEnvironmentService.getTenantId(),
+//                synapseEnvironmentService);
+//        if (activated) {
+//            if (!alreadyCreated) {
+//                try {
+//                    registerDeployer(synapseEnvironmentService.getConfigurationContext().getAxisConfiguration(),
+//                            synapseEnvironmentService.getSynapseEnvironment());
+//                    if (log.isDebugEnabled()) {
+//                        log.debug("Endpoint Admin bundle is activated ");
+//                    }
+//                } catch (Throwable e) {
+//                    log.error("Failed to activate Endpoint Admin bundle ", e);
+//                }
+//            }
+//        }
+//    }
+
+//    /**
+//     * Here we receive an event about Destroying a SynapseEnvironment. This can be the super tenant
+//     * destruction or a tenant destruction.
+//     *
+//     * @param synapseEnvironmentService synapseEnvironment
+//     */
+//    protected void unsetSynapseEnvironmentService(
+//            SynapseEnvironmentService synapseEnvironmentService) {
+//        ConfigHolder.getInstance().removeSynapseEnvironmentService(
+//                synapseEnvironmentService.getTenantId());
+//    }
+//
+//    protected void setRegistryService(RegistryService regService) {
+//        if (log.isDebugEnabled()) {
+//            log.debug("RegistryService bound to the endpoint component");
+//        }
+//        try {
+//            ConfigHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
+//            ConfigHolder.getInstance().setGovernanceRegistry(regService.getGovernanceSystemRegistry());
+//        } catch (RegistryException e) {
+//            log.error("Couldn't retrieve the registry from the registry service");
+//        }
+//    }
+//
+//    protected void unsetRegistryService(RegistryService regService) {
+//        if (log.isDebugEnabled()) {
+//            log.debug("RegistryService unbound from the endpoint component");
+//        }
+//        ConfigHolder.getInstance().setConfigRegistry(null);
+//    }
+//
+//    protected void setDependencyManager(DependencyManagementService dependencyMgr) {
+//        if (log.isDebugEnabled()) {
+//            log.debug("Dependency management service bound to the endpoint component");
+//        }
+//        ConfigHolder.getInstance().setDependencyManager(dependencyMgr);
+//    }
+//
+//    protected void unsetDependencyManager(DependencyManagementService dependencyMgr) {
+//        if (log.isDebugEnabled()) {
+//            log.debug("Dependency management service unbound from the endpoint component");
+//        }
+//        ConfigHolder.getInstance().setDependencyManager(null);
+//    }
+//
+//    protected void setSynapseRegistrationsService(
+//            SynapseRegistrationsService synapseRegistrationsService) {
+//
+//    }
+
+//    protected void unsetSynapseRegistrationsService(
+//            SynapseRegistrationsService synapseRegistrationsService) {
+//        int tenantId = synapseRegistrationsService.getTenantId();
+//        if (ConfigHolder.getInstance().getSynapseEnvironmentServices().containsKey(tenantId)) {
+//            SynapseEnvironment env = ConfigHolder.getInstance().
+//                    getSynapseEnvironmentService(tenantId).getSynapseEnvironment();
+//
+//            ConfigHolder.getInstance().removeSynapseEnvironmentService(
+//                    synapseRegistrationsService.getTenantId());
+//
+//            AxisConfiguration axisConfig = synapseRegistrationsService.getConfigurationContext().
+//                    getAxisConfiguration();
+//            if (axisConfig != null) {
+//                try {
+//                    unregisterDeployer(axisConfig, env);
+//                } catch (Exception e) {
+//                    log.warn("Couldn't remove the EndpointDeployer");
+//                }
+//            }
+//        }
+//    }
+
+//    protected void setRealmService(RealmService realmService) {
+//        ConfigHolder.getInstance().setRealmService(realmService);
+//    }
+//
+//    protected void unsetRealmService(RealmService realmService) {
+//        ConfigHolder.getInstance().setRealmService(null);
+//    }
+//    
+    protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        ConfigHolder.getInstance().setLbConfigService(lbConfigSer);
+    }
+    
+    protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        ConfigHolder.getInstance().setLbConfigService(null);
+    }
+    
+    protected void setTaskService(TaskService taskService) {
+        ConfigHolder.getInstance().setTaskService(taskService);
+    }
+
+    protected void unsetTaskService(TaskService taskService) {
+        ConfigHolder.getInstance().setTaskService(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/service/TopologyManagementService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/service/TopologyManagementService.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/service/TopologyManagementService.java
new file mode 100644
index 0000000..9b490e9
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/service/TopologyManagementService.java
@@ -0,0 +1,69 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.stratos.adc.topology.mgt.service;
+
+import org.apache.stratos.adc.topology.mgt.serviceobjects.DomainContext;
+
+/**
+ * This exposes details regarding up-to-date topology
+ *
+ */
+public interface TopologyManagementService {
+
+	/**
+	 * Provide service cluster domains corresponds to the given information.
+	 * @param cartridgeType cartridge type
+	 * @param tenantId tenant id
+	 * @return String array of service cluster domains
+	 */
+	String[] getDomains(String cartridgeType, int tenantId);
+
+	/**
+	 * Provide service cluster sub domains corresponds to the given information.
+	 * @param cartridgeType cartridge type
+	 * @param tenantId tenant id
+	 * @return String array of service cluster sub domains
+	 */
+	String[] getSubDomains(String cartridgeType, int tenantId);
+
+//	/**
+//	 * Provide public IPs corresponds to the given information.
+//	 * @param cartridgeType cartridge type
+//	 * @param tenantId tenant id
+//	 * @return String array of public IPs
+//	 */
+//	String[] getActiveIPs(String cartridgeType, int tenantId);
+	
+	/**
+	 * Provide public IPs corresponds to the given information.
+	 * @param cartridgeType cartridge type
+	 * @param domain service cluster domain
+	 * @param subDomain service cluster sub domain
+	 * @return String array of public IPs
+	 */
+	String[] getActiveIPs(String cartridgeType, String domain, String subDomain);
+	
+	/**
+	 * Provide domains and the relevant subdomains corresponding to the given information
+	 * 
+	 * @param cartridgeType cartridge type
+	 * @param tenantId tenant id
+	 * @return DomainContext instances array of domains and sub domains 
+	 */
+	DomainContext[] getDomainsAndSubdomains (String cartridgeType, int tenantId);
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java
new file mode 100644
index 0000000..9b976cf
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java
@@ -0,0 +1,127 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.stratos.adc.topology.mgt.service.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
+import org.apache.stratos.adc.topology.mgt.serviceobjects.DomainContext;
+import org.apache.stratos.adc.topology.mgt.util.ConfigHolder;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.lb.common.conf.util.LoadBalancerConfigUtil;
+
+public class TopologyManagementServiceImpl implements TopologyManagementService {
+	
+	ConfigHolder data = ConfigHolder.getInstance();
+
+	public String[] getDomains(String cartridgeType, int tenantId) {
+		List<String> domains = new ArrayList<String>();
+		if(data.getServiceConfigs() != null){
+			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
+			if(serviceConfigs != null){
+				
+				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
+	                
+					List<Integer> tenantIds = LoadBalancerConfigUtil.getTenantIds(serviceConfiguration.getTenantRange());
+					if(!tenantIds.isEmpty() && (tenantIds.contains(tenantId) || tenantIds.contains(0))){
+						if (!domains.contains(serviceConfiguration.getDomain())) {
+							domains.add(serviceConfiguration.getDomain());
+						}
+					}
+                }
+			}
+		}
+		return domains.toArray(new String[domains.size()]);
+	}
+
+	public String[] getSubDomains(String cartridgeType, int tenantId) {
+		List<String> subDomains = new ArrayList<String>();
+		if(data.getServiceConfigs() != null){
+			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
+			if(serviceConfigs != null){
+				
+				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
+	                
+					List<Integer> tenantIds = LoadBalancerConfigUtil.getTenantIds(serviceConfiguration.getTenantRange());
+					if(!tenantIds.isEmpty() && (tenantIds.contains(tenantId) || tenantIds.contains(0))){
+						if (!subDomains.contains(serviceConfiguration.getSubDomain())) {
+							subDomains.add(serviceConfiguration.getSubDomain());
+						}
+					}
+                }
+			}
+		}
+		return subDomains.toArray(new String[subDomains.size()]);
+	}
+
+    public String[] getActiveIPs(String cartridgeType, String domain, String subDomain) {
+		List<String> publicIps = new ArrayList<String>();
+		
+		if(domain == null || subDomain == null){
+			return new String[0];
+		}
+		
+		if(data.getServiceConfigs() != null){
+			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
+			if(serviceConfigs != null){
+				
+				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
+	                
+					if(domain.equals(serviceConfiguration.getDomain()) && subDomain.equals(serviceConfiguration.getSubDomain())){
+						
+						String ipStr = serviceConfiguration.getPublicIp();
+						if(ipStr != null && !ipStr.isEmpty()){
+							for (String ip : ipStr.split(",")) {
+								if (!publicIps.contains(ip)) {
+									publicIps.add(ip);
+								}
+							}
+						}
+					}
+                }
+			}
+		}
+		return publicIps.toArray(new String[publicIps.size()]);
+	}
+
+	/* (non-Javadoc)
+	 * @see org.wso2.carbon.stratos.topology.mgt.service.TopologyManagementService#getDomainsAndSubdomains(java.lang.String, int)
+	 */
+	public DomainContext[] getDomainsAndSubdomains(String cartridgeType, int tenantId) {
+		List<DomainContext> domainContexts = new ArrayList<DomainContext>();
+		
+		if(data.getServiceConfigs() != null){
+			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
+			if(serviceConfigs != null){
+				
+				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
+	                
+					List<Integer> tenantIds = LoadBalancerConfigUtil.getTenantIds(serviceConfiguration.getTenantRange());
+					if(!tenantIds.isEmpty() && (tenantIds.contains(tenantId) || tenantIds.contains(0))){
+						DomainContext domainCtx = new DomainContext(serviceConfiguration.getDomain(), serviceConfiguration.getSubDomain());
+						if (!domainContexts.contains(domainCtx)) {
+							domainContexts.add(domainCtx);
+						}
+					}
+                }
+			}
+		}
+		return domainContexts.toArray(new DomainContext[domainContexts.size()]);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/serviceobjects/DomainContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/serviceobjects/DomainContext.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/serviceobjects/DomainContext.java
new file mode 100644
index 0000000..54357d2
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/serviceobjects/DomainContext.java
@@ -0,0 +1,90 @@
+/**
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.stratos.adc.topology.mgt.serviceobjects;
+
+/**
+ * Class to hold domain and subdomain details
+ *
+ */
+public class DomainContext {
+    
+    private String domain;
+    private String subDomain;
+    
+    /**
+     * Constructor
+     * 
+     * @param domain domain name
+     * @param subDomain subdomain name
+     */
+    public DomainContext (String domain, String subDomain) {
+        this.domain = domain;
+        this.subDomain = subDomain;
+    }
+
+    /**
+     * Returns the domain 
+     * 
+     * @return the domain
+     */
+    public String getDomain() {
+        return domain;
+    }
+
+    /**
+     * Returns the sub domain
+     * 
+     * @return the subDomain
+     */
+    public String getSubDomain() {
+        return subDomain;
+    }
+    
+    /**
+     * Overridden equals method
+     */
+    public boolean equals (Object object) {
+        if (object == null) 
+            return false;
+        if (object == this)  
+            return true;
+        if (!(object instanceof DomainContext))
+            return false;
+        
+        DomainContext domainCtx = (DomainContext)object;
+        if(this.getDomain().equals(domainCtx.getDomain()) &&
+                this.getSubDomain().equals(domainCtx.getSubDomain()))
+            return true;
+        else
+            return false;
+    }
+    
+    /**
+     * Overridden hashCode method
+     */
+    public int hashCode () {
+        int domainHash = 0;
+        int subDomainHash = 0;
+        
+        if(domain != null)
+            domainHash = domain.hashCode();
+        if(subDomain != null)
+            subDomainHash = subDomain.hashCode();
+        
+        return domainHash + subDomainHash;
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopicHealthChecker.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopicHealthChecker.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopicHealthChecker.java
new file mode 100644
index 0000000..de8f9df
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopicHealthChecker.java
@@ -0,0 +1,67 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.adc.topology.mgt.subscriber;
+
+import javax.jms.TopicSubscriber;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * This health checker runs forever, and is responsible for re-establishing a connection
+ * between SC and CC.
+ */
+public class TopicHealthChecker implements Runnable{
+    
+    private static final Log log = LogFactory.getLog(TopicHealthChecker.class);
+    private String topicName;
+    private TopicSubscriber subscriber;
+
+    public TopicHealthChecker(String topicName, TopicSubscriber subscriber) {
+        this.topicName = topicName;
+        this.subscriber = subscriber;
+    }
+    
+    @Override
+    public void run() {
+        log.info("Topic Health Checker is running... ");
+
+        while (true) {
+            try {
+                subscriber.getTopic();
+                
+                // health checker runs in every 30s
+                Thread.sleep(30000);
+
+            } catch (Exception e) {
+                // implies connection is not established
+                // sleep for 5s and retry
+                try {
+                    log.info("Health checker failed and will retry to establish a connection after a 5s.");
+                    Thread.sleep(5000);
+                    break;
+                } catch (InterruptedException ignore) {
+                }
+            }
+
+        }
+
+        TopologySubscriber.subscribe(topicName);
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologyListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologyListener.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologyListener.java
new file mode 100644
index 0000000..57289d7
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologyListener.java
@@ -0,0 +1,44 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.stratos.adc.topology.mgt.subscriber;
+
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageListener;
+import javax.jms.TextMessage;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.topology.mgt.util.ConfigHolder;
+
+public class TopologyListener implements MessageListener {
+
+    private static final Log log = LogFactory.getLog(TopologyListener.class);
+
+    @SuppressWarnings("unchecked")
+    public void onMessage(Message message) {
+        TextMessage receivedMessage = (TextMessage) message;
+        try {
+
+            ConfigHolder.getInstance().getSharedTopologyDiffQueue().add(receivedMessage.getText());
+
+        } catch (JMSException e) {
+            log.error(e.getMessage(), e);
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriber.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriber.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriber.java
new file mode 100644
index 0000000..97bf94f
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriber.java
@@ -0,0 +1,92 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.stratos.adc.topology.mgt.subscriber;
+
+import java.util.Properties;
+
+import javax.jms.*;
+import javax.naming.InitialContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.topology.mgt.util.TopologyConstants;
+
+public class TopologySubscriber {
+
+	private static final Log log = LogFactory.getLog(TopologySubscriber.class);
+	
+    public static void subscribe(String topicName) {
+        Properties initialContextProperties = new Properties();
+        TopicSubscriber topicSubscriber = null;
+        TopicSession topicSession = null;
+        TopicConnection topicConnection = null;
+        InitialContext initialContext = null;
+
+        initialContextProperties.put("java.naming.factory.initial",
+            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");
+
+        String mbServerIp =
+            System.getProperty(TopologyConstants.MB_SERVER_IP) == null
+                ? TopologyConstants.DEFAULT_MB_SERVER_IP
+                : System.getProperty(TopologyConstants.MB_SERVER_IP);
+
+        String connectionString =
+            "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" +
+                mbServerIp + "'&reconnect='true'";
+        initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);
+
+        try {
+            initialContext = new InitialContext(initialContextProperties);
+            TopicConnectionFactory topicConnectionFactory =
+                (TopicConnectionFactory) initialContext.lookup("qpidConnectionfactory");
+            topicConnection = topicConnectionFactory.createTopicConnection();
+            topicConnection.start();
+            topicSession =
+                topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Topic topic = topicSession.createTopic(topicName);
+            topicSubscriber =
+                topicSession.createSubscriber(topic);
+
+            topicSubscriber.setMessageListener(new TopologyListener());
+
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+
+            try {
+                if (topicSubscriber != null) {
+                    topicSubscriber.close();
+                }
+
+                if (topicSession != null) {
+                    topicSession.close();
+                }
+
+                if (topicConnection != null) {
+                    topicConnection.close();
+                }
+            } catch (JMSException e1) {
+                // ignore
+            }
+
+        } finally {
+            // start the health checker
+            Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
+            healthChecker.start();
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriberTask.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriberTask.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriberTask.java
new file mode 100644
index 0000000..525de89
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/subscriber/TopologySubscriberTask.java
@@ -0,0 +1 @@
+package org.apache.stratos.adc.topology.mgt.subscriber;

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java
new file mode 100644
index 0000000..a45aa8f
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java
@@ -0,0 +1,197 @@
+/**
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.stratos.adc.topology.mgt.util;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.topology.mgt.exception.TopologyMgtException;
+import org.apache.synapse.config.SynapseConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.ntask.core.service.TaskService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.service.RealmService;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+
+/**
+ *
+ */
+public class ConfigHolder {
+
+    private static ConfigHolder instance;
+    private static final Log log = LogFactory.getLog(ConfigHolder.class);
+
+    private SynapseConfiguration synapseConfiguration;
+    private ConfigurationContext configCtxt;
+    private AxisConfiguration axisConfiguration;
+    private UserRegistry configRegistry;
+    private UserRegistry governanceRegistry;
+    private TaskService taskService;
+    private BlockingQueue sharedTopologyDiffQueue = new LinkedBlockingQueue();
+    private String previousMessage;
+    private Map<String, List<ServiceConfiguration>> serviceNameToServiceConfigurations;
+//    private DependencyManagementService dependencyManager;
+    private LoadBalancerConfigurationService lbConfigService;
+    
+
+//    private Map<Integer, SynapseEnvironmentService> synapseEnvironmentServices =
+//            new HashMap<Integer, SynapseEnvironmentService>();
+
+    public RealmService getRealmService() {
+        return realmService;
+    }
+
+    public void setRealmService(RealmService realmService) {
+        this.realmService = realmService;
+    }
+
+    private RealmService realmService;
+
+    private ConfigHolder() {
+    }
+
+    public static ConfigHolder getInstance() {
+        if (instance == null) {
+            instance = new ConfigHolder();
+        }
+        return instance;
+    }
+
+    public SynapseConfiguration getSynapseConfiguration() throws TopologyMgtException{
+        assertNull("SynapseConfiguration", synapseConfiguration);
+        return synapseConfiguration;
+    }
+
+    public void setSynapseConfiguration(SynapseConfiguration synapseConfiguration) {
+        this.synapseConfiguration = synapseConfiguration;
+    }
+
+    public AxisConfiguration getAxisConfiguration() throws TopologyMgtException {
+        assertNull("AxisConfiguration", axisConfiguration);
+        return axisConfiguration;
+    }
+
+    public void setAxisConfiguration(AxisConfiguration axisConfiguration) {
+        this.axisConfiguration = axisConfiguration;
+    }
+
+    public UserRegistry getConfigRegistry() throws TopologyMgtException {
+        assertNull("Registry", configRegistry);
+        return configRegistry;
+    }
+
+    public void setConfigRegistry(UserRegistry configRegistry) {
+        this.configRegistry = configRegistry;
+    }
+
+////    public DependencyManagementService getDependencyManager() {
+////        return dependencyManager;
+////    }
+//
+//    public void setDependencyManager(DependencyManagementService dependencyManager) {
+//        this.dependencyManager = dependencyManager;
+//    }
+
+    private void assertNull(String name, Object object) throws TopologyMgtException {
+        if (object == null) {
+            String message = name + " reference in the proxy admin config holder is null";
+            log.error(message);
+            throw new TopologyMgtException(message);
+        }
+    }
+
+    public UserRegistry getGovernanceRegistry() {
+        return governanceRegistry;
+    }
+
+    public void setGovernanceRegistry(UserRegistry governanceRegistry) {
+        this.governanceRegistry = governanceRegistry;
+    }
+
+//    public SynapseEnvironmentService getSynapseEnvironmentService(int id) {
+//        return synapseEnvironmentServices.get(id);
+//    }
+//
+//    public void addSynapseEnvironmentService(int id,
+//                                             SynapseEnvironmentService synapseEnvironmentService) {
+//        synapseEnvironmentServices.put(id, synapseEnvironmentService);
+//    }
+//
+//    public void removeSynapseEnvironmentService(int id) {
+//        synapseEnvironmentServices.remove(id);
+//    }
+//
+//    public Map<Integer, SynapseEnvironmentService> getSynapseEnvironmentServices() {
+//        return synapseEnvironmentServices;
+//    }
+
+    public ConfigurationContext getConfigCtxt() {
+        return configCtxt;
+    }
+
+    public void setConfigCtxt(ConfigurationContext configCtxt) {
+        this.configCtxt = configCtxt;
+    }
+    
+    public void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
+        this.lbConfigService = lbConfigSer;
+    }
+
+    public LoadBalancerConfiguration getLbConfig() {
+        return (LoadBalancerConfiguration) lbConfigService.getLoadBalancerConfig();
+    }
+    
+    public TaskService getTaskService() {
+        return taskService;
+    }
+
+    public void setTaskService(TaskService taskService) {
+        this.taskService = taskService;
+    }
+
+    public BlockingQueue getSharedTopologyDiffQueue() {
+	    return sharedTopologyDiffQueue;
+    }
+
+	public void setSharedTopologyDiffQueue(BlockingQueue sharedTopologyDiffQueue) {
+	    this.sharedTopologyDiffQueue = sharedTopologyDiffQueue;
+    }
+
+	public void setServiceConfigs(Map<String, List<ServiceConfiguration>> serviceNameToServiceConfigurations) {
+
+		this.serviceNameToServiceConfigurations = serviceNameToServiceConfigurations;
+    }
+	
+	public Map<String, List<ServiceConfiguration>> getServiceConfigs(){
+		return serviceNameToServiceConfigurations;
+	}
+
+	public String getPreviousMessage() {
+	    return previousMessage;
+    }
+
+	public void setPreviousMessage(String previousMessage) {
+	    this.previousMessage = previousMessage;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyConstants.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyConstants.java
new file mode 100644
index 0000000..984610d
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyConstants.java
@@ -0,0 +1,13 @@
+package org.apache.stratos.adc.topology.mgt.util;
+
+public class TopologyConstants {
+    
+    public static final String TOPIC_NAME = "cloud-controller-topology";
+    public static final String MB_SERVER_IP = "mb.server.ip";
+    public static final String DEFAULT_MB_SERVER_IP = "localhost:5673";
+    
+    public static final String TOPOLOGY_SYNC_CRON = "1 * * * * ? *";
+	public static final String TOPOLOGY_SYNC_TASK_NAME = "TopologySubscriberTaskOfADC";
+	public static final String TOPOLOGY_SYNC_TASK_TYPE = "TOPOLOGY_SUBSCRIBER_TASK";
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyMgtUtil.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyMgtUtil.java
new file mode 100644
index 0000000..01ff6db
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/TopologyMgtUtil.java
@@ -0,0 +1,5 @@
+package org.apache.stratos.adc.topology.mgt.util;
+
+public class TopologyMgtUtil {
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.adc.topology.mgt/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..ef91287
--- /dev/null
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/resources/META-INF/services.xml
@@ -0,0 +1,9 @@
+<serviceGroup>
+    <service name="TopologyMgtService" scope="application">
+        <parameter name="ServiceClass">org.apache.stratos.adc.topology.mgt.service.impl.TopologyManagementServiceImpl</parameter>
+        <messageReceivers>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
+    </messageReceivers>
+    </service>
+</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/pom.xml b/components/org.apache.stratos.autoscaler.service/pom.xml
new file mode 100644
index 0000000..cd31522
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/pom.xml
@@ -0,0 +1,208 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     ~  Licensed to the Apache Software Foundation (ASF) under one
+     ~  or more contributor license agreements.  See the NOTICE file
+     ~  distributed with this work for additional information
+     ~  regarding copyright ownership.  The ASF licenses this file
+     ~  to you under the Apache License, Version 2.0 (the
+     ~  "License"); you may not use this file except in compliance
+     ~  with the License.  You may obtain a copy of the License at
+     ~
+     ~    http://www.apache.org/licenses/LICENSE-2.0
+     ~
+     ~  Unless required by applicable law or agreed to in writing,
+     ~  software distributed under the License is distributed on an
+     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+     ~  KIND, either express or implied.  See the License for the
+     ~  specific language governing permissions and limitations
+     ~  under the License.
+     ~
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.apache.stratos</groupId>
+    <artifactId>org.apache.stratos.autoscaler.service</artifactId>
+    <packaging>aar</packaging>
+    <name>Apache Stratos - Autoscaler Service</name>
+    <url>http://apache.org</url>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-shade-plugin</artifactId>
+                <version>1.7.1</version>
+                <executions>
+                    <execution>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>shade</goal>
+                        </goals>
+                        <configuration>
+                            <artifactSet>
+                                <includes>
+                                    <include>org.jclouds:*</include>
+                                    <include>org.jclouds.*:*</include>
+                                </includes>
+                            </artifactSet>
+                            <filtering>true</filtering>
+                            <filters>
+                                <filter>
+                                    <artifact>org.jclouds*:*</artifact>
+                                    <includes>
+                                        <include>META-INF/services/org.jclouds.apis.ApiMetadata</include>
+                                        <include>META-INF/services/org.jclouds.providers.ProviderMetadata</include>
+                                    </includes>
+                                </filter>
+                            </filters>
+                            <transformers>
+                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer">
+                                </transformer>
+                            </transformers>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.axis2</groupId>
+                <artifactId>axis2-aar-maven-plugin</artifactId>
+                <version>1.4</version>
+                <extensions>true</extensions>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.apache.stratos.autoscaler.service
+                        </Export-Package>
+                        <Private-Package>
+                            org.apache.stratos.autoscaler.service.*, !org.apache.stratos.autoscaler.service
+                        </Private-Package>
+                        <Import-Package>
+                        	  !org.apache.commons.logging,
+                            org.apache.commons.logging; version=0.0.0,
+                            org.wso2.carbon.utils.*,
+                            org.jclouds.compute*;version="${jclouds.version}";resolution:=optional,
+                            org.jclouds*;version="${jclouds.version}",
+                            *; resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+	    <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.lb.common</artifactId>
+            <version>${apache.stratos.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.securevault</artifactId>
+            <version>4.1.0</version>
+            <!--version>${wso2carbon.version}</version-->
+        </dependency>
+        <!--dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-core</artifactId>
+            <version>${synapse.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-commons</artifactId>
+            <version>${synapse.version}</version>
+        </dependency--> 
+	
+        <!--  Jclouds dependencies -->
+         <dependency>
+           <groupId>org.jclouds</groupId>
+           <artifactId>jclouds-allcompute</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds</groupId>
+           <artifactId>jclouds-compute</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-bouncycastle</artifactId>
+           <version>${jclouds.version}</version>
+           <exclusions>
+              <exclusion>
+                 <groupId>org.bouncycastle</groupId>
+                 <artifactId>bcprov-jdk16</artifactId>
+              </exclusion>
+           </exclusions>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-sshj</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-log4j</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-enterprise</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <!--dependency>
+           <groupId>org.jclouds.api</groupId>
+           <artifactId>ec2</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.provider</groupId>
+           <artifactId>aws-ec2</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.api</groupId>
+           <artifactId>openstack-nova</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency-->
+       
+    </dependencies>
+
+    <properties>
+        <jclouds.version>1.5.0-beta.5</jclouds.version>
+    </properties>
+
+</project>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/IAutoscalerService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/IAutoscalerService.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/IAutoscalerService.java
new file mode 100644
index 0000000..9bf06fc
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/IAutoscalerService.java
@@ -0,0 +1,112 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service;
+
+import org.apache.stratos.lb.common.conf.util.Constants;
+
+/**
+ * This Interface provides a way for a component, to communicate with an underline
+ * Infrastructure which are supported by <i>JClouds</i>.
+ * 
+ */
+public interface IAutoscalerService {
+    
+    /**
+     * Initialize the service.
+     * @param isSpi if this service is to be used by SPI, this parameter should be set to
+     * true. When this is true, you should specify an image id, each time you
+     * are starting an instance i.e. you should use {@link #startSpiInstance(String, String)}
+     * method, instead of using {@link #startInstance(String)}.
+     * @return
+     */
+    public boolean initAutoscaler(boolean isSpi);
+
+    
+    /**
+     * Calling this method will result in an instance startup, which is belong
+     * to the provided service domain. This method is non-blocking, means we do not
+     * wait till the instance is started up. Also note that the instance that is starting up
+     * belongs to the group whose name is derived from its service domain, replacing <i>.</i>
+     * by a hyphen (<i>-</i>). 
+     * @param domainName service clustering domain of the instance to be started up.
+     * @param sudDomainName service clustering sub domain of the instance to be started up.
+     * If this is null, the default value will be used. Default value is 
+     * {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return whether the starting up is successful or not.
+     */
+    public boolean startInstance(String domainName, String sudDomainName);
+    
+    /**
+     * Calling this method will result in an instance startup, which is belong
+     * to the provided service domain. This method will return the public IP address of
+     * the instance that is started. Thus, this method is blocking, since we need to 
+     * return the IP Address and for that we have to wait till the instance started up.
+     * @param domainName should be in following format.
+     * <code>${service-domain}\t\${tenant-id}</code>.
+     * @param imageId starting instance will be an instance of this image. Image id should
+     * be a valid one.
+     * @param sudDomainName service clustering sub domain of the instance to be started up.
+     * If this is null, the default value will be used. Default value is 
+     * {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return public IP address of the instance in String format. If instance failed to 
+     * start, this will return an empty String.
+     */
+    public String startSpiInstance(String domainName, String subDomainName, String imageId);
+    
+   
+    /**
+     * Calling this method will result in termination of an instance which is belong
+     * to the provided service domain.
+     * @param domainName service domain of the instance to be terminated.
+     * @param sudDomainName service clustering sub domain of the instance to be started up.
+     * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return whether an instance terminated successfully or not.
+     */
+	public boolean terminateInstance(String domainName, String subDomainName);
+	
+	/**
+	 * Calling this method will result in termination of the lastly spawned instance which is
+	 * belong to the provided service domain.
+	 * @param domainName service domain of the instance to be terminated.
+	 * @param sudDomainName service clustering sub domain of the instance to be started up.
+     * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
+	 * @return whether the termination is successful or not.
+	 */
+	public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName);
+	
+	/**
+     * Calling this method will result in termination of an instance which has the
+     * provided public IP address.
+     * @param publicIp public IP address of the instance to be terminated.
+     * @return whether the instance terminated successfully or not.
+     */
+    public boolean terminateSpiInstance(String publicIp);
+	
+	/**
+	 * Calling this method will result in returning the pending instances
+	 * count of a particular domain.
+	 * @param domainName service domain
+	 * @param sudDomainName service clustering sub domain of the instance to be started up.
+     * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
+	 * @return number of pending instances for this domain. If no instances of this 
+	 * domain is present, this will return zero.
+	 */
+	public int getPendingInstanceCount(String domainName, String subDomainName);
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/AutoscalerServiceException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/AutoscalerServiceException.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/AutoscalerServiceException.java
new file mode 100644
index 0000000..70e82c8
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/AutoscalerServiceException.java
@@ -0,0 +1,33 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.exception;
+
+public class AutoscalerServiceException extends RuntimeException {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public AutoscalerServiceException(String msg) {
+        super(msg);
+    }
+    
+    public AutoscalerServiceException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/DeserializationException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/DeserializationException.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/DeserializationException.java
new file mode 100644
index 0000000..01819d1
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/DeserializationException.java
@@ -0,0 +1,33 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.exception;
+
+public class DeserializationException extends RuntimeException {
+    
+    private static final long serialVersionUID = -2426068347954381831L;
+
+    public DeserializationException(String msg) {
+        super(msg);
+    }
+    
+    public DeserializationException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/MalformedConfigurationFileException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/MalformedConfigurationFileException.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/MalformedConfigurationFileException.java
new file mode 100644
index 0000000..090e931
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/MalformedConfigurationFileException.java
@@ -0,0 +1,33 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.exception;
+
+public class MalformedConfigurationFileException extends RuntimeException {
+
+    private static final long serialVersionUID = -1662095377704279326L;
+    
+    public MalformedConfigurationFileException(String msg) {
+        super(msg);
+    }
+    
+    public MalformedConfigurationFileException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/NoInstanceFoundException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/NoInstanceFoundException.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/NoInstanceFoundException.java
new file mode 100644
index 0000000..be9356f
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/NoInstanceFoundException.java
@@ -0,0 +1,39 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.exception;
+
+/**
+ * This will throw when no instance is found
+ */
+public class NoInstanceFoundException extends Exception {
+
+    /**
+     * For serializing requirement
+     */
+    private static final long serialVersionUID = -435060299292679892L;
+
+
+    public NoInstanceFoundException(String msg) {
+        super(msg);
+    }
+    
+    public NoInstanceFoundException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/SerializationException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/SerializationException.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/SerializationException.java
new file mode 100644
index 0000000..0ccbd61
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/exception/SerializationException.java
@@ -0,0 +1,33 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.exception;
+
+public class SerializationException extends RuntimeException {
+    
+    private static final long serialVersionUID = -3701458642228072331L;
+
+    public SerializationException(String msg) {
+        super(msg);
+    }
+    
+    public SerializationException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}


[45/45] git commit: Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-stratos

Posted by is...@apache.org.
Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-stratos


Project: http://git-wip-us.apache.org/repos/asf/incubator-stratos/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-stratos/commit/99508a50
Tree: http://git-wip-us.apache.org/repos/asf/incubator-stratos/tree/99508a50
Diff: http://git-wip-us.apache.org/repos/asf/incubator-stratos/diff/99508a50

Branch: refs/heads/master
Commit: 99508a5006e30a5e5cab3ebacef9716c1cfb03ab
Parents: ac065d7 9d7cc50
Author: Isuru <is...@wso2.com>
Authored: Wed Jul 10 22:21:01 2013 +0530
Committer: Isuru <is...@wso2.com>
Committed: Wed Jul 10 22:21:01 2013 +0530

----------------------------------------------------------------------
 .../cartridge/autoscaler/service/axiom/AxiomValidationTest.java    | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------



[19/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/pom.xml b/components/org.apache.stratos.common/2.1.2/pom.xml
deleted file mode 100644
index 457684e..0000000
--- a/components/org.apache.stratos.common/2.1.2/pom.xml
+++ /dev/null
@@ -1,87 +0,0 @@
-<!--
-  ~ Licensed to the Apache Software Foundation (ASF) under one
-  ~ or more contributor license agreements. See the NOTICE file
-  ~ distributed with this work for additional information
-  ~ regarding copyright ownership. The ASF licenses this file
-  ~ to you under the Apache License, Version 2.0 (the
-  ~ "License"); you may not use this file except in compliance
-  ~ with the License. You may obtain a copy of the License at
-  ~
-  ~ http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing,
-  ~ software distributed under the License is distributed on an
-  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-  ~ KIND, either express or implied. See the License for the
-  ~ specific language governing permissions and limitations
-  ~ under the License.
-  -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.common</artifactId>
-    <version>2.1.2</version>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Common</name>
-
-    <build>
-
-        <plugins>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Export-Package>
-                            org.apache.stratos.common.*,
-                        </Export-Package>
-                        <Import-Package>
-                            org.wso2.carbon.registry.core.*;version=1.0.1,
-                            org.wso2.carbon.user.core.*,
-                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
-                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
-                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
-                            *;resolution:=optional
-                        </Import-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.registry.core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.user.core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.user.mgt</artifactId>
-        </dependency>
-        <dependency>
-             <groupId>junit</groupId>
-             <artifactId>junit</artifactId>
-             <scope>test</scope>
-         </dependency>        
-    </dependencies>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/TenantBillingService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/TenantBillingService.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/TenantBillingService.java
deleted file mode 100644
index 23cb7ae..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/TenantBillingService.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common;
-
-import org.apache.stratos.common.exception.StratosException;
-import org.wso2.carbon.user.api.Tenant;
-
-/**
- * The OSGI service interface that enables tenant related billing actions.
- */
-public interface TenantBillingService {
-    
-    public void addUsagePlan(Tenant tenant, String usagePlan) throws StratosException;
-    
-    public String getActiveUsagePlan(String tenantDomain) throws StratosException;
-    
-    public void updateUsagePlan(String tenantDomain, String usagePlan) throws StratosException;
-    
-    public void activateUsagePlan(String tenantDomain) throws StratosException;
-    
-    public void deactivateActiveUsagePlan(String tenantDomain) throws StratosException;
-
-    public void deleteBillingData(int tenantId) throws StratosException;
-
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/beans/TenantInfoBean.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/beans/TenantInfoBean.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/beans/TenantInfoBean.java
deleted file mode 100755
index 447814d..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/beans/TenantInfoBean.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.common.beans;
-
-import java.util.Calendar;
-
-/**
- * Bean class for Tenant Information
- */
-public class TenantInfoBean {
-
-    private String admin; //admin's user name
-    private String firstname;
-    private String lastname;
-    private String adminPassword;
-    private String tenantDomain;
-    private int tenantId;
-    private String email;
-    private boolean active;
-    private String successKey;
-    Calendar createdDate;
-    private String originatedService;
-    private String usagePlan;
-
-    public String getFirstname() {
-        return firstname;
-    }
-
-    public void setFirstname(String firstname) {
-        this.firstname = firstname;
-    }
-
-    public String getLastname() {
-        return lastname;
-    }
-
-    public void setLastname(String lastname) {
-        this.lastname = lastname;
-    }
-
-    public String getEmail() {
-
-        return email;
-    }
-
-    public void setEmail(String email) {
-        this.email = email;
-    }
-
-    public int getTenantId() {
-        return tenantId;
-    }
-
-    public void setTenantId(int tenantId) {
-        this.tenantId = tenantId;
-    }
-
-    public String getTenantDomain() {
-        return tenantDomain;
-    }
-
-    public void setTenantDomain(String tenantDomain) {
-        this.tenantDomain = tenantDomain;
-    }
-
-    public String getAdmin() {
-        return admin;
-    }
-
-    public void setAdmin(String admin) {
-        this.admin = admin;
-    }
-
-    public String getAdminPassword() {
-        return adminPassword;
-    }
-
-    public void setAdminPassword(String adminPassword) {
-        this.adminPassword = adminPassword;
-    }
-
-    public boolean isActive() {
-        return active;
-    }
-
-    public void setActive(boolean active) {
-        this.active = active;
-    }
-
-    public String getSuccessKey() {
-        return successKey;
-    }
-
-    public void setSuccessKey(String successKey) {
-        this.successKey = successKey;
-    }
-
-    public Calendar getCreatedDate() {
-        return createdDate;
-    }
-
-    public void setCreatedDate(Calendar createdDate) {
-        this.createdDate = createdDate;
-    }
-
-    public String getOriginatedService() {
-        return originatedService;
-    }
-
-    public void setOriginatedService(String originatedService) {
-        this.originatedService = originatedService;
-    }
-
-    public String getUsagePlan() {
-        return usagePlan;
-    }
-
-    public void setUsagePlan(String usagePlan) {
-        this.usagePlan = usagePlan;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServiceConfig.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServiceConfig.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServiceConfig.java
deleted file mode 100644
index 62c1664..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServiceConfig.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.config;
-
-import org.apache.axiom.om.OMElement;
-
-import javax.xml.namespace.QName;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-public class CloudServiceConfig {
-    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
-
-    private static final String NAME_ATTR_NAME = "name";
-    private static final String DEFAULT_ATTR_NAME = "default";
-    private static final String LABEL_ELEMENT_NAME = "label";
-    private static final String LINK_ELEMENT_NAME = "link";
-    private static final String ICON_ELEMENT_NAME = "icon";
-    private static final String DESCRIPTION_ELEMENT_NAME = "description";
-    private static final String PERMISSIONS_ELEMENT_NAME = "permissions";
-    private static final String PERMISSION_ELEMENT_NAME = "permission";
-    private static final String PRODUCT_PAGE_URL_ELEMENT_NAME = "productPageURL";
-
-    private String name;
-    private String label;
-    private String link;
-    private String icon;
-    private String description;
-    private List<PermissionConfig> permissionConfigs;
-    boolean defaultActive;
-    private String productPageURL;
-
-    public CloudServiceConfig(OMElement configEle) {
-        permissionConfigs = new ArrayList<PermissionConfig>();
-        serialize(configEle);
-    }
-
-    public void serialize(OMElement configEle) {
-        Iterator cloudServiceChildIt = configEle.getChildElements();
-        name = configEle.getAttributeValue(new QName(null, NAME_ATTR_NAME));
-        defaultActive = "true".equals(configEle.
-                getAttributeValue(new QName(null, DEFAULT_ATTR_NAME)));
-        while (cloudServiceChildIt.hasNext()) {
-            Object cloudServiceChildObj = cloudServiceChildIt.next();
-            if (!(cloudServiceChildObj instanceof OMElement)) {
-                continue;
-            }
-            OMElement cloudServiceChildEle = (OMElement) cloudServiceChildObj;
-            if (new QName(CONFIG_NS, LABEL_ELEMENT_NAME, "").
-                    equals(cloudServiceChildEle.getQName())) {
-                label = cloudServiceChildEle.getText();
-            } else if (new QName(CONFIG_NS, ICON_ELEMENT_NAME, "").
-                    equals(cloudServiceChildEle.getQName())) {
-                icon = cloudServiceChildEle.getText();
-            } else if (new QName(CONFIG_NS, LINK_ELEMENT_NAME, "").
-                    equals(cloudServiceChildEle.getQName())) {
-                link = cloudServiceChildEle.getText();
-            } else if (new QName(CONFIG_NS, PRODUCT_PAGE_URL_ELEMENT_NAME, "").
-                    equals(cloudServiceChildEle.getQName())) {
-                productPageURL = cloudServiceChildEle.getText();
-            } else if (new QName(CONFIG_NS, DESCRIPTION_ELEMENT_NAME, "").
-                    equals(cloudServiceChildEle.getQName())) {
-                description = cloudServiceChildEle.getText();
-            } else if (new QName(CONFIG_NS, PERMISSIONS_ELEMENT_NAME, "").
-                    equals(cloudServiceChildEle.getQName())) {
-                Iterator permissionChildIt = cloudServiceChildEle.getChildElements();
-                while (permissionChildIt.hasNext()) {
-                    Object permissionChildObj = permissionChildIt.next();
-                    if (!(permissionChildObj instanceof OMElement)) {
-                        continue;
-                    }
-                    OMElement permissionChildEle = (OMElement) permissionChildObj;
-
-                    if (new QName(CONFIG_NS, PERMISSION_ELEMENT_NAME, "").
-                            equals(permissionChildEle.getQName())) {
-                        PermissionConfig permissionConfig =
-                                new PermissionConfig(permissionChildEle);
-                        permissionConfigs.add(permissionConfig);
-                    }
-                }
-            }
-
-        }
-    }
-
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getLabel() {
-        return label;
-    }
-
-    public void setLabel(String label) {
-        this.label = label;
-    }
-
-    public String getLink() {
-        return link;
-    }
-
-    public void setLink(String link) {
-        this.link = link;
-    }
-
-    public String getIcon() {
-        return icon;
-    }
-
-    public void setIcon(String icon) {
-        this.icon = icon;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-
-    public List<PermissionConfig> getPermissionConfigs() {
-        return permissionConfigs;
-    }
-
-    public void setPermissionConfigs(List<PermissionConfig> permissionConfigs) {
-        this.permissionConfigs = permissionConfigs;
-    }
-
-    public boolean isDefaultActive() {
-        return defaultActive;
-    }
-
-    public void setDefaultActive(boolean defaultActive) {
-        this.defaultActive = defaultActive;
-    }
-
-    public String getProductPageURL() {
-        return productPageURL;
-    }
-
-    public void setProductPageURL(String productPageURL) {
-        this.productPageURL = productPageURL;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServiceConfigParser.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServiceConfigParser.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServiceConfigParser.java
deleted file mode 100644
index 3cedeff..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServiceConfigParser.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.config;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.common.constants.StratosConstants;
-import org.apache.stratos.common.util.CommonUtil;
-import org.wso2.carbon.utils.CarbonUtils;
-
-import java.io.File;
-import java.io.FileInputStream;
-
-public class CloudServiceConfigParser {
-
-    private static Log log = LogFactory.getLog(CloudServiceConfigParser.class);
-
-    private static class SynchronizingClass {
-    }
-
-    private static final SynchronizingClass loadlock = new SynchronizingClass();
-
-    private static CloudServicesDescConfig cloudServicesDescConfig = null;
-
-    private static final String CONFIG_FILENAME = "cloud-services-desc.xml";
-
-    public static CloudServicesDescConfig loadCloudServicesConfiguration() throws Exception {
-        if (cloudServicesDescConfig != null) {
-            return cloudServicesDescConfig;
-        }
-
-        synchronized (loadlock) {
-            if (cloudServicesDescConfig == null) {
-                try {
-                    String configFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + 
-                            StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator + CONFIG_FILENAME;
-                    OMElement configElement = CommonUtil.buildOMElement(new FileInputStream(configFileName));
-                    cloudServicesDescConfig = new CloudServicesDescConfig(configElement);
-                } catch (Exception e) {
-                    String msg = "Error in building the cloud service configuration.";
-                    log.error(msg, e);
-                    throw new Exception(msg, e);
-                }
-            }
-        }
-        return cloudServicesDescConfig;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServicesDescConfig.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServicesDescConfig.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServicesDescConfig.java
deleted file mode 100644
index 1bbd7aa..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/CloudServicesDescConfig.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.config;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import javax.xml.namespace.QName;
-import java.util.*;
-
-public class CloudServicesDescConfig {
-    private static final Log log = LogFactory.getLog(CloudServicesDescConfig.class);
-    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
-    private static final String CLOUD_SERVICE_ELEMENT_NAME = "cloudService";
-
-    Map<String, CloudServiceConfig> cloudServiceConfigs;
-
-    public CloudServicesDescConfig(OMElement configEle) {
-        // as the cloud service configs are kept in an order, we use an ordered map.
-        cloudServiceConfigs = new LinkedHashMap<String, CloudServiceConfig>();
-        serialize(configEle);
-    }
-
-    public void serialize(OMElement configEle) {
-        Iterator configChildIt = configEle.getChildElements();
-        while (configChildIt.hasNext()) {
-            Object configChildObj = configChildIt.next();
-            if (!( configChildObj instanceof OMElement)) {
-                continue;
-            }
-            OMElement configChildEle = (OMElement)configChildObj;
-            if (new QName(CONFIG_NS, CLOUD_SERVICE_ELEMENT_NAME, "").
-                    equals(configChildEle.getQName())) {
-                CloudServiceConfig cloudServiceConfig = new CloudServiceConfig(configChildEle);
-                String name = cloudServiceConfig.getName();
-                cloudServiceConfigs.put(name, cloudServiceConfig);
-            }
-        }
-    }
-
-    public Map<String, CloudServiceConfig> getCloudServiceConfigs() {
-        return cloudServiceConfigs;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/PermissionConfig.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/PermissionConfig.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/PermissionConfig.java
deleted file mode 100644
index f4d4716..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/config/PermissionConfig.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.config;
-
-import org.apache.axiom.om.OMElement;
-
-import javax.xml.namespace.QName;
-import java.util.Iterator;
-
-public class PermissionConfig {
-    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
-    private static final String PATH = "path";
-    private static final String NAME = "name";
-    String name;
-    String path;
-
-    public PermissionConfig(OMElement configEle) {
-        serialize(configEle);
-    }
-
-    public void serialize(OMElement configEle) {
-
-        Iterator configChildIt = configEle.getChildElements();
-        while (configChildIt.hasNext()) {
-            Object configChildObj = configChildIt.next();
-            if (!( configChildObj instanceof OMElement)) {
-                continue;
-            }
-            OMElement configChildEle = (OMElement)configChildObj;
-            if (new QName(CONFIG_NS, NAME, "").
-                    equals(configChildEle.getQName())) {
-                name = configChildEle.getText();
-            } else if (new QName(CONFIG_NS, PATH, "").
-                    equals(configChildEle.getQName())) {
-                path = configChildEle.getText();
-            }
-        }
-    }
-
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getPath() {
-        return path;
-    }
-
-    public void setPath(String path) {
-        this.path = path;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/constants/StratosConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/constants/StratosConstants.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/constants/StratosConstants.java
deleted file mode 100644
index 800206a..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/constants/StratosConstants.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.constants;
-
-
-public class StratosConstants {
-
-    public static final String CLOUD_SERVICE_IS_ACTIVE_PROP_KEY = "active";
-
-    public static final String CLOUD_SERVICE_INFO_STORE_PATH =
-            "/repository/components/org.wso2.stratos/cloud-manager/cloud-services";
-
-    public static final String TENANT_USER_VALIDATION_STORE_PATH =
-            "/repository/components/org.wso2.carbon.validations";
-    public static final String ADMIN_EMAIL_VERIFICATION_FLAG_PATH =
-            "/repository/components/org.wso2.carbon.email-confirmation-flag";
-    public static final String TENANT_DOMAIN_VERIFICATION_FLAG_PATH =
-            "/repository/components/org.wso2.carbon.domain-confirmation-flag";
-
-    public static final String DOMAIN_VALIDATOR_INFO_PATH =
-            "/repository/components/org.wso2.carbon.domain-validator-info";
-
-    public static final String TENANT_CREATION_THEME_PAGE_TOKEN =
-            "/repository/components/org.wso2.carbon.theme-page-token";
-
-    public static final String TENANT_PACKAGE_INFO_PATH =
-            "/repository/components/org.wso2.carbon.package-info";
-
-    public static final String ALL_THEMES_PATH =
-            "/repository/components/org.wso2.carbon.all-themes";
-
-    public static final String THROTTLING_RULES_PATH =
-            "/repository/components/org.wso2.carbon.throttling-rules";
-
-    public static final String ORIGINATED_SERVICE_PATH =
-            "/repository/components/org.wso2.carbon.originated-service";
-
-    public static final String PATH_SEPARATOR = "/";
-
-    public static final String CLOUD_SERVICE_ICONS_STORE_PATH =
-            "/repository/components/org.wso2.carbon.cloud-manager/" +
-                    "cloud-services-icons";
-
-    public static final String VALIDATION_KEY_RESOURCE_NAME = "validation-key";
-    public static final String INCOMING_PATH_DIR = "incoming";
-    public static final String OUTGOING_PATH_DIR = "outgoing";
-    public static final String MULTITENANCY_SCHEDULED_TASK_ID = "multitenancyScheduledTask";
-    public static final String MULTITENANCY_VIEWING_TASK_ID = "multitenancyViewingTask";
-
-    public static final String INVALID_TENANT = "invalidTenant";
-    public static final String INACTIVE_TENANT = "inactiveTenant";
-    public static final String ACTIVE_TENANT = "activeTenant";
-    public static final String IS_EMAIL_VALIDATED = "isEmailValidated";
-    public static final String IS_CREDENTIALS_ALREADY_RESET = "isCredentialsReset";
-    public static final String TENANT_ADMIN = "tenantAdminUsername";
-
-    public static final String CLOUD_MANAGER_SERVICE = "WSO2 Stratos Manager";
-    public static final String CLOUD_IDENTITY_SERVICE = "WSO2 Stratos Identity";
-    public static final String CLOUD_GOVERNANCE_SERVICE = "WSO2 Stratos Governance";
-    public static final String CLOUD_ESB_SERVICE = "WSO2 Stratos Enterprise Service Bus";
-
-    // keystore mgt related Constants
-    public static final String TENANT_KS = "/repository/security/key-stores/";
-    public static final String TENANT_PUB_KEY = "/repository/security/pub-key";
-    public static final String PROP_TENANT_KS_TYPE = "key-store-type";
-    public static final String PROP_TENANT_KS_PASSWD = "key-store-password";
-    public static final String PROP_TENANT_KS_PRIV_KEY_PASSWD = "priv-key-password";
-    public static final String PROP_TENANT_KS_ALIAS = "alias";
-
-    // constants related to redirection
-
-    public static final String UNVERIFIED_ACCOUNT_DOMAIN_SUFFIX = "-unverified";
-    public static final String TENANT_SPECIFIC_URL_RESOLVED = "tenant-sepcific-url-resolved";
-    public static final String SUFFIXED_UNVERIFIED_SESSION_FLAG = "temp-suffixed-unverified";
-
-    // metering constants
-    public static final String THROTTLING_ALL_ACTION = "all_actions";
-    public static final String THROTTLING_IN_DATA_ACTION = "in_data_action"; //this covers registry capacity + registry bandwidth
-    public static final String THROTTLING_OUT_DATA_ACTION = "out_data_action"; //this covers registry bandwidth
-    public static final String THROTTLING_ADD_USER_ACTION = "add_user_action";
-    public static final String THROTTLING_SERVICE_IN_BANDWIDTH_ACTION = "service_in_bandwith_action";
-    public static final String THROTTLING_SERVICE_OUT_BANDWIDTH_ACTION = "service_out_bandwith_action";
-    public static final String THROTTLING_WEBAPP_IN_BANDWIDTH_ACTION = "webapp_in_bandwith_action";
-    public static final String THROTTLING_WEBAPP_OUT_BANDWIDTH_ACTION = "webapp_out_bandwith_action";
-    public static final String THROTTLING_SERVICE_REQUEST_ACTION = "service_request_action";
-    public static final String THROTTLING_SERVICE_RESPONSE_ACTION = "service_response_action";
-
-    // the session attribute to keep track whether the registry action validated
-    // and the usage persisted
-    public static final String REGISTRY_ACTION_VALIDATED_SESSION_ATTR = "registryActionValidated";
-    public static final String REGISTRY_USAGE_PERSISTED_SESSION_ATTR = "usagePersited";
-
-    // Metering servlet attributes
-    public static final String SERVICE_NAME_SERVLET_ATTR = "meteringServiceName";
-    public static final String TENANT_ID_SERVLET_ATTR = "tenantId";
-    public static final String ADMIN_SERVICE_SERVLET_ATTR = "adminService";
-
-    // * as a Service impl related constants
-    public static final String ORIGINATED_SERVICE = "originatedService";
-
-    // Configuration file name
-    public static final String STRATOS_CONF_FILE = "stratos.xml";
-    //public static final String STRATOS_CONF_LOC = "repository/conf/";
-    //public static final String STRATOS_CONF_FILE_WITH_PATH = STRATOS_CONF_LOC + STRATOS_CONF_FILE;
-
-    // EULA location
-    public static final String STRATOS_EULA = "eula.xml";
-
-    // EULA default text.
-    public static final String STRATOS_EULA_DEFAULT_TEXT =
-            "Please refer to: " + StratosConstants.STRATOS_TERMS_OF_USAGE +
-                    " for terms and usage and " + StratosConstants.STRATOS_PRIVACY_POLICY +
-                    " for privacy policy of WSO2 Stratos.";
-
-    // Web location of Terms of Usage and privacy policy
-    public static final String STRATOS_TERMS_OF_USAGE =
-            "http://wso2.com/cloud/services/terms-of-use/";
-    public static final String STRATOS_PRIVACY_POLICY =
-            "http://wso2.com/cloud/services/privacy-policy/";
-    public static final String MULTITENANCY_FREE_PLAN = "Demo";
-    public static final String MULTITENANCY_SMALL_PLAN = "SMB";
-    public static final String MULTITENANCY_MEDIUM_PLAN = "Professional";
-    public static final String MULTITENANCY_LARGE_PLAN = "Enterprise";
-    public static final String EMAIL_CONFIG= "email";
-    public static final String MULTITENANCY_CONFIG_FOLDER = "multitenancy";
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/constants/UsageConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/constants/UsageConstants.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/constants/UsageConstants.java
deleted file mode 100644
index 607aa27..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/constants/UsageConstants.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.constants;
-
-public class UsageConstants {
-    final public static String ANY_DURATION = "anyDuration";
-
-    public static final String SYSTEM_METERING_PATH =
-            "/repository/components/org.wso2.carbon.system-metering";
-
-    public static final String CUSTOM_METERING_PATH =
-        "/repository/components/org.wso2.carbon.system-metering";
-
-    // the measurements
-    final public static String CAPACITY_USAGE = "capacity-usage";
-    
-    final public static String SERVICE_REQUEST_COUNT = "serviceRequestCount";
-    final public static String SERVICE_RESPONSE_COUNT = "serviceResponseCount";
-    final public static String SERVICE_FAULT_COUNT = "serviceFaultCount";
-    
-    public static final String BANDWIDTH_KEY_PATTERN = "%Bandwidth%";
-    public static final String REGISTRY_BANDWIDTH = "RegistryBandwidth";
-    public static final String SERVICE_BANDWIDTH = "ServiceBandwidth";
-    public static final String WEBAPP_BANDWIDTH = "WebappBandwidth";
-    public static final String IN_LABLE = "-In";
-    public static final String OUT_LABLE = "-Out";
-    public static final String REGISTRY_CONTENT_BANDWIDTH = "ContentBandwidth";
-    
-    final public static String REGISTRY_INCOMING_BW = REGISTRY_BANDWIDTH + IN_LABLE;
-    final public static String REGISTRY_OUTGOING_BW = REGISTRY_BANDWIDTH + OUT_LABLE;
-    final public static String REGISTRY_TOTAL_BW = "registry-total-bw-usage";
-    final public static String NUMBER_OF_USERS = "number-of-users";
-
-    final public static String SERVICE_INCOMING_BW = SERVICE_BANDWIDTH + IN_LABLE;
-    final public static String SERVICE_OUTGOING_BW = SERVICE_BANDWIDTH + OUT_LABLE;
-    final public static String SERVICE_TOTAL_BW = "serviceRequestTotalBw";
-    
-    final public static String WEBAPP_INCOMING_BW = WEBAPP_BANDWIDTH + IN_LABLE;
-    final public static String WEBAPP_OUTGOING_BW = WEBAPP_BANDWIDTH + OUT_LABLE;
-
-    final public static String API_CALL_COUNT = "apiCallCount";
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/exception/StratosException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/exception/StratosException.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/exception/StratosException.java
deleted file mode 100644
index 8be9f89..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/exception/StratosException.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.common.exception;
-
-/**
- * This class is defined as the general Exception implementation for Stratos. This can be used
- * within Stratos components when handling exceptions.
- */
-public class StratosException extends Exception{
-
-    public StratosException() {
-    }
-
-    public StratosException(String message) {
-        super(message);
-    }
-
-    public StratosException(String message, Throwable cause) {
-        super(message, cause);
-    }
-
-    public StratosException(Throwable cause) {
-        super(cause);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java
deleted file mode 100644
index e43c9a6..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/internal/CloudCommonServiceComponent.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.common.packages.PackageInfoHolder;
-import org.apache.stratos.common.util.CommonUtil;
-import org.apache.stratos.common.util.StratosConfiguration;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-
-/**
- * @scr.component name="apache.stratos.common" immediate="true"
- * @scr.reference name="registry.service"
- *                interface="org.wso2.carbon.registry.core.service.RegistryService"
- *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
- *                unbind="unsetRegistryService"
- * @scr.reference name="user.realmservice.default"
- *                interface="org.wso2.carbon.user.core.service.RealmService"
- *                cardinality="1..1" policy="dynamic" bind="setRealmService"
- *                unbind="unsetRealmService"
- */
-public class CloudCommonServiceComponent {
-
-    private static Log log = LogFactory.getLog(CloudCommonServiceComponent.class);
-
-    private static BundleContext bundleContext;
-    private static RealmService realmService;
-    private static RegistryService registryService;
-    private static PackageInfoHolder packageInfos;
-
-    protected void activate(ComponentContext context) {
-        try {
-            bundleContext = context.getBundleContext();
-            if (CommonUtil.getStratosConfig() == null) {
-                StratosConfiguration stratosConfig = CommonUtil.loadStratosConfiguration();
-                CommonUtil.setStratosConfig(stratosConfig);
-            }
-
-            // Loading the EULA
-            if (CommonUtil.getEula() == null) {
-                String eula = CommonUtil.loadTermsOfUsage();
-                CommonUtil.setEula(eula);
-            }
-            
-			packageInfos = new PackageInfoHolder();
-			context.getBundleContext().registerService(
-					PackageInfoHolder.class.getName(), packageInfos, null);
-
-            //Register manager configuration OSGI service
-            try {
-                StratosConfiguration stratosConfiguration = CommonUtil.loadStratosConfiguration();
-                bundleContext.registerService(StratosConfiguration.class.getName(), stratosConfiguration, null);
-                if (log.isDebugEnabled()) {
-                    log.debug("******* Cloud Common Service bundle is activated ******* ");
-                }
-            } catch (Exception ex) {
-                String msg = "An error occurred while initializing Cloud Common Service as an OSGi Service";
-                log.error(msg, ex);
-            }
-        } catch (Throwable e) {
-            log.error("Error in activating Cloud Common Service Component" + e.toString());
-        }
-    }
-
-    protected void deactivate(ComponentContext context) {
-        log.debug("******* Tenant Core bundle is deactivated ******* ");
-    }
-
-    protected void setRegistryService(RegistryService registryService) {
-        CloudCommonServiceComponent.registryService = registryService;
-    }
-
-    protected void unsetRegistryService(RegistryService registryService) {
-        setRegistryService(null);
-    }
-
-    protected void setRealmService(RealmService realmService) {
-        CloudCommonServiceComponent.realmService = realmService;
-    }
-
-    protected void unsetRealmService(RealmService realmService) {
-        setRealmService(null);
-    }
-
-    public static BundleContext getBundleContext() {
-        return bundleContext;
-    }
-
-    public static RegistryService getRegistryService() {
-        return registryService;
-    }
-
-
-    public static RealmService getRealmService() {
-        return realmService;
-    }
-
-    public static TenantManager getTenantManager() {
-        return realmService.getTenantManager();
-    }
-
-    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
-        return registryService.getGovernanceSystemRegistry(tenantId);
-    }
-
-    public static UserRegistry getConfigSystemRegistry(int tenantId) throws RegistryException {
-        return registryService.getConfigSystemRegistry(tenantId);
-    }
-
-	public static PackageInfoHolder getPackageInfos() {
-		return packageInfos;
-	}
-
-    
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java
deleted file mode 100644
index 4a9a316..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/listeners/TenantMgtListener.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.listeners;
-
-
-import org.apache.stratos.common.beans.TenantInfoBean;
-import org.apache.stratos.common.exception.StratosException;
-
-public interface TenantMgtListener {
-    public void onTenantCreate(TenantInfoBean tenantInfo) throws StratosException;
-
-    public void onTenantUpdate(TenantInfoBean tenantInfo) throws StratosException;
-
-    public void onTenantRename(int tenantId, String oldDomainName, 
-                             String newDomainName)throws StratosException;
-    
-    public void onTenantInitialActivation(int tenantId) throws StratosException;
-    
-    public void onTenantActivation(int tenantId) throws StratosException;
-    
-    public void onTenantDeactivation(int tenantId) throws StratosException;
-
-    public void onSubscriptionPlanChange(int tenentId, String oldPlan, 
-                                         String newPlan) throws StratosException;
-    
-    public int getListenerOrder();
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/packages/PackageInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/packages/PackageInfo.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/packages/PackageInfo.java
deleted file mode 100644
index f20a6cd..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/packages/PackageInfo.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.packages;
-
-/*
- * Deserialize following XML
-<packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
-    <package name="multitenancy-free">
-        <!--<subscriptionCharge>0</subscriptionCharge>--> <!-- $ per month -->
-        <users>
-            <limit>5</limit>
-            <charge>0</charge> <!-- charge per month -->
-        </users>
-        <resourceVolume>
-            <limit>10</limit> <!--mb per user -->
-        </resourceVolume>
-        <bandwidth>
-            <limit>1000</limit> <!-- mb per user -->
-            <overuseCharge>0</overuseCharge> <!-- $ per user per month -->
-        </bandwidth>
-    </package>
-    <package name="multitenancy-small">
-        ...
-    </package>
-</packages>
- */
-public class PackageInfo {
-	
-	private String name;
-	private int usersLimit;
-	private int subscriptionCharge;
-	private int chargePerUser;
-	private int resourceVolumeLimit;
-	private int bandwidthLimit;
-	private int bandwidthOveruseCharge;
-
-	
-	public String getName() {
-		return name;
-	}
-
-	public void setName(String name) {
-		this.name = name;
-	}
-
-	public int getUsersLimit() {
-		return usersLimit;
-	}
-
-	public void setUsersLimit(int usersLimit) {
-		this.usersLimit = usersLimit;
-	}
-
-	public int getSubscriptionCharge() {
-		return subscriptionCharge;
-	}
-
-	public void setSubscriptionCharge(int subscriptionCharge) {
-		this.subscriptionCharge = subscriptionCharge;
-	}
-
-	public int getChargePerUser() {
-		return chargePerUser;
-	}
-
-	public void setChargePerUser(int chargePerUser) {
-		this.chargePerUser = chargePerUser;
-	}
-
-	public int getResourceVolumeLimit() {
-		return resourceVolumeLimit;
-	}
-
-	public void setResourceVolumeLimit(int resourceVolumeLimit) {
-		this.resourceVolumeLimit = resourceVolumeLimit;
-	}
-
-	public int getBandwidthLimit() {
-		return bandwidthLimit;
-	}
-
-	public void setBandwidthLimit(int bandwidthLimit) {
-		this.bandwidthLimit = bandwidthLimit;
-	}
-
-	public int getBandwidthOveruseCharge() {
-		return bandwidthOveruseCharge;
-	}
-
-	public void setBandwidthOveruseCharge(int bandwidthOveruseCharge) {
-		this.bandwidthOveruseCharge = bandwidthOveruseCharge;
-	}
-
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java
deleted file mode 100644
index 68fc5da..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/packages/PackageInfoHolder.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.packages;
-
-import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.xpath.AXIOMXPath;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.common.constants.StratosConstants;
-import org.apache.stratos.common.exception.StratosException;
-import org.apache.stratos.common.util.CommonUtil;
-import org.jaxen.JaxenException;
-import org.wso2.carbon.utils.CarbonUtils;
-
-import javax.xml.namespace.QName;
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-public class PackageInfoHolder {
-    private static Log log = LogFactory.getLog(PackageInfoHolder.class);
-    private static final String PACKAGE_DESCRIPTION_CONFIG = "multitenancy-packages.xml";
-    private static final String PACKAGE_DESCRIPTION_CONFIG_NS =
-            "http://wso2.com/carbon/multitenancy/billing/pacakges";
-    
-    List<PackageInfo> multitenancyPackages = new ArrayList<PackageInfo>();
-
-    public PackageInfoHolder() throws StratosException {
-        multitenancyPackages = deserializePackageDescriptionConfig();
-    }
-
-    public List<PackageInfo> getMultitenancyPackages() {
-        return multitenancyPackages;
-    }
-
-    /*
-     * Deserialize following XML
-    <packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
-        <package name="multitenancy-free">
-            <!--<subscriptionCharge>0</subscriptionCharge>--> <!-- $ per month -->
-            <users>
-                <limit>5</limit>
-                <charge>0</charge> <!-- charge per month -->
-            </users>
-            <resourceVolume>
-                <limit>10</limit> <!--mb per user -->
-            </resourceVolume>
-            <bandwidth>
-                <limit>1000</limit> <!-- mb per user -->
-                <overuseCharge>0</overuseCharge> <!-- $ per user per month -->
-            </bandwidth>
-        </package>
-        <package name="multitenancy-small">
-            ...
-        </package>
-    </packages>
-     */
-    private List<PackageInfo> deserializePackageDescriptionConfig() throws StratosException {
-        String configFilePath = CarbonUtils.getCarbonConfigDirPath() + File.separator +
-                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
-                PACKAGE_DESCRIPTION_CONFIG;
-        
-        OMElement packageConfigs;
-        try {
-            packageConfigs = CommonUtil.buildOMElement(new FileInputStream(configFilePath));
-        } catch (Exception e) {
-            String msg = "Error in deserializing the packageConfigs file: " + configFilePath + ".";
-            log.error(msg, e);
-            throw new StratosException(msg, e);
-        }
-
-        @SuppressWarnings("unchecked")
-        Iterator<OMElement> packageConfigsChildsIt = packageConfigs.getChildElements();
-        while (packageConfigsChildsIt.hasNext()) {
-            OMElement packageConfigEle = packageConfigsChildsIt.next();
-            if (!new QName(PACKAGE_DESCRIPTION_CONFIG_NS, "package").equals(
-                    packageConfigEle.getQName())) {
-                continue;
-            }
-            
-            PackageInfo multitenancyPackage = new PackageInfo();
-            String packageName = packageConfigEle.getAttributeValue(new QName("name"));
-            String subscriptionCharge = getPackageConfigValue("subscriptionCharge", packageConfigEle);
-            String usersLimit = getPackageConfigValue("users.limit", packageConfigEle);
-            String usersCharge = getPackageConfigValue("users.charge", packageConfigEle);
-
-            String resourceVolumeLimit =
-                    getPackageConfigValue("resourceVolume.limit", packageConfigEle);
-            String resourceVolumeOveruseCharge =
-                    getPackageConfigValue("resourceVolume.overuseCharge", packageConfigEle);
-            String bandwidthLimit = getPackageConfigValue("bandwidth.limit", packageConfigEle);
-            String bandwidthOveruseCharge =
-                    getPackageConfigValue("bandwidth.overuseCharge", packageConfigEle);
-            int usersLimitInt = -1;
-            if (!usersLimit.equals("unlimited")) {
-                usersLimitInt = Integer.parseInt(usersLimit);
-            }
-            int resourceVolumeLimitInt = -1;
-            if (!resourceVolumeLimit.equals("unlimited")) {
-                resourceVolumeLimitInt = Integer.parseInt(resourceVolumeLimit);
-            }
-            int bandwidthLimitInt = -1;
-            if (!bandwidthLimit.equals("unlimited")) {
-                bandwidthLimitInt = Integer.parseInt(bandwidthLimit);
-            }
-
-            multitenancyPackage.setName(packageName);
-            //In the PackageInfo class subscriptionCharge, chargeperUser and bandwidthOverUsageCharge
-            //are declared as Integers. I think it is better to change them to float. If somebody
-            //enters a float value to the conf file it will cause an exception here
-            multitenancyPackage.setSubscriptionCharge(Integer.parseInt(subscriptionCharge));
-            multitenancyPackage.setUsersLimit(usersLimitInt);
-       //   multitenancyPackage.setChargePerUser(Integer.parseInt(usersCharge));
-            multitenancyPackage.setResourceVolumeLimit(resourceVolumeLimitInt);
-            multitenancyPackage.setBandwidthLimit(bandwidthLimitInt);
-          //  multitenancyPackage.setBandwidthOveruseCharge(Integer.parseInt(bandwidthOveruseCharge));
-
-            multitenancyPackages.add(multitenancyPackage);
-        }
-        return multitenancyPackages;
-    }
-
-    private String getPackageConfigValue(String key, OMElement packageNode) throws StratosException {
-        String qualifiedKey = "ns:" + key.replaceAll("\\.", "/ns:");
-        AXIOMXPath xpathExpression;
-        try {
-            xpathExpression = new AXIOMXPath(qualifiedKey);
-            xpathExpression.addNamespace("ns", PACKAGE_DESCRIPTION_CONFIG_NS);
-            List valueNodes = xpathExpression.selectNodes(packageNode);
-            if (valueNodes.isEmpty()) {
-                if (log.isDebugEnabled()) {
-                    String msg = "No results found parsing package configuration for key: " + 
-                            qualifiedKey + ".";
-                    log.debug(msg);
-                }
-                return null;
-            }
-            OMElement valueNode = (OMElement) valueNodes.get(0);
-            return valueNode.getText();
-        } catch (JaxenException e) {
-            String msg = "Error in retrieving the key: " + qualifiedKey + ".";
-            log.error(msg, e);
-            throw new StratosException(msg, e);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/services/PackageInfoService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/services/PackageInfoService.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/services/PackageInfoService.java
deleted file mode 100644
index 6ace99f..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/services/PackageInfoService.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.services;
-
-import org.apache.stratos.common.internal.CloudCommonServiceComponent;
-import org.apache.stratos.common.packages.PackageInfo;
-
-import java.util.List;
-
-
-public class PackageInfoService {
-
-	public PackageInfo[] getPackageInfos() throws Exception {
-		List<PackageInfo> list = CloudCommonServiceComponent.getPackageInfos().
-		                                                     getMultitenancyPackages();
-		PackageInfo[] packageInfos = list.toArray(new PackageInfo[list.size()]);
-		return packageInfos;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java
deleted file mode 100644
index d151df9..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/ClaimsMgtUtil.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- * http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-package org.apache.stratos.common.util;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.user.core.UserCoreConstants;
-import org.wso2.carbon.user.core.UserStoreException;
-import org.wso2.carbon.user.core.UserStoreManager;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-/*
- * This class handles the parameters that are input during the registration
- * which later are
- * stored as claims.
- * 
- * Current claims are:
- * First Name - GIVEN_NAME
- * Last Name - SURNAME
- */
-public class ClaimsMgtUtil {
-
-    private static final Log log = LogFactory.getLog(ClaimsMgtUtil.class);
-
-    /* Methods to get the first and last names from the getNames() */
-    /**
-     * gets first name
-     * 
-     * @param realmService realmService
-     * @param tenantId
-     *            tenant id
-     * @return first name
-     * @throws Exception
-     *             if error in getting the first name
-     */
-    public static String getFirstName(RealmService realmService, int tenantId)throws Exception {
-        String names[] = getNames(realmService, tenantId);
-        return names[0];
-    }
-
-    /**
-     * gets last name
-     * 
-     * @param tenant
-     *            tenant
-     * @param tenantId
-     *            tenant id
-     * @return last name
-     * @throws Exception
-     *             if error in getting the last name
-     */
-    public static String getLastName(RealmService realmService, int tenantId) throws Exception {
-        String names[] = getNames(realmService, tenantId);
-        return names[1];
-    }
-
-    /**
-     * Gets the first name of a tenant admin to address him/her in the
-     * notifications
-     * 
-     * @param tenant
-     *            tenant
-     * @param tenantId
-     *            tenant Id
-     * @return first name / calling name
-     * @throws Exception
-     *             if unable to retrieve the admin name
-     */
-    public static String[] getNames(RealmService realmService, int tenantId) throws Exception {
-        String[] names = new String[2];
-        String firstname = "", lastname = "";
-        try {
-            firstname = getFirstNamefromUserStoreManager(realmService, tenantId);
-        } catch (Exception ignore) {
-            if (log.isDebugEnabled()) {
-                // Not exceptions,due to the existence of tenants with no full name.
-                String msg = "Unable to get the firstname from the user store manager";
-                log.debug(msg, ignore);
-            }
-        }
-        if (firstname != null && !firstname.trim().equals("")) {
-            lastname = getLastNamefromUserStoreManager(realmService, tenantId);
-            if ((lastname != null) && (!lastname.trim().equals(""))) {
-                names[0] = firstname;
-                names[1] = lastname;
-            } else {
-                // no last name - fullname was considered givenname;
-                names = getNamesfromFullName(realmService, firstname);
-            }
-        } else { 
-            // Work around for old tenants - where even full name is not input.
-            if (log.isDebugEnabled()) {
-                log.debug("First name is not available");
-            }
-            try {
-                firstname = getAdminUserNameFromTenantId(realmService, tenantId);
-                names[0] = firstname;
-                names[1] = lastname;
-            } catch (Exception e) {
-                String msg = "Unable to get the admin Name from the user store manager";
-                log.error(msg, e);
-                throw new Exception(msg, e);
-            }
-        }
-        return names;
-    }
-
-    /**
-     * Method to get the name of the admin user given the tenant id
-     * 
-     * @param tenantId
-     *            tenant id
-     * @return admin user name
-     * @throws Exception
-     *             UserStoreException
-     */
-    public static String getAdminUserNameFromTenantId(RealmService realmService, int tenantId)
-                                                                                              throws Exception {
-        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
-            return realmService.getBootstrapRealmConfiguration().getAdminUserName();
-        }
-        String tenantAdminName ="";
-        try {
-            if (realmService.getTenantManager().getTenant(tenantId) != null) {
-                tenantAdminName = realmService.getTenantManager().getTenant(tenantId).getAdminName();
-            }
-        } catch (org.wso2.carbon.user.api.UserStoreException e) {
-            String msg = "Unable to retrieve the admin name for the tenant with the tenant Id: " +
-                         tenantId;
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-        return tenantAdminName;
-    }
-
-    /**
-     * Let's split the givenname into two.
-     * 
-     * @param fullName
-     *            full name of the tenant admin
-     * @return first name
-     */
-    public static String[] getNamesfromFullName(RealmService realmService, String fullName) {
-        String[] names = new String[0];
-
-        if (!fullName.trim().equals("")) {
-            names = fullName.split(" ", 2); // split by space.
-        }
-        return names; // first entry as the calling name.
-    }
-
-    /**
-     * Get the claims from the user store manager
-     * 
-     * @param tenant
-     *            tenant information
-     * @param tenantId
-     *            tenantId
-     * @param claim
-     *            claim name
-     * @return claim value
-     * @throws org.wso2.carbon.user.core.UserStoreException
-     *             exception in getting the user store manager
-     */
-    public static String getClaimfromUserStoreManager(RealmService realmService, int tenantId,
-                                                      String claim) throws UserStoreException {
-        UserStoreManager userStoreManager = null;
-        String claimValue = "";
-        try {
-            if (realmService.getTenantUserRealm(tenantId) != null) {
-                userStoreManager =
-                        (UserStoreManager) realmService.getTenantUserRealm(tenantId)
-                                .getUserStoreManager();
-            }
-
-        } catch (Exception e) {
-            String msg = "Error retrieving the user store manager for the tenant";
-            log.error(msg, e);
-            throw new UserStoreException(msg, e);
-        }
-        try {
-            if (userStoreManager != null) {
-                claimValue =
-                        userStoreManager.getUserClaimValue(
-                                getAdminUserNameFromTenantId(realmService, tenantId), claim,
-                                UserCoreConstants.DEFAULT_PROFILE);
-            }
-            return claimValue;
-        } catch (Exception e) {
-            String msg = "Unable to retrieve the claim for the given tenant";
-            log.error(msg, e);
-            throw new UserStoreException(msg, e);
-        }
-    }
-
-    /**
-     * Gets first name from the user store manager
-     * 
-     * @param tenant
-     *            tenant
-     * @param tenantId
-     *            tenant id
-     * @return first name
-     * @throws UserStoreException
-     *             , if error in getting the claim GIVEN_NAME
-     */
-    public static String getFirstNamefromUserStoreManager(RealmService realmService,
-                                                          int tenantId) throws UserStoreException {
-        try {
-            return getClaimfromUserStoreManager(realmService, tenantId,
-                                                UserCoreConstants.ClaimTypeURIs.GIVEN_NAME);
-        } catch (Exception e) {
-            String msg = "First Name not found for the tenant";
-            log.debug(msg, e);
-            return ""; // returns empty string
-        }
-    }
-
-    /**
-     * Gets last name from the user store manager
-     * 
-     * @param tenant
-     *            tenant
-     * @param tenantId
-     *            tenant id
-     * @return last name
-     * @throws UserStoreException
-     *             , if error in getting the claim SURNAME
-     */
-    public static String getLastNamefromUserStoreManager(RealmService realmService,
-                                                         int tenantId) throws UserStoreException {
-        String lastname = "";
-        try {
-            lastname = getClaimfromUserStoreManager(realmService, tenantId,
-                                                    UserCoreConstants.ClaimTypeURIs.SURNAME);
-        } catch (Exception e) {
-            String msg = "Last Name not found for the tenant";
-            log.debug(msg, e);
-        }
-        return lastname; // returns empty string, if couldn't get last name from
-                         // userStore manager
-    }
-
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java b/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java
deleted file mode 100644
index 4108973..0000000
--- a/components/org.apache.stratos.common/2.1.2/src/main/java/org/apache/stratos/common/util/CloudServicesUtil.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.common.util;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.common.config.CloudServiceConfig;
-import org.apache.stratos.common.config.CloudServicesDescConfig;
-import org.apache.stratos.common.config.PermissionConfig;
-import org.apache.stratos.common.constants.StratosConstants;
-import org.apache.stratos.common.internal.CloudCommonServiceComponent;
-import org.wso2.carbon.registry.core.Collection;
-import org.wso2.carbon.registry.core.RegistryConstants;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.user.core.UserStoreException;
-import org.wso2.carbon.user.mgt.UserMgtConstants;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-public class CloudServicesUtil {
-
-    private static final Log log = LogFactory.getLog(CloudServicesUtil.class);
-    // TODO protect using Java security
-
-    public static void activateAllServices(CloudServicesDescConfig cloudServicesDesc, int tenantId) throws Exception {
-
-        java.util.Collection<CloudServiceConfig> cloudServiceConfigList =
-                                                                          cloudServicesDesc.getCloudServiceConfigs().
-                                                                                            values();
-        if (cloudServiceConfigList != null) {
-            for (CloudServiceConfig cloudServiceConfig : cloudServiceConfigList) {
-                if (cloudServiceConfig.isDefaultActive()) {
-                    String cloudServiceName = cloudServiceConfig.getName();
-                    try {
-                        if (!CloudServicesUtil.isCloudServiceActive(cloudServiceName, tenantId)) {
-                            CloudServicesUtil.setCloudServiceActive(true,
-                                                                    cloudServiceName,
-                                                                    tenantId,
-                                                                    cloudServicesDesc.getCloudServiceConfigs().
-                                                                                      get(cloudServiceName));
-                        }
-                    } catch (Exception e) {
-                        String msg = "Error in activating the cloud service at the tenant" +
-                                     "creation. tenant id: " + tenantId + ", service name: " +
-                                     cloudServiceName;
-                        log.error(msg, e);
-                        throw new UserStoreException(msg, e);
-                    }
-                }
-            }
-        }     
-    }
-
-    public static void activateOriginalAndCompulsoryServices(CloudServicesDescConfig cloudServicesDesc,
-                                                             String originalService,
-                                                             int tenantId) throws Exception {
-
-        Map<String, CloudServiceConfig> cloudServiceConfigs =
-                                                              cloudServicesDesc.getCloudServiceConfigs();
-        if (CloudServicesUtil.isServiceNameValid(cloudServicesDesc, originalService)) {
-            if (!CloudServicesUtil.isCloudServiceActive(originalService, tenantId)) {
-                CloudServicesUtil.setCloudServiceActive(true, originalService, tenantId,
-                                                        cloudServiceConfigs.get(originalService));
-                log.info("Successfully activated the " + originalService + " for the tenant " +
-                         tenantId);
-            }
-            // register the compulsory services
-            if (!CloudServicesUtil.isCloudServiceActive(StratosConstants.CLOUD_IDENTITY_SERVICE,
-                                                        tenantId)) {
-                CloudServicesUtil.setCloudServiceActive(true,
-                                                        StratosConstants.CLOUD_IDENTITY_SERVICE,
-                                                        tenantId,
-                                                        cloudServiceConfigs.get(StratosConstants.CLOUD_IDENTITY_SERVICE));
-            }
-            if (!CloudServicesUtil.isCloudServiceActive(StratosConstants.CLOUD_GOVERNANCE_SERVICE,
-                                                        tenantId)) {
-                CloudServicesUtil.setCloudServiceActive(true,
-                                                        StratosConstants.CLOUD_GOVERNANCE_SERVICE,
-                                                        tenantId,
-                                                        cloudServiceConfigs.get(StratosConstants.CLOUD_GOVERNANCE_SERVICE));
-            }
-        } else {
-            log.warn("Unable to activate the " + originalService + " for the tenant " + tenantId);
-        }
-
-    }
-
-    public static void setCloudServiceActive(boolean active,
-                                             String cloudServiceName,
-                                             int tenantId, CloudServiceConfig cloudServiceConfig)
-                                                                                                 throws Exception {
-        if (cloudServiceConfig.getLabel() == null) {
-            // for the non-labled services, we are not setting/unsetting the
-            // service active
-            return;
-        }
-
-        UserRegistry govRegistry =
-                CloudCommonServiceComponent.getGovernanceSystemRegistry(
-                        MultitenantConstants.SUPER_TENANT_ID);
-        UserRegistry configRegistry = CloudCommonServiceComponent.getConfigSystemRegistry(tenantId);
-        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
-                                      RegistryConstants.PATH_SEPARATOR + tenantId +
-                                      RegistryConstants.PATH_SEPARATOR + cloudServiceName;
-        
-        Resource cloudServiceInfoResource;
-        if (govRegistry.resourceExists(cloudServiceInfoPath)) {
-            cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
-        } else {
-            cloudServiceInfoResource = govRegistry.newCollection();
-        }
-        cloudServiceInfoResource.setProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY,
-                                             active ? "true" : "false");
-        govRegistry.put(cloudServiceInfoPath, cloudServiceInfoResource);
-
-        // then we will copy the permissions
-        List<PermissionConfig> permissionConfigs = cloudServiceConfig.getPermissionConfigs();
-        for (PermissionConfig permissionConfig : permissionConfigs) {
-            String path = permissionConfig.getPath();
-            String name = permissionConfig.getName();
-            if (active) {
-                if (!configRegistry.resourceExists(path)) {
-                    Collection collection = configRegistry.newCollection();
-                    collection.setProperty(UserMgtConstants.DISPLAY_NAME, name);
-                    configRegistry.put(path, collection);
-                }
-            } else {
-                if (configRegistry.resourceExists(path)) {
-                    configRegistry.delete(path);
-                }
-            }
-        }
-    }
-
-    public static boolean isCloudServiceActive(String cloudServiceName,
-                                               int tenantId) throws Exception {
-        UserRegistry govRegistry = CloudCommonServiceComponent.getGovernanceSystemRegistry(
-                                                                                           MultitenantConstants.SUPER_TENANT_ID);
-        return isCloudServiceActive(cloudServiceName, tenantId, govRegistry);
-    }
-
-    public static boolean isCloudServiceActive(String cloudServiceName,
-                                               int tenantId, UserRegistry govRegistry)
-                                                                                      throws Exception {
-        // The cloud manager is always active
-        if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
-            return true;
-        }
-
-        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
-                                      RegistryConstants.PATH_SEPARATOR + tenantId +
-                                      RegistryConstants.PATH_SEPARATOR + cloudServiceName;
-        Resource cloudServiceInfoResource;
-        if (govRegistry.resourceExists(cloudServiceInfoPath)) {
-            cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
-            String isActiveStr =
-                                 cloudServiceInfoResource.getProperty(
-                                                         StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
-            return "true".equals(isActiveStr);
-        }
-        return false;
-    }
-
-    public static boolean isServiceNameValid(CloudServicesDescConfig cloudServicesDesc,
-                                               String cloudServiceName) {
-        if(cloudServiceName == null) {
-            return false;
-        }
-        java.util.Collection<CloudServiceConfig> cloudServiceConfigList =
-                cloudServicesDesc.getCloudServiceConfigs().values();
-        if (cloudServiceName.equals(StratosConstants.CLOUD_MANAGER_SERVICE)) {
-            return false;
-        }
-        for (CloudServiceConfig cloudServiceConfig : cloudServiceConfigList) {
-            if (cloudServiceConfig.getName().equals(cloudServiceName)) {
-                return true;
-            }
-        }
-        return false;
-    }
-}


[26/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
new file mode 100644
index 0000000..307ffe3
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
@@ -0,0 +1,853 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.utils;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.namespace.QName;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.dao.CartridgeSubscription;
+import org.apache.stratos.adc.mgt.dao.DataCartridge;
+import org.apache.stratos.adc.mgt.dao.PortMapping;
+import org.apache.stratos.adc.mgt.dao.Repository;
+import org.apache.stratos.adc.mgt.dao.RepositoryCredentials;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.securevault.SecretResolver;
+import org.wso2.securevault.SecretResolverFactory;
+
+/**
+ * This class is responsible for handling persistence
+ * 
+ */
+public class PersistenceManager {
+
+	private static final Log log = LogFactory.getLog(PersistenceManager.class);
+
+	public static void persistCartridgeInstanceInfo(String instanceIp, String clusterDomain, String clusterSubDomain,
+			String cartridgeType, String state) throws Exception {
+
+		Connection con = null;
+		PreparedStatement statement = null;
+		PreparedStatement updateStatement = null;
+		ResultSet resultSet = null;
+
+		boolean isUpdate = false;
+		int instanceId = 0;
+		try {
+			con = StratosDBUtils.getConnection();
+
+			// First check whether Ip exists..
+			String sql = "SELECT ID FROM CARTRIDGE_INSTANCE where INSTANCE_IP=? AND CARTRIDGE_TYPE=? "
+					+ " AND CLUSTER_DOMAIN=? AND CLUSTER_SUBDOMAIN=?";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, instanceIp);
+			statement.setString(2, cartridgeType);
+			statement.setString(3, clusterDomain);
+			statement.setString(4, clusterSubDomain);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				isUpdate = true;
+				instanceId = resultSet.getInt("ID");
+			}
+
+			String persistQuery = null;
+			if (isUpdate) {
+				persistQuery = "UPDATE CARTRIDGE_INSTANCE SET STATE=?" + " WHERE ID=?";
+				updateStatement = con.prepareStatement(persistQuery);
+				updateStatement.setString(1, state);
+				updateStatement.setInt(2, instanceId);
+			} else {
+				persistQuery = "INSERT INTO CARTRIDGE_INSTANCE (INSTANCE_IP, CARTRIDGE_TYPE, STATE, CLUSTER_DOMAIN, CLUSTER_SUBDOMAIN)"
+						+ " VALUES (?, ?, ?, ?, ?)";
+				updateStatement = con.prepareStatement(persistQuery);
+				updateStatement.setString(1, instanceIp);
+				updateStatement.setString(2, cartridgeType);
+				updateStatement.setString(3, state);
+				updateStatement.setString(4, clusterDomain);
+				updateStatement.setString(5, clusterSubDomain);
+			}
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + persistQuery);
+			}
+			updateStatement.executeUpdate();
+			con.commit();
+		} catch (Exception e) {
+			if (con != null) {
+				try {
+					con.rollback();
+				} catch (SQLException e1) {
+					log.error("Failed to rollback", e);
+				}
+			}
+			;
+			log.error("Error", e);
+			throw e;
+		} finally {
+			StratosDBUtils.closeResultSet(resultSet);
+			StratosDBUtils.closeAllConnections(con, statement, updateStatement);
+		}
+	}
+
+	public static boolean isAlreadySubscribed(String cartridgeType, int tenantId) throws Exception {
+
+		Connection con = null;
+		PreparedStatement preparedStatement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT C.ALIAS FROM CARTRIDGE_SUBSCRIPTION C WHERE TENANT_ID = ? AND C.CARTRIDGE = ? AND C.STATE != 'UNSUBSCRIBED'";
+			preparedStatement = con.prepareStatement(sql);
+			preparedStatement.setInt(1, tenantId);
+			preparedStatement.setString(2, cartridgeType);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = preparedStatement.executeQuery();
+			if (resultSet.next()) {
+				String alias = resultSet.getString("ALIAS");
+				if (log.isDebugEnabled()) {
+					log.debug("Already subscribed to " + cartridgeType + " with alias " + alias);
+				}
+				return true;
+			} else {
+				return false;
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, preparedStatement, resultSet);
+		}
+	}
+
+	public static List<CartridgeSubscription> retrieveSubscribedCartridges(int tenantId) throws Exception {
+
+		List<CartridgeSubscription> subscribedCartridgeList = new ArrayList<CartridgeSubscription>();
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT C.CARTRIDGE, C.ALIAS, C.CLUSTER_DOMAIN, C.CLUSTER_SUBDOMAIN, C.POLICY, C.STATE, "
+					+ "C.TENANT_ID, C.SUBSCRIPTION_ID, C.DATA_CARTRIDGE_ID, D.TYPE, D.USER_NAME, D.PASSWORD, "
+					+ "C.PROVIDER, C.HOSTNAME, C.MAPPED_DOMAIN, R.REPO_NAME FROM CARTRIDGE_SUBSCRIPTION C "
+					+ "LEFT JOIN DATA_CARTRIDGE D on D.DATA_CART_ID=C.DATA_CARTRIDGE_ID  "
+					+ "LEFT JOIN REPOSITORY R ON C.REPO_ID=R.REPO_ID WHERE TENANT_ID=? AND C.STATE != 'UNSUBSCRIBED' "
+					+ "ORDER BY C.SUBSCRIPTION_ID";
+			statement = con.prepareStatement(sql);
+			statement.setInt(1, tenantId);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			while (resultSet.next()) {
+				CartridgeSubscription cartridge = new CartridgeSubscription();
+				cartridge.setAlias(resultSet.getString("ALIAS"));
+				cartridge.setCartridge(resultSet.getString("CARTRIDGE"));
+				cartridge.setState(resultSet.getString("STATE"));
+				cartridge.setClusterDomain(resultSet.getString("CLUSTER_DOMAIN"));
+				cartridge.setClusterSubdomain(resultSet.getString("CLUSTER_SUBDOMAIN"));
+				cartridge.setProvider(resultSet.getString("PROVIDER"));
+				cartridge.setPolicy(resultSet.getString("POLICY"));
+				cartridge.setMappedDomain(resultSet.getString("MAPPED_DOMAIN"));
+				Repository repo = new Repository();
+				repo.setRepoName(resultSet.getString("REPO_NAME"));
+				cartridge.setRepository(repo);
+				cartridge.setHostName(resultSet.getString("HOSTNAME"));
+				int dataCartridgeId = resultSet.getInt("DATA_CARTRIDGE_ID");
+				if (dataCartridgeId != 0) {
+					DataCartridge dataCartridge = new DataCartridge();
+					dataCartridge.setDataCartridgeType(resultSet.getString("TYPE"));
+					dataCartridge.setPassword(resultSet.getString("PASSWORD"));
+					dataCartridge.setUserName(resultSet.getString("USER_NAME"));
+					cartridge.setDataCartridge(dataCartridge);
+				}
+				subscribedCartridgeList.add(cartridge);
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return subscribedCartridgeList;
+	}
+
+	public static String getRepoURL(int tenantId, String cartridge) throws Exception {
+
+		String repoUrl = null;
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT REPO_NAME FROM REPOSITORY R, CARTRIDGE_SUBSCRIPTION C "
+					+ "WHERE C.REPO_ID=R.REPO_ID AND C.TENANT_ID=? AND C.CARTRIDGE=? "
+					+ "AND C.STATE != 'UNSUBSCRIBED' ";
+			statement = con.prepareStatement(sql);
+			statement.setInt(1, tenantId);
+			statement.setString(2, cartridge);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				repoUrl = resultSet.getString("REPO_NAME");
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return repoUrl;
+	}
+
+	public static RepositoryCredentials getRepoCredentials(int tenantId, String cartridge, String alias)
+			throws Exception {
+
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+		RepositoryCredentials repoCredentials = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT REPO_NAME,REPO_USER_NAME,REPO_USER_PASSWORD FROM REPOSITORY R, CARTRIDGE_SUBSCRIPTION C "
+					+ "WHERE C.REPO_ID=R.REPO_ID AND C.TENANT_ID=? AND C.CARTRIDGE=? AND C.STATE != 'UNSUBSCRIBED' ";
+			if (alias != null) {
+				sql = sql + " AND C.ALIAS=?";
+			}
+			statement = con.prepareStatement(sql);
+			statement.setInt(1, tenantId);
+			statement.setString(2, cartridge);
+			if (alias != null) {
+				statement.setString(3, alias);
+			}
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			while (resultSet.next()) {
+				repoCredentials = new RepositoryCredentials();
+				repoCredentials.setUrl(resultSet.getString("REPO_NAME"));
+				repoCredentials.setUserName(resultSet.getString("REPO_USER_NAME"));
+				repoCredentials.setPassword(decryptPassword(resultSet.getString("REPO_USER_PASSWORD")));
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return repoCredentials;
+	}
+
+	public static boolean isAliasAlreadyTaken(String alias, String cartridgeType) throws Exception {
+		boolean aliasAlreadyTaken = false;
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT SUBSCRIPTION_ID FROM CARTRIDGE_SUBSCRIPTION where ALIAS=? AND CARTRIDGE=? AND STATE != 'UNSUBSCRIBED'";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, alias);
+			statement.setString(2, cartridgeType);
+			statement.setMaxRows(1);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				log.info("Already taken..");
+				aliasAlreadyTaken = true;
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return aliasAlreadyTaken;
+	}
+
+	public static int persistSubscription(CartridgeSubscription cartridgeSubscription) throws Exception {
+
+		int cartridgeSubscriptionId = 0;
+		int repoId = 0;
+		int dataCartridgeId = 0;
+		ResultSet res = null;
+		PreparedStatement insertSubscriptionStmt = null;
+		PreparedStatement insertRepoStmt = null;
+		PreparedStatement insertDataCartStmt = null;
+
+		Connection con = null;
+
+		// persist cartridge_subscription
+		try {
+			con = StratosDBUtils.getConnection();
+			// persist repo
+			if (cartridgeSubscription.getRepository() != null) {
+				String encryptedRepoUserPassword = encryptPassword(cartridgeSubscription.getRepository()
+						.getRepoUserPassword());
+				String insertRepo = "INSERT INTO REPOSITORY (REPO_NAME,STATE,REPO_USER_NAME,REPO_USER_PASSWORD)"
+						+ " VALUES (?,?,?,?)";
+
+				insertRepoStmt = con.prepareStatement(insertRepo, Statement.RETURN_GENERATED_KEYS);
+				insertRepoStmt.setString(1, cartridgeSubscription.getRepository().getRepoName());
+				insertRepoStmt.setString(2, "ACTIVE");
+				insertRepoStmt.setString(3, cartridgeSubscription.getRepository().getRepoUserName());
+				insertRepoStmt.setString(4, encryptedRepoUserPassword);
+				if (log.isDebugEnabled()) {
+					log.debug("Executing insert: " + insertRepo);
+				}
+				insertRepoStmt.executeUpdate();
+				res = insertRepoStmt.getGeneratedKeys();
+				if (res.next()) {
+					repoId = res.getInt(1);
+				}
+				StratosDBUtils.closeResultSet(res);
+			}
+
+			// persist data cartridge
+			if (cartridgeSubscription.getDataCartridge() != null) {
+				String insertDataCartridge = "INSERT INTO DATA_CARTRIDGE (TYPE,USER_NAME,PASSWORD,STATE)"
+						+ " VALUES (?,?,?,?)";
+				insertDataCartStmt = con.prepareStatement(insertDataCartridge, Statement.RETURN_GENERATED_KEYS);
+				insertDataCartStmt.setString(1, cartridgeSubscription.getDataCartridge().getDataCartridgeType());
+				insertDataCartStmt.setString(2, cartridgeSubscription.getDataCartridge().getUserName());
+				insertDataCartStmt.setString(3, cartridgeSubscription.getDataCartridge().getPassword());
+				insertDataCartStmt.setString(4, "ACTIVE");
+				if (log.isDebugEnabled()) {
+					log.debug("Executing insert: " + insertDataCartridge);
+				}
+				insertDataCartStmt.executeUpdate();
+				res = insertDataCartStmt.getGeneratedKeys();
+				if (res.next()) {
+					dataCartridgeId = res.getInt(1);
+				}
+				StratosDBUtils.closeResultSet(res);
+			}
+
+			String insertSubscription = "INSERT INTO CARTRIDGE_SUBSCRIPTION (TENANT_ID, CARTRIDGE, PROVIDER,"
+					+ "HOSTNAME, POLICY, CLUSTER_DOMAIN, " + "CLUSTER_SUBDOMAIN, MGT_DOMAIN, MGT_SUBDOMAIN, STATE, "
+					+ "ALIAS, TENANT_DOMAIN, BASE_DIR, REPO_ID, DATA_CARTRIDGE_ID)"
+					+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+
+			insertSubscriptionStmt = con.prepareStatement(insertSubscription, Statement.RETURN_GENERATED_KEYS);
+			insertSubscriptionStmt.setInt(1, cartridgeSubscription.getTenantId());
+			insertSubscriptionStmt.setString(2, cartridgeSubscription.getCartridge());
+			insertSubscriptionStmt.setString(3, cartridgeSubscription.getProvider());
+			insertSubscriptionStmt.setString(4, cartridgeSubscription.getHostName());
+			insertSubscriptionStmt.setString(5, cartridgeSubscription.getPolicy());
+			insertSubscriptionStmt.setString(6, cartridgeSubscription.getClusterDomain());
+			insertSubscriptionStmt.setString(7, cartridgeSubscription.getClusterSubdomain());
+			insertSubscriptionStmt.setString(8, cartridgeSubscription.getMgtClusterDomain());
+			insertSubscriptionStmt.setString(9, cartridgeSubscription.getMgtClusterSubDomain());
+			insertSubscriptionStmt.setString(10, cartridgeSubscription.getState());
+			insertSubscriptionStmt.setString(11, cartridgeSubscription.getAlias());
+			insertSubscriptionStmt.setString(12, cartridgeSubscription.getTenantDomain());
+			insertSubscriptionStmt.setString(13, cartridgeSubscription.getBaseDirectory());
+			insertSubscriptionStmt.setInt(14, repoId);
+			insertSubscriptionStmt.setInt(15, dataCartridgeId);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing insert: " + insertSubscription);
+			}
+			insertSubscriptionStmt.executeUpdate();
+			res = insertSubscriptionStmt.getGeneratedKeys();
+			if (res.next()) {
+				cartridgeSubscriptionId = res.getInt(1);
+			}
+
+			List<PortMapping> portMapping = cartridgeSubscription.getPortMappings();
+			// persist port map
+			if (portMapping != null && !portMapping.isEmpty()) {
+				for (PortMapping portMap : portMapping) {
+					String insertPortMapping = "INSERT INTO PORT_MAPPING (SUBSCRIPTION_ID, TYPE, PRIMARY_PORT, PROXY_PORT, STATE)"
+							+ " VALUES (?,?,?,?,?)";
+
+					PreparedStatement insertPortsStmt = con.prepareStatement(insertPortMapping);
+					insertPortsStmt.setInt(1, cartridgeSubscriptionId);
+					insertPortsStmt.setString(2, portMap.getType());
+					insertPortsStmt.setString(3, portMap.getPrimaryPort());
+					insertPortsStmt.setString(4, portMap.getProxyPort());
+					insertPortsStmt.setString(5, "ACTIVE");
+					if (log.isDebugEnabled()) {
+						log.debug("Executing insert: " + insertPortMapping);
+					}
+					insertPortsStmt.executeUpdate();
+					StratosDBUtils.closeStatement(insertPortsStmt);
+				}
+			}
+			con.commit(); // Commit manually
+		} catch (Exception e) {
+			if (con != null) {
+				try {
+					con.rollback();
+				} catch (SQLException e1) {
+					log.error("Failed to rollback", e);
+				}
+			}
+			;
+			log.error(e.getMessage());
+			String msg = "Exception : " + e.getMessage();
+			log.error(msg, e);
+			throw new Exception("Subscription failed!", e);
+		} finally {
+			StratosDBUtils.closeResultSet(res);
+			StratosDBUtils.closeAllConnections(con, insertRepoStmt, insertDataCartStmt, insertSubscriptionStmt);
+		}
+		return cartridgeSubscriptionId;
+	}
+
+	public static String getHostNameForCartridgeName(int tenantId, String alias) throws Exception {
+
+		String hostName = null;
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT HOSTNAME FROM CARTRIDGE_SUBSCRIPTION where TENANT_ID=?"
+					+ " AND ALIAS=? AND STATE != 'UNSUBSCRIBED'";
+			statement = con.prepareStatement(sql);
+			statement.setInt(1, tenantId);
+			statement.setString(2, alias);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				hostName = resultSet.getString("HOSTNAME");
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return hostName;
+	}
+
+	public static CartridgeSubscription getSubscription(String tenantDomain, String alias) throws Exception {
+
+		CartridgeSubscription cartridgeSubscription = null;
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT * FROM CARTRIDGE_SUBSCRIPTION C left join REPOSITORY R on "
+					+ "C.REPO_ID=R.REPO_ID left join DATA_CARTRIDGE D on "
+					+ "D.DATA_CART_ID=C.DATA_CARTRIDGE_ID WHERE ALIAS=? AND TENANT_DOMAIN=? AND C.STATE != 'UNSUBSCRIBED'";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, alias);
+			statement.setString(2, tenantDomain);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				cartridgeSubscription = new CartridgeSubscription();
+				populateSubscription(cartridgeSubscription, resultSet);
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+
+		return cartridgeSubscription;
+	}
+
+	private static void populateSubscription(CartridgeSubscription cartridgeSubscription, ResultSet resultSet)
+			throws Exception {
+		String repoName = resultSet.getString("REPO_NAME");
+		if (repoName != null) {
+			Repository repo = new Repository();
+			repo.setRepoName(repoName);
+			cartridgeSubscription.setRepository(repo);
+		}
+
+		int dataCartridgeId = resultSet.getInt("DATA_CARTRIDGE_ID");
+		if (dataCartridgeId != 0) {
+			DataCartridge dataCartridge = new DataCartridge();
+			dataCartridge.setDataCartridgeType(resultSet.getString("TYPE"));
+			dataCartridge.setPassword(resultSet.getString("PASSWORD"));
+			dataCartridge.setUserName(resultSet.getString("USER_NAME"));
+			cartridgeSubscription.setDataCartridge(dataCartridge);
+		}
+		cartridgeSubscription.setPortMappings(getPortMappings(resultSet.getInt("SUBSCRIPTION_ID")));
+		cartridgeSubscription.setTenantId(resultSet.getInt("TENANT_ID"));
+		cartridgeSubscription.setState(resultSet.getString("STATE"));
+		cartridgeSubscription.setPolicy(resultSet.getString("POLICY"));
+		cartridgeSubscription.setCartridge(resultSet.getString("CARTRIDGE"));
+		cartridgeSubscription.setAlias(resultSet.getString("ALIAS"));
+		cartridgeSubscription.setClusterDomain(resultSet.getString("CLUSTER_DOMAIN"));
+		cartridgeSubscription.setClusterSubdomain(resultSet.getString("CLUSTER_SUBDOMAIN"));
+		cartridgeSubscription.setMgtClusterDomain(resultSet.getString("MGT_DOMAIN"));
+		cartridgeSubscription.setMgtClusterSubDomain(resultSet.getString("MGT_SUBDOMAIN"));
+		cartridgeSubscription.setProvider(resultSet.getString("PROVIDER"));
+		cartridgeSubscription.setHostName(resultSet.getString("HOSTNAME"));
+		cartridgeSubscription.setTenantDomain(resultSet.getString("TENANT_DOMAIN"));
+		cartridgeSubscription.setBaseDirectory(resultSet.getString("BASE_DIR"));
+		cartridgeSubscription.setSubscriptionId(resultSet.getInt("SUBSCRIPTION_ID"));
+		cartridgeSubscription.setMappedDomain(resultSet.getString("MAPPED_DOMAIN"));
+	}
+
+	private static List<PortMapping> getPortMappings(int subscriptionId) throws Exception {
+
+		List<PortMapping> portMappingList = new ArrayList<PortMapping>();
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT * FROM PORT_MAPPING WHERE SUBSCRIPTION_ID = ?";
+			statement = con.prepareStatement(sql);
+			statement.setInt(1, subscriptionId);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			while (resultSet.next()) {
+				PortMapping portMapping = new PortMapping();
+				portMapping.setPrimaryPort(resultSet.getString("PRIMARY_PORT"));
+				portMapping.setProxyPort(resultSet.getString("PROXY_PORT"));
+				portMapping.setType(resultSet.getString("TYPE"));
+				portMappingList.add(portMapping);
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return portMappingList;
+	}
+
+	public static void updateDomainMapping(int tenantId, String cartridgeAlias, String domain) throws Exception {
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "UPDATE CARTRIDGE_SUBSCRIPTION SET MAPPED_DOMAIN = ? WHERE TENANT_ID = ? AND ALIAS = ?";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, domain);
+			statement.setInt(2, tenantId);
+			statement.setString(3, cartridgeAlias);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing update: " + sql);
+			}
+			statement.executeUpdate();
+			con.commit();
+		} catch (Exception s) {
+			if (con != null) {
+				try {
+					con.rollback();
+				} catch (SQLException e) {
+					log.error("Failed to rollback", e);
+				}
+			}
+			String msg = "Error: " + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+	}
+
+	public static List<CartridgeSubscription> getSubscription(String repositoryURL) throws Exception {
+
+		List<CartridgeSubscription> subscriptionList = new ArrayList<CartridgeSubscription>();
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT * from CARTRIDGE_SUBSCRIPTION C, REPOSITORY R "
+					+ "where R.REPO_NAME LIKE ? AND C.REPO_ID = R.REPO_ID AND C.STATE != 'UNSUBSCRIBED'";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, repositoryURL + "%");
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			while (resultSet.next()) {
+				CartridgeSubscription cartridgeSubscription = new CartridgeSubscription();
+				populateSubscription(cartridgeSubscription, resultSet);
+				subscriptionList.add(cartridgeSubscription);
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return subscriptionList;
+	}
+
+	public static void updateSubscriptionState(int subscriptionId, String state) throws Exception {
+
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "UPDATE CARTRIDGE_SUBSCRIPTION SET STATE=? WHERE SUBSCRIPTION_ID=?";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, state);
+			statement.setInt(2, subscriptionId);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing update: " + sql);
+			}
+			statement.executeUpdate();
+			con.commit();
+		} catch (Exception s) {
+			if (con != null) {
+				try {
+					con.rollback();
+				} catch (SQLException e) {
+					log.error("Failed to rollback", e);
+				}
+			}
+			;
+			String msg = "Error: " + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+	}
+
+	public static Map<String, String> getCartridgeInstanceInfo(String[] ips, String clusterDomain, String clusterSubdomain)
+            throws Exception {
+		Map<String, String> instanceIpToStateMap = new HashMap<String, String>();
+		
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+		
+		try {
+			con = StratosDBUtils.getConnection();
+			StringBuilder sqlBuilder = new StringBuilder(
+					"SELECT INSTANCE_IP, STATE FROM CARTRIDGE_INSTANCE WHERE INSTANCE_IP IN (");
+			for (int i = 0; i < ips.length; i++) {
+				if (i > 0) {
+					sqlBuilder.append(", ");
+				}
+				sqlBuilder.append("?");
+			}
+			sqlBuilder.append(") AND CLUSTER_DOMAIN=? AND CLUSTER_SUBDOMAIN=?");
+			String sql = sqlBuilder.toString();
+			
+			statement = con.prepareStatement(sql);
+			int i = 1;
+			for (int j = 0; j < ips.length; j++, i++) {
+				String ip = ips[j];
+				statement.setString(i, ip);
+			}
+			statement.setString(i++, clusterDomain);
+			statement.setString(i, clusterSubdomain);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			while (resultSet.next()) {
+				instanceIpToStateMap.put(resultSet.getString("INSTANCE_IP"), resultSet.getString("STATE"));
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw new Exception("Ann error occurred while listing cartridge information.");
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return instanceIpToStateMap;
+	}
+
+	public static String getSecurityKey() {
+		String securityKey = CartridgeConstants.DEFAULT_SECURITY_KEY;
+		OMElement documentElement = null;
+		File xmlFile = new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "conf"
+				+ File.separator + CartridgeConstants.SECURITY_KEY_FILE);
+
+		if (xmlFile.exists()) {
+			try {
+				documentElement = new StAXOMBuilder(xmlFile.getPath()).getDocumentElement();
+			} catch (Exception ex) {
+				String msg = "Error occurred when parsing the " + xmlFile.getPath() + ".";
+				log.error(msg, ex);
+				ex.printStackTrace();
+			}
+			if (documentElement != null) {
+				Iterator<?> it = documentElement.getChildrenWithName(new QName(CartridgeConstants.SECURITY_KEY));
+				if (it.hasNext()) {
+					OMElement securityKeyElement = (OMElement) it.next();
+					SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
+					String alias = securityKeyElement.getAttributeValue(new QName(CartridgeConstants.ALIAS_NAMESPACE,
+							CartridgeConstants.ALIAS_LOCALPART, CartridgeConstants.ALIAS_PREFIX));
+
+					if (secretResolver != null && secretResolver.isInitialized()
+							&& secretResolver.isTokenProtected(alias)) {
+						securityKey = "";
+						securityKey = secretResolver.resolve(alias);
+						// TODO : a proper testing on the secure vault protected
+						// user defined encryption key
+					}
+				}
+			}
+		} else {
+			System.out.println("No such file ezoxists");
+		}
+		return securityKey;
+	}
+
+	public static void updateInstanceState(String state, String[] ips, String clusterDomain, String clusterSubDomain, String cartridgeType)
+			throws Exception {
+
+		Connection con = null;
+		PreparedStatement statement = null;
+
+		if (ips != null && ips.length > 0) {
+			try {
+				con = StratosDBUtils.getConnection();
+				StringBuilder sqlBuilder = new StringBuilder(
+						"UPDATE CARTRIDGE_INSTANCE SET STATE=? WHERE INSTANCE_IP IN (");
+				for (int i = 0; i < ips.length; i++) {
+					if (i > 0) {
+						sqlBuilder.append(", ");
+					}
+					sqlBuilder.append("?");
+				}
+				sqlBuilder.append(") AND CLUSTER_DOMAIN=? AND CLUSTER_SUBDOMAIN=? AND CARTRIDGE_TYPE=?");
+				String sql = sqlBuilder.toString();
+				statement = con.prepareStatement(sql);
+				statement.setString(1, state);
+				int i = 2;
+				for (int j = 0; j < ips.length; j++, i++) {
+					String ip = ips[j];
+					statement.setString(i, ip);
+				}
+				statement.setString(i++, clusterDomain);
+				statement.setString(i++, clusterSubDomain);
+				statement.setString(i, cartridgeType);
+				if (log.isDebugEnabled()) {
+					log.debug("Executing query: " + sql);
+				}
+				statement.executeUpdate();
+				con.commit();
+			} catch (Exception s) {
+				if (con != null) {
+					try {
+						con.rollback();
+					} catch (SQLException e) {
+						log.error("Failed to rollback", e);
+					}
+				}
+				String msg = "Error: " + s.getMessage();
+				log.error(msg, s);
+				throw s;
+			} finally {
+				StratosDBUtils.closeAllConnections(con, statement);
+			}
+		}
+
+	}
+
+	private static String encryptPassword(String repoUserPassword) {
+		String encryptPassword = "";
+		String secret = getSecurityKey(); // secret key length must be 16
+		SecretKey key;
+		Cipher cipher;
+		Base64 coder;
+		key = new SecretKeySpec(secret.getBytes(), "AES");
+		try {
+			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
+			coder = new Base64();
+			cipher.init(Cipher.ENCRYPT_MODE, key);
+			byte[] cipherText = cipher.doFinal(repoUserPassword.getBytes());
+			encryptPassword = new String(coder.encode(cipherText));
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return encryptPassword;
+	}
+
+	private static String decryptPassword(String repoUserPassword) {
+		String decryptPassword = "";
+		String secret = getSecurityKey(); // secret key length must be 16
+		SecretKey key;
+		Cipher cipher;
+		Base64 coder;
+		key = new SecretKeySpec(secret.getBytes(), "AES");
+		try {
+			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
+			coder = new Base64();
+			byte[] encrypted = coder.decode(repoUserPassword.getBytes());
+			cipher.init(Cipher.DECRYPT_MODE, key);
+			byte[] decrypted = cipher.doFinal(encrypted);
+			decryptPassword = new String(decrypted);
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return decryptPassword;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java
new file mode 100644
index 0000000..3a83a54
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java
@@ -0,0 +1,289 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.Source;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.validation.Validator;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNode;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.impl.dom.DOOMAbstractFactory;
+import org.apache.axiom.om.impl.dom.ElementImpl;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.dto.Policy;
+import org.apache.stratos.adc.mgt.dto.PolicyDefinition;
+import org.jaxen.JaxenException;
+import org.w3c.dom.Element;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.xml.sax.SAXException;
+
+import com.google.gson.Gson;
+
+public class PolicyHolder {
+
+	private static Log log = LogFactory.getLog(PolicyHolder.class);
+
+	private static final String POLICIES_ELEMENT = "policies";
+	private static final String POLICY_ELEMENT = "policy";
+
+	private static final String POLICIES_ELEMENT_XPATH = "/" + POLICIES_ELEMENT + "/" + POLICY_ELEMENT;
+
+	private static final String NAME_ATTR = "name";
+	private static final String IS_DEFAULT_ATTR = "isDefault";
+	private static final String DESCRIPTION_ELEMENT = "description";
+	private static final String MIN_APP_INSTANCES_ELEMENT = "min_app_instances";
+	private static final String MAX_APP_INSTANCES_ELEMENT = "max_app_instances";
+	private static final String MAX_REQUESTS_PER_SECOND_ELEMENT = "max_requests_per_second";
+	private static final String ALARMING_UPPER_RATE_ELEMENT = "alarming_upper_rate";
+	private static final String ALARMING_LOWER_RATE_ELEMENT = "alarming_lower_rate";
+	private static final String SCALE_DOWN_FACTOR_ELEMENT = "scale_down_factor";
+	private static final String ROUNDS_TO_AVERAGE_ELEMENT = "rounds_to_average";
+
+	private Map<String, Policy> policyMap = new HashMap<String, Policy>();
+
+	private Policy defaultPolicy;
+
+	private List<PolicyDefinition> policyDefinitions = new ArrayList<PolicyDefinition>();
+
+	private PolicyHolder(File policiesSchema, File policiesXML) {
+		try {
+			readPolicies(policiesSchema, policiesXML);
+		} catch (Exception e) {
+			log.error("Error reading policies", e);
+		}
+	}
+
+	private static class SingletonHolder {
+		private final static PolicyHolder INSTANCE = new PolicyHolder(new File(CarbonUtils.getCarbonConfigDirPath()
+				+ File.separator + "etc" + File.separator, "policies.xsd"), new File(
+				CarbonUtils.getCarbonConfigDirPath(), "policies.xml"));
+	}
+
+	public static PolicyHolder getInstance() {
+		return SingletonHolder.INSTANCE;
+	}
+
+	public Policy getPolicy(String policyName) {
+		return policyMap.get(policyName);
+	}
+
+	public Policy getDefaultPolicy() {
+		return defaultPolicy;
+	}
+
+	public List<PolicyDefinition> getPolicyDefinitions() {
+		return policyDefinitions;
+	}
+
+	private void readPolicies(File policiesSchema, File policiesXML) throws XMLStreamException, JaxenException,
+			SAXException, IOException {
+		if (log.isDebugEnabled()) {
+			log.debug("Policies schema: " + policiesSchema.getPath());
+			log.debug("Loading policies from file: " + policiesXML.getPath());
+		}
+		OMElement documentElement;
+		if (policiesXML.exists()) {
+			documentElement = new StAXOMBuilder(policiesXML.getPath()).getDocumentElement();
+		} else {
+			throw new IllegalStateException("Policies file cannot be found : " + policiesXML.getPath());
+		}
+
+		// Validate XML
+		validate(documentElement, policiesSchema);
+		
+		String xpath = POLICIES_ELEMENT_XPATH;
+
+		AXIOMXPath axiomXpath;
+		axiomXpath = new AXIOMXPath(xpath);
+		@SuppressWarnings("unchecked")
+		List<OMNode> policyNodes = axiomXpath.selectNodes(documentElement);
+
+		if (policyNodes == null || policyNodes.isEmpty()) {
+			log.warn("No policies found in the file : " + policiesXML.getPath());
+			return;
+		}
+
+		for (OMNode policyNode : policyNodes) {
+
+			if (policyNode.getType() == OMNode.ELEMENT_NODE) {
+
+				OMElement policyElement = (OMElement) policyNode;
+
+				try {
+					readPolicy(policyElement);
+				} catch (Exception e) {
+					log.error("Error reading policy", e);
+				}
+			}
+		}
+	}
+
+	private void readPolicy(OMElement policyElement) {
+		// retrieve attributes
+		String name = policyElement.getAttributeValue(new QName(NAME_ATTR));
+		boolean isDefault = Boolean.valueOf(policyElement.getAttributeValue(new QName(IS_DEFAULT_ATTR)));
+
+		Policy policy = new Policy();
+		policy.setName(name);
+		policy.setDefaultPolicy(isDefault);
+
+		// read description
+		Iterator<?> it = policyElement.getChildrenWithName(new QName(DESCRIPTION_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setDescription(element.getText());
+		}
+
+		// read min_app_instances
+		it = policyElement.getChildrenWithName(new QName(MIN_APP_INSTANCES_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setMinAppInstances(Integer.parseInt(element.getText()));
+		}
+
+		// read max_app_instances
+		it = policyElement.getChildrenWithName(new QName(MAX_APP_INSTANCES_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setMaxAppInstances(Integer.parseInt(element.getText()));
+		}
+
+		// read max_requests_per_second
+		it = policyElement.getChildrenWithName(new QName(MAX_REQUESTS_PER_SECOND_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setMaxRequestsPerSecond(Integer.parseInt(element.getText()));
+		}
+
+		// read rounds_to_average
+		it = policyElement.getChildrenWithName(new QName(ROUNDS_TO_AVERAGE_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setRoundsToAverage(Integer.parseInt(element.getText()));
+		}
+
+		// read alarming_upper_rate
+		it = policyElement.getChildrenWithName(new QName(ALARMING_UPPER_RATE_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setAlarmingUpperRate(new BigDecimal(element.getText()));
+		}
+
+		// read alarming_lower_rate
+		it = policyElement.getChildrenWithName(new QName(ALARMING_LOWER_RATE_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setAlarmingLowerRate(new BigDecimal(element.getText()));
+		}
+
+		// read scale_down_factor
+		it = policyElement.getChildrenWithName(new QName(SCALE_DOWN_FACTOR_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setScaleDownFactor(new BigDecimal(element.getText()));
+		}
+		if (log.isDebugEnabled()) {
+			log.debug("Policy: " + new Gson().toJson(policy));
+		}
+
+		policyMap.put(policy.getName(), policy);
+		PolicyDefinition policyDefinition = new PolicyDefinition();
+		policyDefinition.setName(policy.getName());
+		policyDefinition.setDescription(policy.getDescription());
+		policyDefinition.setDefaultPolicy(policy.isDefaultPolicy());
+		policyDefinitions.add(policyDefinition);
+		
+		// Set first default policy
+		if (defaultPolicy == null && policy.isDefaultPolicy()) {
+			defaultPolicy = policy;
+		}
+	}
+	
+	// TODO Following code is copied from
+	// org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser
+	// There should be a common util to validate XML using a schema.
+	public void validate(final OMElement omElement, final File schemaFile) throws SAXException, IOException {
+
+		Element sourceElement;
+
+		// if the OMElement is created using DOM implementation use it
+		if (omElement instanceof ElementImpl) {
+			sourceElement = (Element) omElement;
+		} else { // else convert from llom to dom
+			sourceElement = getDOMElement(omElement);
+		}
+
+		// Create a SchemaFactory capable of understanding WXS schemas.
+
+		// Load a WXS schema, represented by a Schema instance.
+		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+		Source source = new StreamSource(schemaFile);
+
+		// Create a Validator object, which can be used to validate
+		// an instance document.
+		Schema schema = factory.newSchema(source);
+		Validator validator = schema.newValidator();
+
+		// Validate the DOM tree.
+		validator.validate(new DOMSource(sourceElement));
+	}
+
+	private Element getDOMElement(final OMElement omElement) {
+
+		// Get the StAX reader from the created element
+		XMLStreamReader llomReader = omElement.getXMLStreamReader();
+
+		// Create the DOOM OMFactory
+		OMFactory doomFactory = DOOMAbstractFactory.getOMFactory();
+
+		// Create the new builder
+		StAXOMBuilder doomBuilder = new StAXOMBuilder(doomFactory, llomReader);
+
+		// Get the document element
+		OMElement newElem = doomBuilder.getDocumentElement();
+
+		return newElem instanceof Element ? (Element) newElem : null;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java
new file mode 100644
index 0000000..30f8149
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java
@@ -0,0 +1,266 @@
+package org.apache.stratos.adc.mgt.utils;
+
+import com.gitblit.Constants;
+import com.gitblit.models.RepositoryModel;
+import com.gitblit.utils.RpcUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.dao.Repository;
+import org.apache.stratos.adc.mgt.exception.ADCException;
+import org.apache.stratos.adc.mgt.service.RepositoryInfoBean;
+import org.eclipse.jgit.api.*;
+import org.eclipse.jgit.storage.file.FileRepository;
+import org.eclipse.jgit.transport.CredentialsProvider;
+import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.UUID;
+
+public class RepositoryCreator implements Runnable {
+
+	private static final Log log = LogFactory.getLog(RepositoryCreator.class);
+	private RepositoryInfoBean repoInfoBean;
+
+	public RepositoryCreator(RepositoryInfoBean repoInfoBean) {
+		this.repoInfoBean = repoInfoBean;
+	}
+
+	@Override
+	public void run() {
+
+		if (repoInfoBean != null) {
+			try {
+				createRepository(repoInfoBean.getCartridgeAlias(), repoInfoBean.getTenantDomain(),
+				                 repoInfoBean.getUserName(), repoInfoBean.getPassword());
+				createGitFolderStructure(repoInfoBean.getTenantDomain(),
+				                         repoInfoBean.getCartridgeAlias(),
+				                         repoInfoBean.getDirArray());
+
+			} catch (Exception e) {
+				log.error(e);
+			}
+		}
+	}
+
+    //Creating the internal repo in the same thread as subscribe()
+    public void createInternalRepository () throws Exception {
+
+        if (repoInfoBean != null) {
+            try {
+                createRepository(repoInfoBean.getCartridgeAlias(), repoInfoBean.getTenantDomain(),
+                        repoInfoBean.getUserName(), repoInfoBean.getPassword());
+                
+				if (repoInfoBean.getDirArray() != null && repoInfoBean.getDirArray().length > 0) {
+					createGitFolderStructure(repoInfoBean.getTenantDomain(),
+					                         repoInfoBean.getCartridgeAlias(),
+					                         repoInfoBean.getDirArray());
+				}
+
+            } catch (Exception e) {
+                String errorMsg = "Creating an internal repository failed for tenant " + repoInfoBean.getTenantDomain();
+                log.error(errorMsg, e);
+                throw new Exception(errorMsg, e);
+            }
+        }
+    }
+
+	private Repository createRepository(String cartridgeName, String tenantDomain, String userName, String password)
+	                                                                                               throws Exception {
+
+		Repository repository = new Repository();
+		String repoName = tenantDomain + "/" + cartridgeName;
+
+		try {
+			
+			log.info("Creating internal repo ["+repoName+"] ");
+
+			RepositoryModel model = new RepositoryModel();
+			model.name = repoName;
+			model.accessRestriction = Constants.AccessRestrictionType.VIEW;
+
+			char[] passwordArr = password.toCharArray();
+
+			boolean isSuccess =
+			                    RpcUtils.createRepository(model,
+			                                              "https://localhost:8443/",
+			                                              userName, passwordArr);
+			if (!isSuccess) {
+				throw new Exception("Exception is occurred when creating an internal git repo. ");
+			}
+		} catch (Exception e) {
+			log.error(" Exception is occurred when creating an internal git repo. Reason :" +
+			          e.getMessage());
+			handleException(e.getMessage(), e);
+		}
+
+		return repository;
+
+	}
+
+	private void createGitFolderStructure(String tenantDomain, String cartridgeName,
+	                                      String[] dirArray) throws Exception {
+		
+		if (log.isDebugEnabled()) {
+			log.debug("Creating git repo folder structure  ");
+		}		
+		
+		String parentDirName = "/tmp/" + UUID.randomUUID().toString();
+		CredentialsProvider credentialsProvider =
+		                                          new UsernamePasswordCredentialsProvider(
+		                                                                                  System.getProperty(CartridgeConstants.INTERNAL_GIT_USERNAME),
+		                                                                                  System.getProperty(CartridgeConstants.INTERNAL_GIT_PASSWORD).toCharArray());
+		// Clone
+		// --------------------------
+		FileRepository localRepo = null;
+		try {
+			localRepo = new FileRepository(new File(parentDirName + "/.git"));
+		} catch (IOException e) {
+			log.error("Exception occurred in creating a new file repository. Reason: " + e.getMessage());
+			throw e;
+		}
+
+		Git git = new Git(localRepo);
+
+		CloneCommand cloneCmd =
+		                        git.cloneRepository()
+		                           .setURI("https://localhost:8443/git/" + tenantDomain + "/" +
+		                                           cartridgeName + ".git")
+		                           .setDirectory(new File(parentDirName));
+
+		cloneCmd.setCredentialsProvider(credentialsProvider);
+		try {
+			log.debug("Clonning git repo");
+			cloneCmd.call();
+		} catch (Exception e1) {
+			log.error("Exception occurred in cloning Repo. Reason: " + e1.getMessage());
+			throw e1;
+		}
+		// ------------------------------------
+
+		// --- Adding directory structure --------
+
+		File parentDir = new File(parentDirName);
+		parentDir.mkdir();
+
+		for (String string : dirArray) {
+			String[] arr = string.split("=");
+			if (log.isDebugEnabled()) {
+				log.debug("Creating dir: " + arr[0]);
+			}
+			File parentFile = new File(parentDirName + "/" + arr[0]);
+			parentFile.mkdirs();
+
+			File filess = new File(parentFile, "README");
+			String content = "Content goes here";
+
+			filess.createNewFile();
+			FileWriter fw = new FileWriter(filess.getAbsoluteFile());
+			BufferedWriter bw = new BufferedWriter(fw);
+			bw.write(content);
+			bw.close();
+		}
+		// ----------------------------------------------------------
+
+		// ---- Git status ---------------
+		StatusCommand s = git.status();
+		Status status = null;
+		try {
+			log.debug("Getting git repo status");
+			status = s.call();
+		} catch (Exception e) {
+			log.error("Exception occurred in git status check. Reason: " + e.getMessage());
+			throw e;
+		}
+		// --------------------------------
+
+		// ---------- Git add ---------------
+		AddCommand addCmd = git.add();
+		Iterator<String> it = status.getUntracked().iterator();
+
+		while (it.hasNext()) {
+			addCmd.addFilepattern(it.next());
+		}
+
+		try {
+			log.debug("Adding files to git repo");
+			addCmd.call();
+		} catch (Exception e) {
+			log.error("Exception occurred in adding files. Reason: " + e.getMessage());
+			throw e;
+		}
+		// -----------------------------------------
+
+		// ------- Git commit -----------------------
+
+		CommitCommand commitCmd = git.commit();
+		commitCmd.setMessage("Adding directories");
+
+		try {
+			log.debug("Committing git repo");
+			commitCmd.call();
+		} catch (Exception e) {
+			log.error("Exception occurred in committing . Reason: " + e.getMessage());
+			throw e;
+		}
+		// --------------------------------------------
+
+		// --------- Git push -----------------------
+		PushCommand pushCmd = git.push();
+		pushCmd.setCredentialsProvider(credentialsProvider);
+		try {
+			log.debug("Git repo push");
+			pushCmd.call();
+		} catch (Exception e) {
+			log.error("Exception occurred in Git push . Reason: " + e.getMessage());
+			throw e;
+		}
+
+		try {
+			deleteDirectory(new File(parentDirName));
+		} catch (Exception e) {
+			log.error("Exception occurred in deleting temp files. Reason: " + e.getMessage());
+			throw e;
+		}
+
+		log.info(" Folder structure  is created ..... ");
+
+	}
+
+	private void handleException(String msg, Exception e) throws Exception {
+		log.error(msg, e);
+		throw new Exception(msg, e);
+	}
+
+	private void deleteDirectory(File file) throws IOException {
+
+		if (file.isDirectory()) {
+			// directory is empty, then delete it
+			if (file.list().length == 0) {
+				file.delete();
+
+			} else {
+				// list all the directory contents
+				String files[] = file.list();
+
+				for (String temp : files) {
+					// construct the file structure
+					File fileDelete = new File(file, temp);
+					// recursive delete
+					deleteDirectory(fileDelete);
+				}
+				// check the directory again, if empty then delete it
+				if (file.list().length == 0) {
+					file.delete();
+				}
+			}
+
+		} else {
+			// if file, then delete it
+			file.delete();
+		}
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java
new file mode 100644
index 0000000..d0dd919
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.utils;
+
+import java.io.File;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.dao.Repository;
+import org.apache.stratos.adc.mgt.service.ApplicationManagementService;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * @author wso2
+ * 
+ */
+public class RepositoryFactory {
+
+	private static final Log log = LogFactory.getLog(ApplicationManagementService.class);
+
+	/*public synchronized Repository createRepository(String cartridgeName, String tenantDomain,
+	                                          String userName) throws Exception {
+
+		Repository repository = new Repository();
+		String repoName = tenantDomain + "/" + cartridgeName; // removed .git part
+		String repoUserName = userName + "@" + tenantDomain;
+
+		Process proc;
+		try {
+
+			String command =
+			                 CarbonUtils.getCarbonHome() + File.separator + "bin" + File.separator +
+			                         "manage-git-repo.sh " + "create " + repoUserName + " " +
+			                         tenantDomain + " " + cartridgeName + " " +
+			                         System.getProperty(CartridgeConstants.REPO_NOTIFICATION_URL) + " " +
+			                         System.getProperty(CartridgeConstants.GIT_HOST_NAME) +
+			                         " /";
+			proc = Runtime.getRuntime().exec(command);
+			log.info("executing manage-git-repo script..... command :" + command);
+			proc.waitFor();
+			log.info(" Repo is created ..... for user: " + userName + ", tenantName: " +
+			         tenantDomain + " ");
+			repository.setRepoName("git@" + System.getProperty(CartridgeConstants.GIT_HOST_NAME) + ":" +repoName);
+		} catch (Exception e) {
+			log.error(" Exception is occurred when executing manage-git-repo script. Reason :" +
+			          e.getMessage());
+			handleException(e.getMessage(), e);
+		}
+
+		return repository;
+
+	}*/
+
+	/*public synchronized void createGitFolderStructure(String tenantDomain, String cartridgeName,
+	                                            String[] dirArray) throws Exception {
+
+		log.info("In create Git folder structure...!");
+
+		StringBuffer dirBuffer = new StringBuffer();
+		for (String dir : dirArray) {
+			dirBuffer.append(dir).append(" ");
+		}
+
+		Process proc;
+		try {
+			String command =
+			                 CarbonUtils.getCarbonHome() + File.separator + "bin" + File.separator +
+			                         "git-folder-structure.sh " + tenantDomain + " " +
+			                         cartridgeName + " " + dirBuffer.toString() + " /";
+			proc = Runtime.getRuntime().exec(command);
+			log.info("executing manage-git-repo script..... command : " + command);
+			proc.waitFor();
+
+		} catch (Exception e) {
+			log.error(" Exception is occurred when executing manage-git-repo script. Reason :" +
+			          e.getMessage());
+			handleException(e.getMessage(), e);
+		}
+
+		log.info(" Folder structure  is created ..... ");
+
+	}*/
+	
+	public synchronized void destroyRepository(String cartridgeName, String tenantDomain,
+	                                          String userName) throws Exception {
+
+		String repoUserName = userName + "@" + tenantDomain;
+
+		Process proc;
+		try {
+
+			String command =
+			                 CarbonUtils.getCarbonHome() + File.separator + "bin" + File.separator +
+			                         "manage-git-repo.sh " + "destroy " + repoUserName + " " +
+			                         tenantDomain + " " + cartridgeName + 
+			                         " /";
+			proc = Runtime.getRuntime().exec(command);
+			log.info("executing manage-git-repo script (destroy)..... command :" + command);
+			proc.waitFor();
+			log.info(" Repo is destroyed ..... for user: " + userName + ", tenantName: " +
+			         tenantDomain + " ");
+		} catch (Exception e) {
+			log.error(" Exception is occurred when destroying git repo. Reason :" +
+			          e.getMessage());
+			handleException(e.getMessage(), e);
+		}
+
+	}
+
+	private void handleException(String msg, Exception e) throws Exception {
+		log.error(msg, e);
+		throw new Exception(msg, e);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java
new file mode 100644
index 0000000..7a4736d
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java
@@ -0,0 +1,210 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.apache.stratos.adc.mgt.utils;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.tomcat.jdbc.pool.DataSource;
+import org.apache.tomcat.jdbc.pool.PoolProperties;
+
+public final class StratosDBUtils {
+
+	private static final Log log = LogFactory.getLog(StratosDBUtils.class);
+
+	private static volatile javax.sql.DataSource dataSource = null;
+
+	/**
+	 * Initializes the data source
+	 * 
+	 * @throws RuntimeException
+	 *             if an error occurs while loading DB configuration
+	 */
+	public static void initialize() throws Exception {
+		if (dataSource != null) {
+			return;
+		}
+
+		synchronized (StratosDBUtils.class) {
+			if (dataSource == null) {
+
+				String datasourceName = System.getProperty(CartridgeConstants.DB_DATASOURCE);
+
+				if (datasourceName != null && datasourceName.trim().length() > 0) {
+					if (log.isInfoEnabled()) {
+						log.info("Initializing data source: " + datasourceName);
+					}
+					try {
+						Context ctx = new InitialContext();
+						dataSource = (DataSource) ctx.lookup(datasourceName);
+						if (dataSource != null && log.isInfoEnabled()) {
+							log.info("Found data source: " + datasourceName + ", " + dataSource.getClass().getName());
+						}
+					} catch (NamingException e) {
+						throw new RuntimeException("Error while looking up the data source: " + datasourceName, e);
+					}
+				} else {
+					// FIXME Should we use system properties to get database
+					// details?
+					String dbUrl = System.getProperty(CartridgeConstants.DB_URL);
+					String driver = System.getProperty(CartridgeConstants.DB_DRIVER);
+					String username = System.getProperty(CartridgeConstants.DB_USERNAME);
+					String password = System.getProperty(CartridgeConstants.DB_PASSWORD);
+
+					if (dbUrl == null || driver == null || username == null || password == null) {
+						String msg = "Required DB configuration parameters are not specified.";
+						log.warn(msg);
+						throw new RuntimeException(msg);
+					}
+					
+					if (log.isInfoEnabled()) {
+						log.info("Initializing data source for JDBC URL: " + dbUrl);
+					}
+
+					PoolProperties p = new PoolProperties();
+					p.setUrl(dbUrl);
+					p.setDriverClassName(driver);
+					p.setUsername(username);
+					p.setPassword(password);
+					p.setJmxEnabled(true);
+					p.setTestWhileIdle(false);
+					p.setTestOnBorrow(true);
+					p.setValidationQuery("SELECT 1");
+					p.setTestOnReturn(false);
+					p.setValidationInterval(30000);
+					p.setTimeBetweenEvictionRunsMillis(30000);
+					p.setMaxActive(100);
+					p.setInitialSize(10);
+					p.setMaxWait(10000);
+					p.setRemoveAbandonedTimeout(60);
+					p.setMinEvictableIdleTimeMillis(30000);
+					p.setMinIdle(10);
+					p.setLogAbandoned(true);
+					p.setRemoveAbandoned(true);
+					p.setDefaultAutoCommit(false);
+					p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
+							+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
+					DataSource tomcatDatasource = new DataSource();
+					tomcatDatasource.setPoolProperties(p);
+
+					dataSource = tomcatDatasource;
+				}
+
+			}
+		}
+	}
+
+	/**
+	 * Utility method to get a new database connection
+	 * 
+	 * @return Connection
+	 * @throws java.sql.SQLException
+	 *             if failed to get Connection
+	 */
+	public static Connection getConnection() throws SQLException {
+		if (dataSource != null) {
+			return dataSource.getConnection();
+		}
+		throw new SQLException("Datasource is not configured properly.");
+	}
+
+	/**
+	 * Utility method to close the connection streams.
+	 * 
+	 * @param connection
+	 *            Connection
+	 * @param preparedStatement
+	 *            PreparedStatement
+	 * @param resultSet
+	 *            ResultSet
+	 */
+	public static void closeAllConnections(Connection connection, PreparedStatement preparedStatement,
+			ResultSet resultSet) {
+		closeResultSet(resultSet);
+		closeStatement(preparedStatement);
+		closeConnection(connection);
+	}
+
+	public static void closeAllConnections(Connection connection, PreparedStatement... preparedStatements) {
+		for (PreparedStatement preparedStatement : preparedStatements) {
+			closeStatement(preparedStatement);
+		}
+		closeConnection(connection);
+	}
+
+	/**
+	 * Close Connection
+	 * 
+	 * @param dbConnection
+	 *            Connection
+	 */
+	public static void closeConnection(Connection dbConnection) {
+		if (dbConnection != null) {
+			try {
+				dbConnection.close();
+			} catch (SQLException e) {
+				log.warn(
+						"Database error. Could not close database connection. Continuing with " + "others. - "
+								+ e.getMessage(), e);
+			}
+		}
+	}
+
+	/**
+	 * Close ResultSet
+	 * 
+	 * @param resultSet
+	 *            ResultSet
+	 */
+	public static void closeResultSet(ResultSet resultSet) {
+		if (resultSet != null) {
+			try {
+				resultSet.close();
+			} catch (SQLException e) {
+				log.warn("Database error. Could not close ResultSet  - " + e.getMessage(), e);
+			}
+		}
+
+	}
+
+	/**
+	 * Close PreparedStatement
+	 * 
+	 * @param preparedStatement
+	 *            PreparedStatement
+	 */
+	public static void closeStatement(PreparedStatement preparedStatement) {
+		if (preparedStatement != null) {
+			try {
+				preparedStatement.close();
+			} catch (SQLException e) {
+				log.warn(
+						"Database error. Could not close PreparedStatement. Continuing with" + " others. - "
+								+ e.getMessage(), e);
+			}
+		}
+
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java
new file mode 100644
index 0000000..6905a51
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.utils;
+
+import org.apache.axis2.clustering.ClusteringCommand;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.clustering.ClusteringMessage;
+import org.apache.axis2.clustering.management.GroupManagementCommand;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.engine.AxisConfigurator;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.osgi.util.tracker.ServiceTracker;
+import org.wso2.carbon.core.CarbonAxisConfigurator;
+import org.wso2.carbon.core.internal.CarbonCoreDataHolder;
+import org.wso2.carbon.core.multitenancy.TenantAxisConfigurator;
+import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.deployment.GhostDeployerUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+import java.util.UUID;
+
+/**
+ * ClusterMessage for sending a deployment repository synchronization request
+ */
+public class SynchronizeRepositoryRequest extends GroupManagementCommand {
+
+	/**
+     * 
+     */
+	private static final long serialVersionUID = 8717694086109561127L;
+
+	private transient static final Log log = LogFactory.getLog(SynchronizeRepositoryRequest.class);
+	private int tenantId;
+	private String tenantDomain;
+	private UUID messageId;
+
+	public SynchronizeRepositoryRequest() {
+	}
+
+	public SynchronizeRepositoryRequest(int tenantId, String tenantDomain, UUID messageId) {
+		this.tenantId = tenantId;
+		this.tenantDomain = tenantDomain;
+		this.messageId = messageId;
+	}
+
+	public void setTenantId(int tenantId) {
+		this.tenantId = tenantId;
+	}
+
+	public void execute(ConfigurationContext configContext) throws ClusteringFault {
+		log.info("Received  [" + this + "] ");
+		// Run only if the tenant is loaded
+		if (tenantId == MultitenantConstants.SUPER_TENANT_ID ||
+		    TenantAxisUtils.getTenantConfigurationContexts(configContext).get(tenantDomain) != null) {
+			updateDeploymentRepository(configContext);
+			doDeployment(configContext);
+		}
+	}
+
+	private void doDeployment(ConfigurationContext configContext) {
+		AxisConfigurator axisConfigurator = configContext.getAxisConfiguration().getConfigurator();
+		if (axisConfigurator instanceof CarbonAxisConfigurator) {
+			((CarbonAxisConfigurator) axisConfigurator).runDeployment();
+		} else if (axisConfigurator instanceof TenantAxisConfigurator) {
+			((TenantAxisConfigurator) axisConfigurator).runDeployment();
+		}
+	}
+
+	private void updateDeploymentRepository(ConfigurationContext configContext) {
+
+		log.info(" Update Deployment Repo...");
+		/*
+		 * BundleContext bundleContext =
+		 * CarbonCoreDataHolder.getInstance().getBundleContext();
+		 * ServiceReference reference =
+		 * bundleContext.getServiceReference(DeploymentSynchronizer.class.getName
+		 * ());
+		 * if (reference != null) {
+		 * ServiceTracker serviceTracker =
+		 * new ServiceTracker(bundleContext,
+		 * DeploymentSynchronizer.class.getName(), null);
+		 * try {
+		 * serviceTracker.open();
+		 * for (Object obj : serviceTracker.getServices()) {
+		 * // if the update is for worker node with ghost ON, then we will
+		 * update the
+		 * // whole repo for now. See CARBON-13899
+		 * if (GhostDeployerUtils.isGhostOn() && CarbonUtils.isWorkerNode() &&
+		 * tenantId > 0) {
+		 * String repoPath = MultitenantUtils.getAxis2RepositoryPath(tenantId);
+		 * ((DeploymentSynchronizer) obj).update(repoPath, repoPath, 3);
+		 * } else {
+		 * ((DeploymentSynchronizer) obj).update(tenantId);
+		 * }
+		 * }
+		 * } catch (Exception e) {
+		 * log.error("Repository update failed for tenant " + tenantId, e);
+		 * setRepoUpdateFailed(configContext);
+		 * } finally {
+		 * serviceTracker.close();
+		 * }
+		 * }
+		 */
+	}
+
+	private void setRepoUpdateFailed(ConfigurationContext configContext) {
+		AxisConfigurator axisConfigurator = configContext.getAxisConfiguration().getConfigurator();
+		if (axisConfigurator instanceof CarbonAxisConfigurator) {
+			((CarbonAxisConfigurator) axisConfigurator).setRepoUpdateFailed();
+		} else if (axisConfigurator instanceof TenantAxisConfigurator) {
+			((TenantAxisConfigurator) axisConfigurator).setRepoUpdateFailed();
+		}
+	}
+
+	public ClusteringCommand getResponse() {
+		return null;
+	}
+
+	@Override
+	public String toString() {
+		return "SynchronizeRepositoryRequest{" + "tenantId=" + tenantId + ", tenantDomain='" +
+		       tenantDomain + '\'' + ", messageId=" + messageId + '}';
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.adc.mgt/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..a7ddc11
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/resources/META-INF/services.xml
@@ -0,0 +1,86 @@
+<!-- ~ Copyright WSO2 Inc. (http://www.wso2.com) All Rights
+	Reserved. ~ ~ WSO2 Inc. licenses this file to you under the Apache License, 
+	~ Version 2.0 (the "License"); you may not use this file except ~ in compliance 
+	with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 
+	~ ~ Unless required by applicable law or agreed to in writing, ~ software 
+	distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT 
+	WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the 
+	License for the ~ specific language governing permissions and limitations 
+	~ under the License. -->
+<serviceGroup>
+	<service name="ApplicationManagementService" scope="transportsession">
+		<transports>
+			<transport>https</transport>
+		</transports>
+		<description>
+			Admin service for ADC activities
+		</description>
+		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.ApplicationManagementService
+        </parameter>
+		<parameter name="enableMTOM">true</parameter>
+		<parameter name="adminService" locked="true">true</parameter>
+		<parameter name="hiddenService" locked="true">true</parameter>
+		<parameter name="AuthorizationAction" locked="true">
+			/permission/admin/manage/modify/webapp    </parameter>
+		<parameter name="DoAuthentication" locked="true">true</parameter>
+	</service>
+
+	<service name="RepoNotificationService" scope="transportsession">
+		<schema schemaNamespace="http://org.apache.axis2/xsd"
+			elementFormDefaultQualified="true" />
+		<transports>
+			<transport>https</transport>
+		</transports>
+		<description>
+			Admin service for receiving git repo update notifications
+		</description>
+		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.RepoNotificationService
+		</parameter>
+		<parameter name="enableMTOM">true</parameter>
+		<parameter name="adminService" locked="true">false</parameter>
+		<parameter name="hiddenService" locked="true">false</parameter>
+		<parameter name="AuthorizationAction" locked="false">
+			/permission/admin/manage/modify/webapp
+    </parameter>
+	</service>
+
+	<service name="RepositoryInformationService" scope="transportsession">
+		<schema schemaNamespace="http://org.apache.axis2/xsd"
+			elementFormDefaultQualified="true" />
+		<transports>
+			<transport>https</transport>
+		</transports>
+		<description>
+			Exposes information related to internally created
+			repositories
+        </description>
+		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.RepositoryInformationService
+		</parameter>
+		<parameter name="enableMTOM">true</parameter>
+		<parameter name="adminService" locked="true">false</parameter>
+		<parameter name="hiddenService" locked="true">false</parameter>
+		<parameter name="AuthorizationAction" locked="false">
+			/permission/admin/manage/modify/webapp
+    	</parameter>
+	</service>
+
+	<service name="InstanceInformationManagementService" scope="transportsession">
+		<schema schemaNamespace="http://org.apache.axis2/xsd"
+			elementFormDefaultQualified="true" />
+		<transports>
+			<transport>https</transport>
+		</transports>
+		<description>
+			Exposes information related to internally created
+			repositories
+        </description>
+		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.InstanceInformationManagementService</parameter>
+		<parameter name="enableMTOM">true</parameter>
+		<parameter name="adminService" locked="true">false</parameter>
+		<parameter name="hiddenService" locked="true">false</parameter>
+		<parameter name="AuthorizationAction" locked="false">
+			/permission/admin/manage/modify/webapp
+    	</parameter>
+	</service>
+
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/resources/policies.xsd
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/resources/policies.xsd b/components/org.apache.stratos.adc.mgt/src/main/resources/policies.xsd
new file mode 100644
index 0000000..87f7b58
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/resources/policies.xsd
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<xs:schema attributeFormDefault="unqualified"
+	elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+	<xs:element name="policies">
+		<xs:annotation>
+			<xs:documentation>Use below section to specify auto-scaling policies
+				for cartridges.
+			</xs:documentation>
+		</xs:annotation>
+		<xs:complexType>
+			<xs:sequence>
+				<xs:element name="policy" maxOccurs="unbounded"
+					minOccurs="1">
+					<xs:annotation>
+						<xs:documentation>You can have 1..n policy elements.
+						</xs:documentation>
+					</xs:annotation>
+					<xs:complexType>
+						<xs:sequence>
+							<xs:element type="xs:string" name="description" />
+							<xs:element type="xs:integer" name="min_app_instances" />
+							<xs:element type="xs:integer" name="max_app_instances" />
+							<xs:element type="xs:integer" name="max_requests_per_second" />
+							<xs:element type="xs:decimal" name="alarming_upper_rate" />
+							<xs:element type="xs:decimal" name="alarming_lower_rate" />
+							<xs:element type="xs:decimal" name="scale_down_factor" />
+							<xs:element type="xs:integer" name="rounds_to_average" />
+						</xs:sequence>
+						<xs:attribute type="xs:string" name="name" use="required" />
+						<xs:attribute type="xs:boolean" name="isDefault" use="required" />
+					</xs:complexType>
+				</xs:element>
+			</xs:sequence>
+		</xs:complexType>
+	</xs:element>
+</xs:schema>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/scripts/append_zone_file.sh
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/scripts/append_zone_file.sh b/components/org.apache.stratos.adc.mgt/src/scripts/append_zone_file.sh
new file mode 100755
index 0000000..45491df
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/scripts/append_zone_file.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+echo "subdomain $1 and ip $2 added to $3"
+appending_file=$3
+subdomain=$1
+ip=$2
+
+#appending the zone file
+echo $subdomain'\t'IN'\t'A'\t'$ip>> $appending_file
+
+#increasing the count
+for file in $appending_file;
+do
+  if [ -f $file ];
+  then
+    OLD=`egrep -ho "2010-9[0-9]*" $file`
+    NEW=$(($OLD + 1))
+    sed -i "s/$OLD/$NEW/g" $file
+    echo "fixed $file" 
+  fi
+done
+
+
+#reloading bind server
+/etc/init.d/bind9 reload

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java b/components/org.apache.stratos.adc.mgt/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java
new file mode 100644
index 0000000..ba350aa
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java
@@ -0,0 +1,63 @@
+package org.apache.stratos.adc.mgt.test;
+
+import java.io.File;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
+import junit.framework.TestCase;
+
+import org.apache.stratos.adc.mgt.utils.PolicyHolder;
+
+public class PolicyHolderTest extends TestCase {
+
+	private PolicyHolder getPolicyHolder(String policiesXMLFile) {
+		File policiesXmlSchema = new File("src/main/resources/policies.xsd");
+		String dir = "src/test/resources/";
+
+		Class<PolicyHolder> clazz = PolicyHolder.class;
+
+		Constructor<PolicyHolder> c;
+		try {
+			c = clazz.getDeclaredConstructor(File.class, File.class);
+			c.setAccessible(true);
+		} catch (NoSuchMethodException e) {
+			throw new RuntimeException(e);
+		} catch (SecurityException e) {
+			throw new RuntimeException(e);
+		}
+		PolicyHolder policyHolder;
+		try {
+			policyHolder = c.newInstance(policiesXmlSchema, new File(dir, policiesXMLFile));
+		} catch (InstantiationException e) {
+			throw new RuntimeException(e);
+		} catch (IllegalAccessException e) {
+			throw new RuntimeException(e);
+		} catch (IllegalArgumentException e) {
+			throw new RuntimeException(e);
+		} catch (InvocationTargetException e) {
+			throw new RuntimeException(e);
+		}
+		return policyHolder;
+	}
+
+	public void testDefaultPolicy() {
+		PolicyHolder policyHolder = getPolicyHolder("policies-1.xml");
+		assertNotNull(policyHolder);
+		assertNotNull(policyHolder.getDefaultPolicy());
+	}
+	
+	
+	public void testSinglePolicy() {
+		PolicyHolder policyHolder = getPolicyHolder("policies-1.xml");
+		assertNotNull(policyHolder);
+		assertNotNull(policyHolder.getPolicy("single"));
+		assertEquals("single", policyHolder.getPolicy("single").getName());
+	}
+	
+	public void testElasticPolicy() {
+		PolicyHolder policyHolder = getPolicyHolder("policies-1.xml");
+		assertNotNull(policyHolder);
+		assertNotNull(policyHolder.getPolicy("elastic"));
+		assertEquals("elastic", policyHolder.getPolicy("elastic").getName());
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/test/resources/log4j.properties b/components/org.apache.stratos.adc.mgt/src/test/resources/log4j.properties
new file mode 100644
index 0000000..d30536d
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/test/resources/log4j.properties
@@ -0,0 +1,8 @@
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.Target=System.out
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} [%t] %n%m%n
+
+#Loggers
+log4j.rootLogger=info, console
+log4j.logger.org.apache.stratos.adc.mgt=trace
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/test/resources/policies-1.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/test/resources/policies-1.xml b/components/org.apache.stratos.adc.mgt/src/test/resources/policies-1.xml
new file mode 100644
index 0000000..7dd37d5
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/test/resources/policies-1.xml
@@ -0,0 +1,22 @@
+<policies>
+	<policy name="single" isDefault="true">
+		<description>Single - Instances: Min 1, Max 1</description>
+		<min_app_instances>1</min_app_instances>
+		<max_app_instances>1</max_app_instances>
+		<max_requests_per_second>5</max_requests_per_second>
+		<alarming_upper_rate>0.7</alarming_upper_rate>
+		<alarming_lower_rate>0.2</alarming_lower_rate>
+		<scale_down_factor>0.25</scale_down_factor>
+		<rounds_to_average>2</rounds_to_average>
+	</policy>
+	<policy name="elastic" isDefault="false">
+		<description>Elastic - Instances: Min 1, Max 4</description>
+		<min_app_instances>1</min_app_instances>
+		<max_app_instances>4</max_app_instances>
+		<max_requests_per_second>5</max_requests_per_second>
+		<alarming_upper_rate>0.7</alarming_upper_rate>
+		<alarming_lower_rate>0.2</alarming_lower_rate>
+		<scale_down_factor>0.25</scale_down_factor>
+		<rounds_to_average>2</rounds_to_average>
+	</policy>
+</policies>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.topology.mgt/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/2.1.3/pom.xml b/components/org.apache.stratos.adc.topology.mgt/2.1.3/pom.xml
deleted file mode 100644
index 2024ba8..0000000
--- a/components/org.apache.stratos.adc.topology.mgt/2.1.3/pom.xml
+++ /dev/null
@@ -1,137 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-       Licensed to the Apache Software Foundation (ASF) under one
-       or more contributor license agreements.  See the NOTICE file
-       distributed with this work for additional information
-       regarding copyright ownership.  The ASF licenses this file
-       to you under the Apache License, Version 2.0 (the
-       "License"); you may not use this file except in compliance
-       with the License.  You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing,
-       software distributed under the License is distributed on an
-       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-       KIND, either express or implied.  See the License for the
-       specific language governing permissions and limitations
-       under the License.
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <groupId>org.apache.stratos</groupId>
-    <artifactId>org.apache.stratos.adc.topology.mgt</artifactId>
-    <packaging>bundle</packaging>
-    <version>2.1.3</version>
-    <name>Apache Stratos - Topology Management</name>
-    <url>http://apache.org</url>
-    
-    <dependencies>
-        <!-- <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.mediation.initializer</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency> -->
-        <!-- <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.mediation.dependency.mgt</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency> -->
-        <dependency>
-            <groupId>org.apache.synapse</groupId>
-            <artifactId>synapse-core</artifactId>
-            <version>${synapse.core.version}</version>
-        </dependency>
-         <!--dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2</artifactId>
-            <version>1.6.1.wso2v9</version>
-        </dependency-->
-        <dependency>
-            <groupId>org.apache.axis2</groupId>
-            <artifactId>axis2-kernel</artifactId>
-            <version>${axis2.kernel.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.logging</artifactId>
-	    <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.utils</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.core</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.stratos</groupId>
-            <artifactId>org.apache.stratos.lb.common</artifactId>
-            <version>4.1.3</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.ntask.core</artifactId>
-	    <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-                <groupId>org.wso2.andes.wso2</groupId>
-                <artifactId>andes-client</artifactId>
-                <version>0.13.wso2v3</version>
-            </dependency>
-        <dependency>
-                <groupId>org.apache.geronimo.specs.wso2</groupId>
-                <artifactId>geronimo-jms_1.1_spec</artifactId>
-                <version>${orbit.version.geronimo-jms_1.1_spec}</version>
-            </dependency>
-    </dependencies>
-
-    <build>
-        <plugins>
-
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <!-- <Private-Package>
-                        	org.wso2.carbon.stratos.topology.mgt.service.impl.*
-                        </Private-Package> -->
-                        <Export-Package>
-                            org.apache.stratos.adc.topology.mgt.subscriber.*,
-                            org.apache.stratos.adc.topology.mgt.service.*,
-                            org.apache.stratos.adc.topology.mgt.group.mgt.*,
-							org.apache.stratos.adc.topology.mgt.serviceobjects.*
-                        </Export-Package>
-                        <Import-Package>
-                            org.apache.stratos.lb.common.*; version=4.1.3,
-                            org.apache.stratos.registry.core.service; version=1.0.1,
-                            *;resolution:=optional
-                        </Import-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-</project>


[10/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/pom.xml b/components/org.apache.stratos.mediator.autoscale/pom.xml
new file mode 100644
index 0000000..e07b9d0
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/pom.xml
@@ -0,0 +1,135 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     ~  Licensed to the Apache Software Foundation (ASF) under one
+     ~  or more contributor license agreements.  See the NOTICE file
+     ~  distributed with this work for additional information
+     ~  regarding copyright ownership.  The ASF licenses this file
+     ~  to you under the Apache License, Version 2.0 (the
+     ~  "License"); you may not use this file except in compliance
+     ~  with the License.  You may obtain a copy of the License at
+     ~
+     ~    http://www.apache.org/licenses/LICENSE-2.0
+     ~
+     ~  Unless required by applicable law or agreed to in writing,
+     ~  software distributed under the License is distributed on an
+     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+     ~  KIND, either express or implied.  See the License for the
+     ~  specific language governing permissions and limitations
+     ~  under the License.
+     ~
+ -->
+
+
+<!--
+We need to modify this file since this copied from branch
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.apache.stratos</groupId>
+    <artifactId>org.apache.stratos.mediator.autoscale</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Autoscale Mediator BE</name>
+    <url>http://apache.org</url>
+
+    <build>
+        <plugins>
+			<plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            !org.org.apache.stratos.mediator.autoscale.lbautoscale.internal,
+                            org.apache.stratos.mediator.autoscale.*
+                        </Export-Package>
+                        <Private-Package>org.apache.stratos.mediator.autoscale.lbautoscale.internal</Private-Package>
+                        <Import-Package>
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            !org.apache.commons.logging,
+                            org.apache.commons.logging; version=0.0.0,
+                            org.apache.axis2.*,
+                            org.apache.synapse.*,
+                            org.wso2.carbon.task.*; version=0.0.0,
+                            org.wso2.carbon.core.*,
+                            org.apache.stratos.lb.common.*,
+                            org.apache.stratos.load.balance.cartridge.autoscaler.service.stub.*; version=0.0.0,
+                            org.wso2.carbon.utils.*,
+                            org.apache.axiom.om; version="${axiom.osgi.version.range}",
+                            org.apache.stratos.cloud.controller.*,
+                            *; resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+          <groupId>org.apache.axis2.wso2</groupId>
+          <artifactId>axis2</artifactId>
+          <version>1.6.1.wso2v9</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-core</artifactId>
+            <version>${synapse.core.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.load.balance.cartridge.autoscaler.service.stub</artifactId>
+            <version>${apache.stratos.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.lb.common</artifactId>
+            <version>${apache.stratos.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.cloud.controller</artifactId>
+            <version>${apache.stratos.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.task</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-tasks</artifactId>
+            <version>2.1.1-wso2v4</version>
+        </dependency>
+
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
new file mode 100644
index 0000000..c535489
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
@@ -0,0 +1,86 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.mediator.autoscale.lbautoscale.callables;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+import java.util.concurrent.Callable;
+
+/** Performing sanity checks for each service domain, sub domain combination **/
+public class AppNodeSanityCheckCallable implements Callable<Boolean> {
+
+    private static final Log log = LogFactory.getLog(AppNodeSanityCheckCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    private AppDomainContext appDomainContext;
+    private ServiceConfiguration serviceConfig;
+    
+    public AppNodeSanityCheckCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+        this.appDomainContext = appCtxt;
+        serviceConfig =
+                AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig().getServiceConfig(this.domain,
+                    this.subDomain);
+    }
+    
+    @Override
+    public Boolean call() throws Exception {
+
+        if (appDomainContext != null) {
+            int currentInstances = 0;
+            // we're considering both running and pending instance count
+            currentInstances = appDomainContext.getInstances();
+
+            int requiredInstances = serviceConfig.getMinAppInstances();
+
+            // we try to maintain the minimum number of instances required
+            if (currentInstances < requiredInstances) {
+                log.debug("App domain Sanity check failed for " +
+                    AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+                        " . Current instances: " +
+                        currentInstances +
+                        ". Required instances: " +
+                        requiredInstances);
+
+                int diff = requiredInstances - currentInstances;
+
+                // Launch diff number of App instances
+                log.debug("Launching " +
+                    diff +
+                    " App instances for " +AutoscaleUtil.domainSubDomainString(domain, subDomain));
+
+                // FIXME: should we need to consider serviceConfig.getInstancesPerScaleUp()?
+                AutoscaleUtil.runInstances(client, appDomainContext, this.domain, this.subDomain, diff);
+            }
+        }
+
+        return true;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
new file mode 100644
index 0000000..84705bb
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
@@ -0,0 +1,241 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.callables;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.state.check.TerminatingInstancesStateChecker;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+import java.util.concurrent.Callable;
+
+/** Take auto-scaling decisions for each service domain, sub domain combination **/
+public class AutoscaleDeciderCallable implements Callable<Boolean> {
+
+    private static final Log log = LogFactory.getLog(AutoscaleDeciderCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    private AppDomainContext appDomainContext;
+    private ServiceConfiguration serviceConfig;
+    private String clusterStr;
+    
+    public AutoscaleDeciderCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+        this.appDomainContext = appCtxt;
+        clusterStr = AutoscaleUtil.domainSubDomainString(domain, subDomain);
+    }
+    
+    @Override
+    public Boolean call() throws Exception {
+
+        // expire tokens
+        if (appDomainContext != null) {
+            appDomainContext.expireRequestTokens();
+
+            serviceConfig = appDomainContext.getServiceConfig();
+
+            appDomainContext.recordRequestTokenListLength();
+            if (!appDomainContext.canMakeScalingDecision()) {
+                return true;
+            }
+
+            long average = appDomainContext.getAverageRequestsInFlight();
+            int runningAppInstances = appDomainContext.getRunningInstanceCount();
+            int terminatingAppInstances = appDomainContext.getTerminatingInstanceCount();
+
+            int maxRPS = serviceConfig.getMaxRequestsPerSecond();
+            double taskInterval =
+                AutoscalerTaskDSHolder
+                    .getInstance()
+                    .getWholeLoadBalancerConfig()
+                    .getLoadBalancerConfig()
+                    .getAutoscalerTaskInterval() / (double)1000;
+            double aur = serviceConfig.getAlarmingUpperRate();
+            double alr = serviceConfig.getAlarmingLowerRate();
+            double scaleDownFactor = serviceConfig.getScaleDownFactor();
+
+            // scale up early
+            double maxhandleableReqs = maxRPS * taskInterval * aur;
+            // scale down slowly
+            double minhandleableReqs = maxRPS * taskInterval * alr * scaleDownFactor;
+
+            if (log.isDebugEnabled()) {
+                log.debug(clusterStr +": Average requests in flight: " + average + " **** Handleable requests: " +
+                    (runningAppInstances * maxhandleableReqs));
+            }
+            if (average > (runningAppInstances * maxhandleableReqs) && maxhandleableReqs > 0) {
+                
+                // estimate number of instances we might want to spawn
+                int requiredInstances = (int) Math.ceil(average/maxhandleableReqs);
+                
+                log.debug(clusterStr+" : Required instance count: "+requiredInstances);
+                
+                // current average is higher than that can be handled by current nodes.
+                scaleUp(requiredInstances - runningAppInstances);
+            } else if (terminatingAppInstances == 0 && average < ((runningAppInstances - 1) * minhandleableReqs)) {
+                // current average is less than that can be handled by (current nodes - 1).
+                scaleDown();
+            }
+        }
+
+        return true;
+    }
+
+    private void scaleDown() {
+
+        int runningInstances = appDomainContext.getRunningInstanceCount();
+//        int pendingInstances = appDomainContext.getPendingInstanceCount();
+        int terminatingInstances = appDomainContext.getTerminatingInstanceCount();
+        int minAppInstances = serviceConfig.getMinAppInstances();
+//        int serverStartupDelay = AutoscalerTaskDSHolder
+//                                            .getInstance()
+//                                            .getWholeLoadBalancerConfig()
+//                                            .getLoadBalancerConfig()
+//                                            .getServerStartupDelay();
+
+        if ( (runningInstances - terminatingInstances) > minAppInstances) {
+
+            if (log.isDebugEnabled()) {
+                log.debug("Scale Down - " +
+                    clusterStr +
+                        ". Running instances:" +
+                        runningInstances +
+                        ". Terminating instances: " +
+                        terminatingInstances +
+                        ". Min instances:" +
+                        minAppInstances);
+            }
+            // ask to scale down
+            try {
+                if (client.terminateInstance(domain, subDomain)) {
+                    
+                    Thread th = new Thread(new TerminatingInstancesStateChecker(appDomainContext, domain, subDomain));
+                    th.start();
+                    
+//                        log.debug(clusterStr +": There's an instance who's in shutting down state " +
+//                            "(but still not left ELB), hence we should wait till " +
+//                            "it leaves the cluster.");
+//
+//                        int totalWaitedTime = 0;
+//
+//                        log.debug(clusterStr +": Task will wait maximum of (milliseconds) : " +
+//                            serverStartupDelay +
+//                                ", to let the member leave the cluster.");
+//                        
+//                        // for each sub domain, get the clustering group management agent
+//                        GroupManagementAgent agent =
+//                            AutoscalerTaskDSHolder.getInstance().getAgent()
+//                                .getGroupManagementAgent(domain,
+//                                    subDomain);
+//
+//                        // we give some time for the server to be terminated, we'll check time to time
+//                        // whether the instance has actually left the cluster.
+//                        while (agent.getMembers().size() == runningInstances &&
+//                            totalWaitedTime < serverStartupDelay) {
+//
+//                            try {
+//                                Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
+//                            } catch (InterruptedException ignore) {
+//                            }
+//
+//                            totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
+//                        }
+//
+//                        log.debug(clusterStr+ " : task waited for (milliseconds) : " + totalWaitedTime);
+//
+//                        // we recalculate number of alive instances
+//                        runningInstances = agent.getMembers().size();
+//                        
+//                        appDomainContext.setRunningInstanceCount(runningInstances);
+//
+//                        log.debug(clusterStr+" : New running instance count: " + runningInstances);
+                }
+
+            } catch (Exception e) {
+                log.error("Instance termination failed for " + clusterStr, e);
+            }
+        }
+
+    }
+
+    private void scaleUp(int requiredInstanceCount) {
+
+        int maxAppInstances = serviceConfig.getMaxAppInstances();
+//        int instancesPerScaleUp = serviceConfig.getInstancesPerScaleUp();
+//        int runningInstances = appDomainContext.getRunningInstanceCount();
+//        int pendingInstances = appDomainContext.getPendingInstanceCount();
+        int totalInstanceCount = appDomainContext.getInstances();
+        
+        log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain)+ " - Total Running/Pending instance count: "+totalInstanceCount);
+        
+        if(maxAppInstances > totalInstanceCount){
+            
+            int availableQuotaOfInstances = maxAppInstances - totalInstanceCount;
+            
+            log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain)+ " - Available Quota of Instances: "+availableQuotaOfInstances);
+            
+            requiredInstanceCount = requiredInstanceCount <= availableQuotaOfInstances ? requiredInstanceCount : availableQuotaOfInstances;
+            
+            log.debug(clusterStr + " - Going to start " +
+                    requiredInstanceCount + " instance/s.");
+
+                AutoscaleUtil.runInstances(client, appDomainContext, domain, subDomain,
+                    requiredInstanceCount);
+                
+        } else if (totalInstanceCount > maxAppInstances) {
+            log.fatal("Number of running instances has over reached the maximum limit of " +
+                maxAppInstances + " of " + clusterStr);
+        }
+
+//        int failedInstances = 0;
+//        if (runningInstances < maxAppInstances && pendingInstances == 0) {
+//
+//            log.debug(clusterStr + " - Going to start " +
+//                    requiredInstanceCount + " instance/s. Running instances:" + runningInstances);
+//
+//                AutoscaleUtil.runInstances(client, appDomainContext, domain, subDomain,
+//                    requiredInstanceCount);
+
+//            if (successfullyStarted != instancesPerScaleUp) {
+//                failedInstances = instancesPerScaleUp - successfullyStarted;
+//                if (log.isDebugEnabled()) {
+//                    log.debug(successfullyStarted +
+//                        " instances successfully started and\n" + failedInstances +
+//                        " instances failed to start for " + clusterStr);
+//                }
+//            }
+//
+//            // we increment the pending instance count
+//            // appDomainContext.incrementPendingInstances(instancesPerScaleUp);
+//            else {
+//                log.debug("Successfully started " + successfullyStarted +
+//                    " instances of " + clusterStr);
+//            }
+
+       
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
new file mode 100644
index 0000000..90c2c3a
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
@@ -0,0 +1,78 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.callables;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+/** Calculate instances of each service domain, sub domain combination **/
+public class InstanceCountCallable implements Callable<Boolean> {
+
+    private static final Log log = LogFactory.getLog(InstanceCountCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    private AppDomainContext appCtxt;
+    private ExecutorService executor = Executors.newFixedThreadPool(10);
+    
+    public InstanceCountCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+        this.appCtxt = appCtxt;
+    }
+    
+    @Override
+    public Boolean call() throws Exception {
+        log.debug("Computation of instance counts started for domain: " + this.domain +
+            " and sub domain: " + this.subDomain);
+
+        Callable<Integer> worker = new RunningInstanceCountCallable(this.domain, this.subDomain);
+        Future<Integer> runningInstanceCount = executor.submit(worker);
+
+//        worker = new PendingInstanceCountCallable(this.domain, this.subDomain, client);
+//        Future<Integer> pendingInstanceCount = executor.submit(worker);
+
+        int runningInstances = 0, pendingInstances = 0;
+        if (appCtxt != null) {
+
+            try {
+                // get the values of Callables
+                runningInstances = runningInstanceCount.get();
+                pendingInstances = appCtxt.getPendingInstanceCount();
+            } catch (Exception e) {
+                // no need to throw
+                log.error(e.getMessage(), e);
+            }
+
+            appCtxt.setRunningInstanceCount(runningInstances);
+            appCtxt.setPendingInstanceCount(pendingInstances);
+            
+        }
+        return true;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
new file mode 100644
index 0000000..27cf50e
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
@@ -0,0 +1,65 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.callables;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+
+import java.util.concurrent.Callable;
+
+/** Calculate pending instances of each service domain, sub domain combination **/
+public class PendingInstanceCountCallable implements Callable<Integer> {
+
+    private static final Log log = LogFactory.getLog(PendingInstanceCountCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    
+    public PendingInstanceCountCallable(String domain, String subDomain, CloudControllerClient client){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+    }
+    
+    @Override
+    public Integer call() throws Exception {
+        int pendingInstanceCount = 0;
+
+        try {
+            pendingInstanceCount =
+                client.getPendingInstanceCount(this.domain,
+                    this.subDomain);
+
+        } catch (Exception e) {
+            log.error("Failed to retrieve pending instance count for domain: " +
+                this.domain + " and sub domain: " + this.subDomain, e);
+        }
+
+        log.debug("Pending instance count for domain: " +
+            this.domain +
+            ", sub domain: " +
+            this.subDomain +
+            " is " +
+            pendingInstanceCount);
+
+        return pendingInstanceCount;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
new file mode 100644
index 0000000..3bc3db5
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
@@ -0,0 +1,68 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.callables;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+import java.util.concurrent.Callable;
+
+/** Calculate running instances of each service domain, sub domain combination **/
+public class RunningInstanceCountCallable implements Callable<Integer> {
+
+    private static final Log log = LogFactory.getLog(RunningInstanceCountCallable.class);
+    private String domain;
+    private String subDomain;
+    
+    public RunningInstanceCountCallable(String domain, String subDomain){
+        this.domain = domain;
+        this.subDomain = subDomain;
+    }
+    
+    @Override
+    public Integer call() throws Exception {
+        int runningInstances;
+        // for each sub domain, get the clustering group management agent
+        GroupManagementAgent agent =
+            AutoscalerTaskDSHolder.getInstance().getAgent()
+                .getGroupManagementAgent(this.domain,
+                    this.subDomain);
+
+        // if it isn't null
+        if (agent != null) {
+            // we calculate running instance count for this service domain
+            runningInstances = agent.getMembers().size();
+        } else {
+            // if agent is null, we assume no service instances are running
+            runningInstances = 0;
+        }
+
+        log.debug("Running instance count for domain: " +
+            this.domain +
+                ", sub domain: " +
+                this.subDomain +
+                " is " +
+                runningInstances);
+        
+        return runningInstances;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
new file mode 100644
index 0000000..ec9e1bb
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
@@ -0,0 +1,66 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.clients;
+
+/**
+ * Each Implementation which provides access to Cloud Controller, should implement this interface.
+ */
+public abstract class CloudControllerClient {
+
+    /**
+     * Initializes the client.
+     */
+    public abstract void init();
+    
+    /**
+     * Should start an instance.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return Public IP of the spawned instance.
+     * @throws Exception 
+     */
+    public abstract String startInstance(String domainName, String subDomainName) throws Exception;
+    
+    /**
+     * Terminates an instance belongs to the given cluster.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return whether the termination is successful or not.
+     * @throws Exception
+     */
+    public abstract boolean terminateInstance(String domainName, String subDomainName) throws Exception;
+    
+    /**
+     * Terminates lastly spawned instance of the given cluster.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return whether the termination is successful or not.
+     * @throws Exception
+     */
+    public abstract boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception;
+    
+    /**
+     * Return pending instance count of the given cluster.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return pending instance count.
+     * @throws Exception
+     */
+    public abstract int getPendingInstanceCount(String domainName, String subDomainName) throws Exception;
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
new file mode 100644
index 0000000..907a894
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
@@ -0,0 +1,82 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.clients;
+
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cloud.controller.interfaces.CloudControllerService;
+
+/**
+ * This is the client class this calls Autoscaler service.
+ */
+public class CloudControllerOsgiClient extends CloudControllerClient {
+
+    private CloudControllerService cloudControllerService;
+
+    private static final Log log = LogFactory.getLog(CloudControllerOsgiClient.class);
+
+    // public CloudControllerStubClient(String epr) throws AxisFault {
+    //
+    // try {
+    //
+    // stub = new CloudControllerServiceStub(epr);
+    // stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(90000);
+    //
+    // } catch (AxisFault axisFault) {
+    // String msg =
+    // "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
+    // log.error(msg, axisFault);
+    // throw new AxisFault(msg, axisFault);
+    // }
+    // }
+
+    // public boolean init(boolean isSpi) throws Exception {
+    //
+    // return stub.initAutoscaler(isSpi);
+    // }
+
+    public String startInstance(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.startInstance(domainName, subDomainName);
+    }
+
+    public boolean terminateInstance(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.terminateInstance(domainName, subDomainName);
+    }
+
+    public boolean
+        terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.terminateLastlySpawnedInstance(domainName, subDomainName);
+    }
+
+    public int getPendingInstanceCount(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.getPendingInstanceCount(domainName, subDomainName);
+    }
+
+    @Override
+    public void init() {
+
+        cloudControllerService = AutoscalerTaskDSHolder.getInstance().getCloudControllerService();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
new file mode 100644
index 0000000..34954e9
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
@@ -0,0 +1,93 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.clients;
+
+import org.apache.axis2.AxisFault;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cloud.controller.stub.CloudControllerServiceStub;
+
+/**
+ * This is the client class this calls Autoscaler service.
+ */
+public class CloudControllerStubClient extends CloudControllerClient {
+
+    private CloudControllerServiceStub stub;
+    private static final String CLOUD_CONTROLLER_EPR = AutoscalerTaskDSHolder.getInstance().getLoadBalancerConfig().getAutoscalerServiceEpr();
+
+    private static final Log log = LogFactory.getLog(CloudControllerStubClient.class);
+
+    // public CloudControllerStubClient(String epr) throws AxisFault {
+    //
+    // try {
+    //
+    // stub = new CloudControllerServiceStub(epr);
+    // stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(90000);
+    //
+    // } catch (AxisFault axisFault) {
+    // String msg =
+    // "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
+    // log.error(msg, axisFault);
+    // throw new AxisFault(msg, axisFault);
+    // }
+    // }
+
+    // public boolean init(boolean isSpi) throws Exception {
+    //
+    // return stub.initAutoscaler(isSpi);
+    // }
+
+    public String startInstance(String domainName, String subDomainName) throws Exception {
+
+        return stub.startInstance(domainName, subDomainName);
+    }
+
+    public boolean terminateInstance(String domainName, String subDomainName) throws Exception {
+
+        return stub.terminateInstance(domainName, subDomainName);
+    }
+
+    public boolean
+        terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception {
+
+        return stub.terminateLastlySpawnedInstance(domainName, subDomainName);
+    }
+
+    public int getPendingInstanceCount(String domainName, String subDomainName) throws Exception {
+
+        return stub.getPendingInstanceCount(domainName, subDomainName);
+    }
+
+    @Override
+    public void init() {
+
+        try {
+
+            stub = new CloudControllerServiceStub(CLOUD_CONTROLLER_EPR);
+            stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RuntimeException(msg, axisFault);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/AppDomainContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/AppDomainContext.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/AppDomainContext.java
new file mode 100644
index 0000000..f8155a7
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/AppDomainContext.java
@@ -0,0 +1,170 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.context;
+
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+
+
+/**
+ * Contextual information related to autoscaling for a particular clustering domain
+ */
+public class AppDomainContext extends LoadBalancerContext{
+
+    private static final long serialVersionUID = 6582721801663800609L;
+
+    private static final Log log = LogFactory.getLog(AppDomainContext.class);
+
+    /**
+     * Request tokens of requests in flight
+     * <p/>
+     * Key - request token ID, Value - message received time
+     */
+    private Map<String, Long> requestTokens = new ConcurrentHashMap<String, Long>();
+    private List<Integer> requestTokenListLengths;
+    private LoadBalancerConfiguration.ServiceConfiguration serviceConfig;
+
+    public AppDomainContext(LoadBalancerConfiguration.ServiceConfiguration serviceConfig) {
+        this.serviceConfig = serviceConfig;
+        requestTokenListLengths = new Vector<Integer>(serviceConfig.getRoundsToAverage());
+    }
+
+    public LoadBalancerConfiguration.ServiceConfiguration getServiceConfig() {
+        return serviceConfig;
+    }
+
+    /**
+     * If there is insufficient number of messages we cannot make a scaling decision.
+     *
+     * @return true - if a scaling decision can be made
+     */
+    public boolean canMakeScalingDecision() {
+        return requestTokenListLengths.size() >= serviceConfig.getRoundsToAverage();
+    }
+
+    public void addRequestToken(String tokenId) {
+        requestTokens.put(tokenId, System.currentTimeMillis());
+        if (log.isDebugEnabled()) {
+            log.debug("Request Tokens Added : "+requestTokens.size());
+        }
+    }
+
+    public void removeRequestToken(String tokenId) {
+        requestTokens.remove(tokenId);
+    }
+
+//    public int getRunningInstanceCount() {
+//        return super.getRunningInstanceCount();
+//    }
+
+    /**
+     * This will set the running instance count for this app domain
+     * and also will return the difference of current running instance count and previous count.
+     * @param runningInstanceCount current running instance count
+     * @return difference of current running instance count and previous count.
+     */
+//    public int setRunningInstanceCount(int runningInstanceCount) {
+//        int diff = 0;
+//        
+//        if(this.runningInstanceCount < runningInstanceCount){
+//            diff = runningInstanceCount - this.runningInstanceCount;
+//        }
+//        
+//        this.runningInstanceCount = runningInstanceCount;
+//        
+//        return diff;
+//    }
+
+    public void expireRequestTokens() {
+        for (Map.Entry<String, Long> entry : requestTokens.entrySet()) {
+            if (System.currentTimeMillis() - entry.getValue() >= serviceConfig.getMessageExpiryTime()) {
+                requestTokens.remove(entry.getKey());
+                if (log.isDebugEnabled()) {
+                    log.debug("Request Tokens Expired : " + requestTokens.get(entry.getKey()));
+                }
+            }
+        }
+    }
+
+    public void recordRequestTokenListLength() {
+        if (requestTokenListLengths.size() >= serviceConfig.getRoundsToAverage()) {
+            int count = requestTokenListLengths.remove(0);
+            if (log.isDebugEnabled()) {
+                log.debug("Request Tokens Removed : " + count);
+            }
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Request Tokens Added : " + requestTokens.size());
+        }
+        requestTokenListLengths.add(requestTokens.size());
+    }
+
+
+//    public synchronized int getPendingInstances() {
+//        return pendingInstances;
+//    }
+
+//    public synchronized void incrementPendingInstances() {
+//        this.pendingInstances++;
+//    }
+
+//    public synchronized void decrementPendingInstancesIfNotZero(int diff) {
+//        
+//        while (diff > 0 && this.pendingInstances > 0 ){
+//            this.pendingInstances--;
+//            diff--;
+//        }
+//        
+//    }
+    
+//    public synchronized int getInstances() {
+//        return runningInstanceCount + pendingInstances;
+//    }
+
+    /**
+     * Get the average requests in flight, averaged over the number of  of observations rounds
+     *
+     * @return number of average requests in flight. -1 if there no requests were received
+     */
+    public long getAverageRequestsInFlight() {
+        long total = 0;
+        for (Integer messageQueueLength : requestTokenListLengths) {
+            total += messageQueueLength;
+        }
+        int size = requestTokenListLengths.size();
+        if (size == 0) {
+            return -1; // -1 means that no requests have been received
+        }
+        
+        if (log.isDebugEnabled()) {
+            log.debug("Total Tokens : "+total+ " : Size: "+size);
+        }
+        return (long) total / size;
+    }
+
+
+//    public synchronized void resetRunningPendingInstances() {
+//        pendingInstances = 0;
+//        runningInstanceCount = 0;
+//    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
new file mode 100644
index 0000000..b6a6d9b
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
@@ -0,0 +1,104 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.context;
+
+import java.io.Serializable;
+
+/**
+ * Contextual information related to autoscaling for a particular domain
+ */
+public class LoadBalancerContext implements Serializable{
+
+    private static final long serialVersionUID = -2022110665957598060L;
+    private int runningInstances;
+    private int pendingInstances;
+    private int terminatingInstances;
+    
+    public synchronized int getTerminatingInstanceCount() {
+        return terminatingInstances;
+    }
+    
+    public synchronized int getRunningInstanceCount() {
+        return runningInstances;
+    }
+    
+    public synchronized int getPendingInstanceCount() {
+        return pendingInstances;
+    }
+
+    /**
+     * This will set the running instance count for a domain
+     * and also will return the difference of current running instance count and previous count.
+     * @param runningInstanceCount current running instance count
+     * @return difference of current running instance count and previous count.
+     */
+    public synchronized int setRunningInstanceCount(int count) {
+        int diff = 0;
+
+        if (this.runningInstances < count) {
+            diff = count - this.runningInstances;
+        }
+
+        this.runningInstances = count;
+
+        return diff;
+    }
+
+    public synchronized int getInstances() {
+        return runningInstances + pendingInstances;
+    }
+    
+    public synchronized void setPendingInstanceCount(int count) {
+        
+        this.pendingInstances = count;
+    }
+    
+    public synchronized void setTerminatingInstanceCount(int count) {
+        
+        this.terminatingInstances = count;
+    }
+
+    public synchronized void incrementPendingInstances(int diff) {
+
+        this.pendingInstances += diff;
+    }
+    
+    public synchronized void incrementTerminatingInstances(int diff) {
+
+        this.terminatingInstances += diff;
+    }
+    
+    public synchronized void decrementPendingInstancesIfNotZero(int diff) {
+
+        while (diff > 0 && this.pendingInstances > 0) {
+            this.pendingInstances--;
+            diff--;
+        }
+
+    }
+    
+    public synchronized void decrementTerminatingInstancesIfNotZero(int diff) {
+
+        while (diff > 0 && this.terminatingInstances > 0) {
+            this.terminatingInstances--;
+            diff--;
+        }
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
new file mode 100644
index 0000000..41811eb
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
@@ -0,0 +1,325 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.internal;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.Parameter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.apache.stratos.mediator.autoscale.lbautoscale.mediators.AutoscaleInMediator;
+import org.apache.stratos.mediator.autoscale.lbautoscale.mediators.AutoscaleOutMediator;
+import org.apache.stratos.mediator.autoscale.lbautoscale.task.*;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.Mediator;
+import org.apache.synapse.SynapseConstants;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.mediators.base.SequenceMediator;
+import org.apache.synapse.mediators.filters.InMediator;
+import org.apache.synapse.mediators.filters.OutMediator;
+import org.apache.synapse.task.Task;
+import org.apache.synapse.task.TaskConstants;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskScheduler;
+import org.apache.synapse.task.service.TaskManagementService;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.quartz.JobBuilder;
+import org.quartz.JobDetail;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.apache.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * @scr.component name="autoscaler.task.component" immediate="true"
+ * @scr.reference name="carbon.core.configurationContextService"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService"
+ * cardinality="1..1" policy="dynamic"
+ * bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
+ * @scr.reference name="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService"
+ * unbind="unsetRealmService"
+ * @scr.reference name="org.apache.stratos.lb.common"
+ * interface="org.apache.stratos.lb.common.service.LoadBalancerConfigurationService"
+ * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
+ * unbind="unsetLoadBalancerConfigurationService"
+ * @scr.reference name="registry.service"
+ * interface="org.wso2.carbon.registry.core.service.RegistryService"
+ * cardinality="1..1" policy="dynamic"
+ * bind="setRegistryService" unbind="unsetRegistryService"
+ * @scr.reference name="org.apache.stratos.cloud.controller"
+ * interface="org.apache.stratos.cloud.controller.interfaces.CloudControllerService"
+ * cardinality="1..1" policy="dynamic" bind="setCloudControllerService"
+ * unbind="unsetCloudControllerService"
+ */
+public class AutoscalerTaskServiceComponent {
+
+    private static final Log log = LogFactory.getLog(AutoscalerTaskServiceComponent.class);
+    private ConfigurationContext configurationContext = null;
+
+    protected void activate(ComponentContext context) {
+    	
+    	try{
+
+        // read config file
+//        String configURL = System.getProperty(AutoscaleConstants.LOAD_BALANCER_CONFIG);
+//        LoadBalancerConfiguration lbConfig = new LoadBalancerConfiguration();
+//        lbConfig.init(configURL);
+        
+        if(configurationContext == null){
+            String msg = "Configuration context is null. Autoscaler task activation failed.";
+            log.fatal(msg);
+            throw new RuntimeException(msg);
+        }
+
+        // load synapse environment
+        Parameter synEnv =
+                configurationContext.getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_ENV);
+
+        if (synEnv == null || synEnv.getValue() == null ||
+                !(synEnv.getValue() instanceof SynapseEnvironment)) {
+
+            String message = "Unable to initialize the Synapse Configuration : Can not find the ";
+            log.fatal(message + "Synapse Environment");
+            throw new SynapseException(message + "Synapse Environment");
+        }
+
+        SynapseEnvironment synapseEnv = (SynapseEnvironment) synEnv.getValue();
+
+        /** Initializing autoscaleIn and autoscaleOut Mediators.**/
+
+        LoadBalancerConfiguration lbConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
+        // check whether autoscaling is enabled
+        if (lbConfig.getLoadBalancerConfig().isAutoscaleEnabled()) {
+
+            // get the main sequence mediator
+            SequenceMediator mainSequence =
+                    (SequenceMediator) synapseEnv.getSynapseConfiguration().getSequence("main");
+
+            // iterate through its child mediators
+            for (Mediator child : mainSequence.getList()) {
+
+                // find the InMediator
+                if (child instanceof InMediator) {
+                    InMediator inSequence = (InMediator) child;
+
+                    // if the first child of InMediator isn't an AutoscaleInMediator
+                    if (!(inSequence.getList().get(0) instanceof AutoscaleInMediator)) {
+
+                        // we gonna add it!
+                        inSequence.getList().add(0, new AutoscaleInMediator());
+                        if (log.isDebugEnabled()) {
+                            log.debug("Added Mediator: " + inSequence.getChild(0) + "" +
+                                    " to InMediator. Number of child mediators in InMediator" + " is " +
+                                    inSequence.getList().size() + ".");
+                        }
+                    }
+
+                }
+
+                // find the OutMediator
+                if (child instanceof OutMediator) {
+
+                    OutMediator outSequence = (OutMediator) child;
+
+                    // if the first child of OutMediator isn't an AutoscaleOutMediator
+                    if (!(outSequence.getList().get(0) instanceof AutoscaleOutMediator)) {
+
+                        // we gonna add it!
+                        outSequence.getList().add(0, new AutoscaleOutMediator());
+
+                        if (log.isDebugEnabled()) {
+                            log.debug("Added Mediator: " + outSequence.getChild(0) + "" +
+                                    " to OutMediator. Number of child mediators in OutMediator" +
+                                    " is " + outSequence.getList().size() + ".");
+                        }
+
+                    }
+                }
+            }
+
+            /** Initializing Autoscaler Task **/
+
+            BundleContext bundleContext = context.getBundleContext();
+            if (log.isDebugEnabled()) {
+                log.debug("Initiating Autoscaler task service component");
+            }
+
+            if (bundleContext.getServiceReference(TaskManagementService.class.getName()) != null) {
+                bundleContext.registerService(TaskManagementService.class.getName(),
+                        new AutoscalerTaskMgmtAdminService(), null);
+            }
+
+
+            AutoscalerTaskInitializer listener = new AutoscalerTaskInitializer();
+
+            if (bundleContext.getServiceReference(Axis2ConfigurationContextObserver.class.getName()) != null) {
+                bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(),
+                        listener, null);
+            }
+
+            if (configurationContext != null) {
+                TaskScheduler scheduler =
+                        (TaskScheduler) configurationContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER);
+                if (scheduler == null) {
+                    scheduler = new TaskScheduler(TaskConstants.TASK_SCHEDULER);
+                    scheduler.init(null);
+                    configurationContext.setProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER,
+                            scheduler);
+                } else if (!scheduler.isInitialized()) {
+                    scheduler.init(null);
+                }
+            }
+            
+            String autoscalerClass = lbConfig.getLoadBalancerConfig().getAutoscalerTaskClass();
+            Task task;
+            if (autoscalerClass != null) {
+                try {
+                    task = (Task) Class.forName(autoscalerClass).newInstance();
+                } catch (Exception e) {
+                    String msg = "Cannot instantiate Autoscaling Task. Class: " + autoscalerClass
+                    		+". It should implement 'org.apache.synapse.task.Task' and "
+                    		+"'org.apache.synapse.ManagedLifecycle' interfaces.";
+                    log.error(msg, e);
+                    throw new RuntimeException(msg, e);
+                }
+            } else {
+                task = new ServiceRequestsInFlightAutoscaler();
+            }
+
+//            ServiceRequestsInFlightAutoscaler autoscalerTask =
+//                    new ServiceRequestsInFlightAutoscaler();
+
+            ((ManagedLifecycle) task).init(synapseEnv);
+
+            // specify scheduler task details
+            JobBuilder jobBuilder = JobBuilder.newJob(AutoscalingJob.class)
+                .withIdentity("autoscalerJob");
+            JobDetail job = jobBuilder.build();
+
+            Map<String, Object> dataMap = job.getJobDataMap();
+            dataMap.put(AutoscalingJob.AUTOSCALER_TASK, task);
+            dataMap.put(AutoscalingJob.SYNAPSE_ENVI, synapseEnv);
+
+            final TaskDescription taskDescription = new TaskDescription();
+            taskDescription.setTaskClass(ServiceRequestsInFlightAutoscaler.class.getName());
+            taskDescription.setName("autoscaler");
+            //taskDescription.setCount(SimpleTrigger.REPEAT_INDEFINITELY);
+
+            int interval = AutoscalerTaskDSHolder.getInstance().getLoadBalancerConfig().getAutoscalerTaskInterval();
+            taskDescription.setInterval(interval);
+            taskDescription.setStartTime(new Date(System.currentTimeMillis() + (interval*2)));
+
+            TaskSchedulingManager scheduler = new TaskSchedulingManager();
+            scheduler.scheduleTask(taskDescription, dataMap, configurationContext);
+
+
+        } else {
+
+            log.info("Autoscaling is disabled.");
+        }
+    	} catch (Throwable e) {
+            log.error("Failed to activate Autoscaler Task Service Component. ", e);
+        }
+    }
+
+
+    protected void deactivate(ComponentContext ctx) {
+        AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(null);
+        if (log.isDebugEnabled()) {
+            log.debug("Autoscaler task bundle is deactivated");
+        }
+    }
+
+	protected void setCloudControllerService(CloudControllerService cc) {
+        AutoscalerTaskDSHolder.getInstance().setCloudControllerService(cc);
+    }
+    
+    protected void unsetCloudControllerService(CloudControllerService cc) {
+        AutoscalerTaskDSHolder.getInstance().setCloudControllerService(null);
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService context) {
+        if (log.isDebugEnabled()) {
+            log.debug("ConfigurationContextService bound to the Autoscaler task initialization process");
+        }
+        this.configurationContext = context.getServerConfigContext();
+        AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(context);
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
+        if (log.isDebugEnabled()) {
+            log.debug("ConfigurationContextService unbound from the Autoscaler task");
+        }
+        this.configurationContext = null;
+        AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Bound realm service from the Autoscaler task");
+        }
+        AutoscalerTaskDSHolder.getInstance().setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Unbound realm service from the Autoscaler task");
+        }
+        AutoscalerTaskDSHolder.getInstance().setRealmService(null);
+    }
+    
+    protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        AutoscalerTaskDSHolder.getInstance().setLbConfigService(lbConfigSer);
+    }
+    
+    protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        AutoscalerTaskDSHolder.getInstance().setLbConfigService(null);
+    }
+    
+    protected void setRegistryService(RegistryService regService) {
+        if (log.isDebugEnabled()) {
+            log.debug("RegistryService bound to the endpoint component");
+        }
+        try {
+            AutoscalerTaskDSHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
+            AutoscalerTaskDSHolder.getInstance().setGovernanceRegistry(regService.getGovernanceSystemRegistry());
+        } catch (RegistryException e) {
+            log.error("Couldn't retrieve the registry from the registry service");
+        }
+    }
+
+    protected void unsetRegistryService(RegistryService regService) {
+        if (log.isDebugEnabled()) {
+            log.debug("RegistryService unbound from the endpoint component");
+        }
+        AutoscalerTaskDSHolder.getInstance().setConfigRegistry(null);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/RegistryManager.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/RegistryManager.java
new file mode 100644
index 0000000..0f5a03d
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/internal/RegistryManager.java
@@ -0,0 +1,54 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.internal;
+
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.util.DomainMapping;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+
+public class RegistryManager {
+    UserRegistry governanceRegistry = AutoscalerTaskDSHolder.getInstance().getGovernanceRegistry();
+    private static final Log log = LogFactory.getLog(RegistryManager.class);
+    /**
+     *
+     */
+    private Resource resource = null;
+    public static final String HOST_INFO = "hostinfo/";
+    public static final String ACTUAL_HOST = "actual.host";
+
+    public DomainMapping getMapping(String hostName) {
+        DomainMapping domainMapping;
+        try {
+            if (governanceRegistry.resourceExists(HOST_INFO + hostName)) {
+                resource = governanceRegistry.get(HOST_INFO + hostName);
+                domainMapping = new DomainMapping(hostName);
+                domainMapping.setActualHost(resource.getProperty(ACTUAL_HOST));
+                return domainMapping;
+            }
+        } catch (RegistryException e) {
+            log.info("Error while getting registry resource");
+            throw new RuntimeException(e);
+        }
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
new file mode 100644
index 0000000..6ec1da3
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
@@ -0,0 +1,174 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.mediators;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.internal.RegistryManager;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.apache.http.protocol.HTTP;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.synapse.mediators.AbstractMediator;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.apache.stratos.lb.common.cache.URLMappingCache;
+import org.apache.stratos.lb.common.util.DomainMapping;
+
+import java.util.Map;
+
+/**
+ * This Synapse mediator generates a token per request received. These tokens are used for tracking
+ * the number of requests in flight. Once a response is received, the relevant token will be removed
+ * by the {@link AutoscaleOutMediator}
+ *
+ * @see AutoscaleOutMediator
+ */
+public class AutoscaleInMediator extends AbstractMediator implements ManagedLifecycle {
+
+    private LoadBalancerConfiguration lbConfig;
+    private Map<String, HostContext> hostCtxts;
+    /**
+     * keep the size of cache which used to keep hostNames of url mapping.
+     */
+    private URLMappingCache mappingCache;
+    private RegistryManager registryManager;
+    private int sizeOfCache;
+
+    public AutoscaleInMediator() {
+
+        this.lbConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
+        hostCtxts = lbConfig.getHostContextMap();
+        sizeOfCache = lbConfig.getLoadBalancerConfig().getSizeOfCache();
+        mappingCache = URLMappingCache.getInstance(sizeOfCache);
+    }
+
+    public boolean mediate(MessageContext synCtx) {
+
+        if (log.isDebugEnabled()) {
+            log.debug("Mediation started .......... " + AutoscaleInMediator.class.getName());
+
+        }
+
+        ConfigurationContext configCtx =
+                                         ((Axis2MessageContext) synCtx).getAxis2MessageContext()
+                                                                       .getConfigurationContext();
+        String uuid = org.apache.axiom.util.UIDGenerator.generateUID();
+        synCtx.setProperty(AutoscaleConstants.REQUEST_ID, uuid);
+
+        Map<String, Map<String, ?>> appDomainContexts =
+                                                                       AutoscaleUtil.getAppDomainContexts(configCtx,
+                                                                               lbConfig);
+        org.apache.axis2.context.MessageContext axis2MessageContext =
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+        Map<String, String> transportHeaders = (Map<String, String>) axis2MessageContext.
+                getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+        String targetHost = transportHeaders.get(HTTP.TARGET_HOST);
+        
+        String toAddress = synCtx.getTo().getAddress();
+        if (targetHost.contains(":")) {
+            targetHost = targetHost.substring(0, targetHost.indexOf(':'));
+        }
+
+        int tenantId = AutoscaleUtil.getTenantId(synCtx.getTo().toString());
+
+        String domain = null, subDomain = null;
+        
+        log.debug("************ Target Host: "+targetHost + " -- Tenant id : "+tenantId);
+
+        HostContext ctxt = hostCtxts.get(targetHost);
+        
+        if (ctxt == null) {
+
+            DomainMapping domainMapping = mappingCache.getMapping(targetHost);
+            if (domainMapping == null) {
+                registryManager = new RegistryManager();
+                domainMapping = registryManager.getMapping(targetHost);
+                mappingCache.addValidMapping(targetHost, domainMapping);
+            }
+            if (domainMapping != null) {
+
+                String actualHost = domainMapping.getActualHost();
+
+                // get the HostContext from the actual host name in the case of domain 
+                // mapping.
+                ctxt = hostCtxts.get(actualHost);
+
+            }
+        }
+
+        if (ctxt == null) {
+            log.debug("Host Context is null.");
+        	// we don't need to do anything 
+        	return true;
+        }
+
+
+        // gets the corresponding domain
+        domain = ctxt.getDomainFromTenantId(tenantId);
+        synCtx.setProperty(AutoscaleConstants.TARGET_DOMAIN, domain);
+
+        // gets the corresponding sub domain
+        subDomain = ctxt.getSubDomainFromTenantId(tenantId);
+        synCtx.setProperty(AutoscaleConstants.TARGET_SUB_DOMAIN, subDomain);
+
+        if (appDomainContexts.get(domain) == null) {
+            // if we do not find a correct context, we just ignore
+            log.debug("AppDomainContext not found for domain " + domain);
+
+        } else {
+            AppDomainContext appDomainContext = (AppDomainContext) appDomainContexts.get(domain).get(subDomain);
+
+            if (appDomainContext != null) {
+                appDomainContext.addRequestToken(uuid);
+                System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");
+
+            } else {
+                // if we do not find a correct context, we just ignore
+                log.debug("AppDomainContext not found for sub domain: " + subDomain +
+                          " of domain: " + domain);
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public void destroy() {
+
+        log.info("Mediator destroyed! " + AutoscaleInMediator.class.getName());
+    }
+
+    @Override
+    public void init(SynapseEnvironment arg0) {
+
+        if (log.isDebugEnabled()) {
+            log.debug("Mediator initialized! " + AutoscaleInMediator.class.getName());
+        }
+    }
+    
+    private void throwException(String msg){
+        log.error(msg);
+        throw new RuntimeException(msg);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
new file mode 100644
index 0000000..3640c08
--- /dev/null
+++ b/components/org.apache.stratos.mediator.autoscale/src/main/java/org/apache/stratos/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
@@ -0,0 +1,78 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.mediator.autoscale.lbautoscale.mediators;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.synapse.mediators.AbstractMediator;
+import org.apache.stratos.mediator.autoscale.lbautoscale.context.AppDomainContext;
+
+import java.util.Map;
+
+/**
+ * This Synapse mediator removes the request token generated by the {@link AutoscaleInMediator}
+ * 
+ * @see AutoscaleInMediator
+ */
+public class AutoscaleOutMediator extends AbstractMediator implements ManagedLifecycle {
+
+    public boolean mediate(MessageContext synCtx) {
+
+        log.debug("Mediation started ....... " + AutoscaleOutMediator.class.getName());
+
+        ConfigurationContext configCtx =
+            ((Axis2MessageContext) synCtx).getAxis2MessageContext().getConfigurationContext();
+
+        String domain = (String) synCtx.getProperty(AutoscaleConstants.TARGET_DOMAIN);
+        // gets the corresponding sub domain
+        String subDomain = (String) synCtx.getProperty(AutoscaleConstants.TARGET_SUB_DOMAIN);
+        
+        String tokenId = (String) synCtx.getProperty(AutoscaleConstants.REQUEST_ID);
+        @SuppressWarnings("unchecked")
+        Map<String, Map<String, AppDomainContext>> appDomainContexts =
+            (Map<String, Map<String, AppDomainContext>>) configCtx.getPropertyNonReplicable(AutoscaleConstants.APP_DOMAIN_CONTEXTS);
+        AppDomainContext appDomainContext = null ;
+        
+        if(appDomainContexts.get(domain) != null){
+        	appDomainContext = appDomainContexts.get(domain).get(subDomain);
+        }
+        
+        if (appDomainContext != null) {
+            appDomainContext.removeRequestToken(tokenId);
+            System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");
+        } else {
+            log.debug("AppDomainContext not found for domain " + domain+" and sub domain : "+subDomain);
+        }
+        return true;
+    }
+
+    @Override
+    public void destroy() {
+        log.debug("Autoscale out mediator destroyed...");
+    }
+
+    @Override
+    public void init(SynapseEnvironment arg0) {
+        log.debug("Autoscale out mediator started...");
+    }
+}


[05/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/util/TenantMgtEmailSenderUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/util/TenantMgtEmailSenderUtil.java b/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/util/TenantMgtEmailSenderUtil.java
deleted file mode 100644
index 6b64019..0000000
--- a/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/util/TenantMgtEmailSenderUtil.java
+++ /dev/null
@@ -1,482 +0,0 @@
-/*
- * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.stratos.tenant.mgt.email.sender.util;
-
-import org.apache.stratos.tenant.mgt.email.sender.internal.DataHolder;
-import org.wso2.carbon.email.sender.api.EmailSender;
-import org.wso2.carbon.email.sender.api.EmailSenderConfiguration;
-import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber;
-import org.wso2.carbon.email.verification.util.EmailVerifierConfig;
-import org.wso2.carbon.registry.core.RegistryConstants;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.registry.core.utils.UUIDGenerator;
-import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
-import org.wso2.carbon.stratos.common.constants.StratosConstants;
-import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil;
-import org.wso2.carbon.stratos.common.util.CommonUtil;
-import org.wso2.carbon.user.api.Tenant;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-import org.wso2.carbon.utils.AuthenticationObserver;
-import org.wso2.carbon.utils.CarbonUtils;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.osgi.framework.BundleContext;
-import org.osgi.util.tracker.ServiceTracker;
-
-/**
- * Utility methods for the email sender component
- */
-public class TenantMgtEmailSenderUtil {
-
-    private static final Log log = LogFactory.getLog(TenantMgtEmailSenderUtil.class);
-    
-    private static EmailSender successMsgSender;
-    private static EmailSender tenantCreationNotifier;
-    private static EmailSender tenantActivationNotifier;
-    private static EmailSender passwordResetMsgSender;
-    private static EmailVerifierConfig emailVerifierConfig;
-    private static EmailVerifierConfig superTenantEmailVerifierConfig = null;
-    
-    public static void init() {
-        initTenantActivatedEmailSender();
-        initSuperTenantNotificationEmailSender();
-        initEmailVerificationSender();
-        initPasswordResetEmailSender();
-    }
-    
-    /**
-     * Sends validation mail to the tenant admin upon the tenant creation
-     *
-     * @param tenantInfoBean    - registered tenant's details
-     * @throws Exception, if the sending mail failed
-     */
-    public static void sendTenantCreationVerification(
-                                              TenantInfoBean tenantInfoBean) throws Exception {
-        String confirmationKey = generateConfirmationKey(tenantInfoBean,
-                DataHolder.getRegistryService().getConfigSystemRegistry(
-                        MultitenantConstants.SUPER_TENANT_ID));
-
-        if (CommonUtil.isTenantActivationModerated()) {
-            requestSuperTenantModeration(tenantInfoBean, confirmationKey);
-        } else {
-            //request for verification
-            requestUserVerification(tenantInfoBean, confirmationKey);
-        }
-    }
-    
-    /**
-     * Emails the tenant admin notifying the account creation.
-     *
-     * @param tenantId tenant Id
-     */
-    public static void notifyTenantInitialActivation(int tenantId) {
-        TenantManager tenantManager = DataHolder.getTenantManager();
-        String firstName = "";
-        String domainName = "";
-        String adminName = "";
-        String email = "";
-        try {
-            Tenant tenant = tenantManager.getTenant(tenantId);
-            domainName = tenant.getDomain();
-            firstName = ClaimsMgtUtil.getFirstName(DataHolder.getRealmService(), tenantId);
-            adminName = tenant.getAdminName();
-            email = tenant.getEmail(); 
-        } catch (Exception e) {
-            String msg = "Unable to get the tenant with the tenant domain";
-            log.error(msg, e);
-            // just catch from here.
-        }
-
-        // load the mail configuration
-        Map<String, String> userParams = new HashMap<String, String>();
-        userParams.put("first-name", firstName);
-        userParams.put("user-name", adminName);
-        userParams.put("domain-name", domainName);
-
-        try {
-            successMsgSender.sendEmail(email, userParams);
-        } catch (Exception e) {
-            // just catch from here..
-            String msg = "Error in sending the notification email.";
-            log.error(msg, e);
-        }
-        
-        // send the notification message to the super tenant
-        notifyTenantActivationToSuperAdmin(domainName, adminName, email);
-    }
-    
-    /**
-     * Emails the super admin notifying the account creation for a new tenant.
-     *
-     * @param tenantInfoBean - tenant details
-     */
-    public static void notifyTenantCreationToSuperAdmin(TenantInfoBean tenantInfoBean) {
-        String notificationEmailAddress = CommonUtil.getNotificationEmailAddress();
-
-        if (notificationEmailAddress.trim().equals("")) {
-            if (log.isDebugEnabled()) {
-                log.debug("No super-admin notification email address is set to notify upon a" +
-                          " tenant registration");
-            }
-            return;
-        }
-
-        Map<String, String> userParams = initializeSuperTenantNotificationParams(
-                tenantInfoBean.getTenantDomain(), tenantInfoBean.getAdmin(), 
-                tenantInfoBean.getEmail());
-
-        try {
-            tenantCreationNotifier.sendEmail(notificationEmailAddress, userParams);
-        } catch (Exception e) {
-            // just catch from here..
-            String msg = "Error in sending the notification email.";
-            log.error(msg, e);
-        }
-    }
-    
-    public static void notifyResetPassword(TenantInfoBean tenantInfoBean) throws Exception {
-        int tenantId = tenantInfoBean.getTenantId();
-        String firstName = ClaimsMgtUtil.getFirstName(DataHolder.getRealmService(), tenantId);
-
-        // load the mail configuration
-        Map<String, String> userParams = new HashMap<String, String>();
-        userParams.put("user-name", tenantInfoBean.getAdmin());
-        userParams.put("first-name", firstName);
-        userParams.put("domain-name", tenantInfoBean.getTenantDomain());
-        userParams.put("password", tenantInfoBean.getAdminPassword());
-
-        try {
-            passwordResetMsgSender.sendEmail(tenantInfoBean.getEmail(), userParams);
-        } catch (Exception e) {
-            // just catch from here..
-            String msg = "Error in sending the notification email.";
-            log.error(msg, e);
-        }
-    }
-    
-    /**
-     * Emails the super admin notifying the account activation for an unactivated tenant.
-     *
-     * @param domainName tenant domain
-     * @param adminName  tenant admin
-     * @param email      tenant's email address
-     */
-    private static void notifyTenantActivationToSuperAdmin(String domainName, String adminName,
-                                                          String email) {
-        String notificationEmailAddress = CommonUtil.getNotificationEmailAddress();
-
-        if (notificationEmailAddress.trim().equals("")) {
-            if (log.isDebugEnabled()) {
-                log.debug("No super-admin notification email address is set to notify upon a"
-                          + " tenant activation");
-            }
-            return;
-        }
-
-        Map<String, String> userParams =
-                initializeSuperTenantNotificationParams(domainName, adminName, email);
-
-        try {
-            tenantActivationNotifier.sendEmail(notificationEmailAddress, userParams);
-        } catch (Exception e) {
-            // just catch from here..
-            String msg = "Error in sending the notification email.";
-            log.error(msg, e);
-        }
-    }
-    
-    /**
-     * generates the confirmation key for the tenant
-     *
-     * @param tenantInfoBean            - tenant details
-     * @param superTenantConfigSystemRegistry
-     *                          - super tenant config system registry.
-     * @return confirmation key
-     * @throws RegistryException if generation of the confirmation key failed.
-     */
-    private static String generateConfirmationKey(TenantInfoBean tenantInfoBean,
-                                                  UserRegistry superTenantConfigSystemRegistry
-                                                  ) throws RegistryException {
-        // generating the confirmation key
-        String confirmationKey = UUIDGenerator.generateUUID();
-        UserRegistry superTenantGovernanceSystemRegistry;
-        try {
-            superTenantGovernanceSystemRegistry =
-                DataHolder.getRegistryService().getGovernanceSystemRegistry(
-                        MultitenantConstants.SUPER_TENANT_ID);
-        } catch (RegistryException e) {
-            String msg = "Exception in getting the governance system registry for the super tenant";
-            log.error(msg, e);
-            throw new RegistryException(msg, e);
-        }
-        Resource resource;
-        String emailVerificationPath = StratosConstants.ADMIN_EMAIL_VERIFICATION_FLAG_PATH +
-                                       RegistryConstants.PATH_SEPARATOR + 
-                                       tenantInfoBean.getTenantId();
-        try {
-            if (superTenantGovernanceSystemRegistry.resourceExists(emailVerificationPath)) {
-                resource = superTenantGovernanceSystemRegistry.get(emailVerificationPath);
-            } else {
-                resource = superTenantGovernanceSystemRegistry.newResource();
-            }
-            resource.setContent(confirmationKey);
-        } catch (RegistryException e) {
-            String msg = "Error in creating the resource or getting the resource" +
-                         "from the email verification path";
-            log.error(msg, e);
-            throw new RegistryException(msg, e);
-        }
-        // email is not validated yet, this prop is used to activate the tenant later.
-        resource.addProperty(StratosConstants.IS_EMAIL_VALIDATED, "false");
-        resource.addProperty(StratosConstants.TENANT_ADMIN, tenantInfoBean.getAdmin());
-        try {
-            superTenantGovernanceSystemRegistry.put(emailVerificationPath, resource);
-        } catch (RegistryException e) {
-            String msg = "Error in putting the resource to the super tenant registry" +
-                         " for the email verification path";
-            log.error(msg, e);
-            throw new RegistryException(msg, e);
-        }
-
-        // Used for * as a Service impl.
-        // Store the cloud service from which the register req. is originated.
-        if (tenantInfoBean.getOriginatedService() != null) {
-            String originatedServicePath =
-                    StratosConstants.ORIGINATED_SERVICE_PATH +
-                    StratosConstants.PATH_SEPARATOR +
-                    StratosConstants.ORIGINATED_SERVICE +
-                    StratosConstants.PATH_SEPARATOR + tenantInfoBean.getTenantId();
-            try {
-                Resource origServiceRes = superTenantConfigSystemRegistry.newResource();
-                origServiceRes.setContent(tenantInfoBean.getOriginatedService());
-                superTenantGovernanceSystemRegistry.put(originatedServicePath, origServiceRes);
-            } catch (RegistryException e) {
-                String msg = "Error in putting the originated service resource "
-                             + "to the governance registry";
-                log.error(msg, e);
-                throw new RegistryException(msg, e);
-            }
-        }
-        initializeRegistry(tenantInfoBean.getTenantId());
-        if (log.isDebugEnabled()) {
-            log.debug("Successfully generated the confirmation key.");
-        }
-        return confirmationKey;
-    }
-    
-    /**
-     * Sends mail for the super tenant for the account moderation. Once super tenant clicks the
-     * link provided in the email, the tenant will be activated.
-     *
-     * @param tenantInfoBean      - the tenant who registered an account
-     * @param confirmationKey confirmation key.
-     * @throws Exception if an exception is thrown from EmailVerificationSubscriber.
-     */
-    private static void requestSuperTenantModeration(TenantInfoBean tenantInfoBean, 
-                                                       String confirmationKey) throws Exception {
-        try {
-            Map<String, String> dataToStore = new HashMap<String, String>();
-            dataToStore.put("email", CommonUtil.getSuperAdminEmail());
-            dataToStore.put("first-name", tenantInfoBean.getFirstname());
-            dataToStore.put("userName", tenantInfoBean.getAdmin());
-            dataToStore.put("tenantDomain", tenantInfoBean.getTenantDomain());
-            dataToStore.put("confirmationKey", confirmationKey);
-
-            DataHolder.getEmailVerificationService().requestUserVerification(
-                    dataToStore, superTenantEmailVerifierConfig);
-            if (log.isDebugEnabled()) {
-                log.debug("Email verification for the tenant registration.");
-            }
-        } catch (Exception e) {
-            String msg = "Error in notifying the super tenant on the account creation for " +
-                         "the domain: " + tenantInfoBean.getTenantDomain();
-            log.error(msg);
-            throw new Exception(msg, e);
-        }
-    }
-    
-    /**
-     * request email verification from the user.
-     *
-     * @param tenantInfoBean - Tenant information
-     * @param confirmationKey confirmation key.
-     * @throws Exception if an exception is thrown from EmailVerificationSubscriber.
-     */
-    private static void requestUserVerification(TenantInfoBean tenantInfoBean, 
-                                                String confirmationKey) throws Exception {
-        try {
-            Map<String, String> dataToStore = new HashMap<String, String>();
-            dataToStore.put("email", tenantInfoBean.getEmail());
-            dataToStore.put("first-name", tenantInfoBean.getFirstname());
-            dataToStore.put("userName", tenantInfoBean.getAdmin());
-            dataToStore.put("tenantDomain", tenantInfoBean.getTenantDomain());
-            dataToStore.put("confirmationKey", confirmationKey);
-
-            EmailVerifcationSubscriber emailVerifier = DataHolder.getEmailVerificationService();
-            emailVerifier.requestUserVerification(dataToStore, emailVerifierConfig);
-            if (log.isDebugEnabled()) {
-                log.debug("Email verification for the tenant registration.");
-            }
-        } catch (Exception e) {
-            String msg = "Error in notifying tenant of domain: " + tenantInfoBean.getTenantDomain();
-            log.error(msg);
-            throw new Exception(msg, e);
-        }
-    }
-    
-    /**
-     * Initializes the registry for the tenant.
-     *
-     * @param tenantId tenant id.
-     */
-    private static void initializeRegistry(int tenantId) {
-        BundleContext bundleContext = DataHolder.getBundleContext();
-        if (bundleContext != null) {
-            ServiceTracker tracker =
-                    new ServiceTracker(bundleContext,
-                                       AuthenticationObserver.class.getName(),
-                                       null);
-            tracker.open();
-            Object[] services = tracker.getServices();
-            if (services != null) {
-                for (Object service : services) {
-                    ((AuthenticationObserver) service).startedAuthentication(tenantId);
-                }
-            }
-            tracker.close();
-        }
-    }
-    
-    /**
-     * loads the notification configurations for the mail to super tenant for account creations
-     * and activations.
-     */
-    private static void initSuperTenantNotificationEmailSender() {
-        // Tenant Registration Email Configurations
-        String tenantRegistrationEmailConfFile =
-                CarbonUtils.getCarbonConfigDirPath() + File.separator +
-                        StratosConstants.EMAIL_CONFIG + File.separator +
-                        "email-new-tenant-registration.xml";
-        EmailSenderConfiguration newTenantRegistrationEmailConf =
-                EmailSenderConfiguration.loadEmailSenderConfiguration(
-                        tenantRegistrationEmailConfFile);
-        tenantCreationNotifier = new EmailSender(newTenantRegistrationEmailConf);
-
-        // Tenant Activation Email Configurations
-        String tenantActivationEmailConfFile =
-                CarbonUtils.getCarbonConfigDirPath() + File.separator +
-                        StratosConstants.EMAIL_CONFIG + File.separator +
-                        "email-new-tenant-activation.xml";
-        EmailSenderConfiguration newTenantActivationEmailConf =
-                EmailSenderConfiguration
-                        .loadEmailSenderConfiguration(tenantActivationEmailConfFile);
-        tenantActivationNotifier = new EmailSender(newTenantActivationEmailConf);
-    }
-    
-    /**
-     * loads the Email configuration files to be sent on the tenant registrations.
-     */
-    private static void initEmailVerificationSender() {
-        String confXml =
-                CarbonUtils.getCarbonConfigDirPath() + File.separator +
-                        StratosConstants.EMAIL_CONFIG + File.separator + "email-registration.xml";
-        try {
-            emailVerifierConfig = org.wso2.carbon.email.verification.util.Util
-                            .loadeMailVerificationConfig(confXml);
-        } catch (Exception e) {
-            String msg = "Email Registration Configuration file not found. "
-                            + "Pls check the repository/conf/email folder.";
-            log.error(msg);
-        }
-        String superTenantConfXml =
-                CarbonUtils.getCarbonConfigDirPath() + File.separator +
-                        StratosConstants.EMAIL_CONFIG + File.separator +
-                        "email-registration-moderation.xml";
-        try {
-            superTenantEmailVerifierConfig = org.wso2.carbon.email.verification.util.Util
-                            .loadeMailVerificationConfig(superTenantConfXml);
-        } catch (Exception e) {
-            String msg =
-                    "Email Moderation Configuration file not found. "
-                            + "Pls check the repository/conf/email folder.";
-            log.error(msg);
-        }
-    }
-
-    /**
-     * loads the Email configuration files to be sent on the tenant activations.
-     */
-    private static void initTenantActivatedEmailSender() {
-        String confFilename =
-                CarbonUtils.getCarbonConfigDirPath() + File.separator +
-                        StratosConstants.EMAIL_CONFIG + File.separator +
-                        "email-registration-complete.xml";
-        EmailSenderConfiguration successMsgConfig =
-                EmailSenderConfiguration.loadEmailSenderConfiguration(confFilename);
-        successMsgSender = new EmailSender(successMsgConfig);
-    }
-
-    private static void initPasswordResetEmailSender() {
-        String passwordResetConfigFileName = CarbonUtils.getCarbonConfigDirPath()+ File.separator + 
-                StratosConstants.EMAIL_CONFIG + File.separator + "email-password-reset.xml";
-        EmailSenderConfiguration passwordResetMsgConfig =
-            EmailSenderConfiguration.loadEmailSenderConfiguration(passwordResetConfigFileName);
-        passwordResetMsgSender = new EmailSender(passwordResetMsgConfig);
-    }
-
-    /**
-     * Initializes the super tenant notification parameters
-     *
-     * @param domainName - tenant domain
-     * @param adminName  - tenant admin
-     * @param email      - tenant email
-     * @return the parameters
-     */
-    private static Map<String, String> initializeSuperTenantNotificationParams(
-            String domainName, String adminName, String email) {
-        TenantManager tenantManager = DataHolder.getTenantManager();
-        String firstName = "";
-        String lastName = "";
-        try {
-            int tenantId = tenantManager.getTenantId(domainName);
-            firstName = ClaimsMgtUtil.getFirstName(DataHolder.getRealmService(), tenantId);
-            lastName = ClaimsMgtUtil.getLastName(DataHolder.getRealmService(), tenantId);
-
-        } catch (Exception e) {
-            String msg = "Unable to get the tenant with the tenant domain";
-            log.error(msg, e);
-            // just catch from here.
-        }
-
-        // load the mail configuration
-        Map<String, String> userParams = new HashMap<String, String>();
-        userParams.put("user-name", adminName);
-        userParams.put("domain-name", domainName);
-        userParams.put("email-address", email);
-        userParams.put("first-name", firstName);
-        userParams.put("last-name", lastName);
-        return userParams;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.email.sender/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.email.sender/pom.xml b/components/org.apache.stratos.tenant.mgt.email.sender/pom.xml
new file mode 100644
index 0000000..ab9adcb
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt.email.sender/pom.xml
@@ -0,0 +1,105 @@
+<!--
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.tenant.mgt.email.sender</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Tenant Management Email Sender Component</name>
+
+    <build>
+
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Private-Package>
+                            org.apache.stratos.tenant.mgt.email.sender.internal.*,
+                            org.apache.stratos.tenant.mgt.email.sender.util.*,
+                        </Private-Package>
+                        <Export-Package>
+                            org.apache.stratos.tenant.mgt.email.sender.listener.*
+                        </Export-Package>
+                        <Import-Package>
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            org.wso2.carbon.email.sender.api,
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+	    <version>1.2.13</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+	    <version>${apache.stratos.version}</version>
+        </dependency>
+        <dependency>
+           <groupId>org.wso2.carbon</groupId>
+           <artifactId>org.wso2.carbon.email.verification</artifactId>
+	   <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+	    <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+	    <version>1.1.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.email.sender</artifactId>
+            <version>2.1.0</version>
+        </dependency>
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/DataHolder.java b/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/DataHolder.java
new file mode 100644
index 0000000..99710c9
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/DataHolder.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stratos.tenant.mgt.email.sender.internal;
+
+import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import org.apache.axis2.context.ConfigurationContext;
+
+import org.osgi.framework.BundleContext;
+
+/**
+ * Utility methods for the email sender component
+ */
+public class DataHolder {
+
+    private static RegistryService registryService;
+    private static RealmService realmService;
+    private static ConfigurationContextService configurationContextService;
+    private static EmailVerifcationSubscriber emailVerificationService;
+    private static BundleContext bundleContext;
+
+    public static BundleContext getBundleContext() {
+        return bundleContext;
+    }
+
+    public static void setBundleContext(BundleContext bundleContext) {
+        DataHolder.bundleContext = bundleContext;
+    }
+
+    public static ConfigurationContextService getConfigurationContextService() {
+        return configurationContextService;
+    }
+
+    public static void setConfigurationContextService(
+            ConfigurationContextService configurationContextService) {
+        DataHolder.configurationContextService = configurationContextService;
+    }
+
+    public static ConfigurationContext getConfigurationContext() {
+        return configurationContextService.getServerConfigContext();
+    }
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        if ((registryService == null) || (service == null)) {
+            registryService = service;
+        }
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static synchronized void setRealmService(RealmService service) {
+        if ((realmService == null) || (service == null)){
+            realmService = service;
+        }
+    }
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static TenantManager getTenantManager() {
+        return realmService.getTenantManager();
+    }
+
+    public static RealmConfiguration getBootstrapRealmConfiguration() {
+        return realmService.getBootstrapRealmConfiguration();
+    }
+
+    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getGovernanceSystemRegistry(tenantId);
+    }
+    
+    public static void setEmailVerificationService(EmailVerifcationSubscriber emailService) {
+        if ((emailVerificationService == null) || (emailService == null)){
+            emailVerificationService = emailService;
+        }
+    }
+    
+    public static EmailVerifcationSubscriber getEmailVerificationService() {
+        return emailVerificationService;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/TenantMgtEmailSenderServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/TenantMgtEmailSenderServiceComponent.java b/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/TenantMgtEmailSenderServiceComponent.java
new file mode 100644
index 0000000..5226897
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/TenantMgtEmailSenderServiceComponent.java
@@ -0,0 +1,106 @@
+/*
+*       Licensed to the Apache Software Foundation (ASF) under one
+*       or more contributor license agreements.  See the NOTICE file
+*       distributed with this work for additional information
+*       regarding copyright ownership.  The ASF licenses this file
+*       to you under the Apache License, Version 2.0 (the
+*       "License"); you may not use this file except in compliance
+*       with the License.  You may obtain a copy of the License at
+*
+*         http://www.apache.org/licenses/LICENSE-2.0
+*
+*       Unless required by applicable law or agreed to in writing,
+*       software distributed under the License is distributed on an
+*       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+*       KIND, either express or implied.  See the License for the
+*       specific language governing permissions and limitations
+*       under the License.
+*/
+package org.apache.stratos.tenant.mgt.email.sender.internal;
+
+import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.apache.stratos.common.util.CommonUtil;
+import org.apache.stratos.tenant.mgt.email.sender.listener.EmailSenderListener;
+import org.apache.stratos.tenant.mgt.email.sender.util.TenantMgtEmailSenderUtil;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.osgi.service.component.ComponentContext;
+
+/**
+ * @scr.component name="org.apache.stratos.tenant.mgt.email.sender"
+ * immediate="true"
+ * @scr.reference name="registry.service"
+ * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="1..1"
+ * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
+ * @scr.reference name="user.realmservice.default" 
+ * interface="org.wso2.carbon.user.core.service.RealmService" cardinality="1..1" 
+ * policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
+ * @scr.reference name="configuration.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
+ * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
+ * @scr.reference name="emailverification.service" 
+ * interface= "org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber"
+ * cardinality="1..1" policy="dynamic"
+ * bind="setEmailVerificationService" unbind="unsetEmailVerificationService"
+ */
+public class TenantMgtEmailSenderServiceComponent {
+    private static Log log = LogFactory.getLog(TenantMgtEmailSenderServiceComponent.class);
+
+    protected void activate(ComponentContext context) {
+        try {
+            DataHolder.setBundleContext(context.getBundleContext());
+            if (!CommonUtil.isTenantManagementEmailsDisabled()) {
+                TenantMgtEmailSenderUtil.init();
+                EmailSenderListener emailSenderListener = new EmailSenderListener();
+                context.getBundleContext().registerService(
+                        org.apache.stratos.common.listeners.TenantMgtListener.class.getName(),
+                        emailSenderListener, null);
+                log.debug("******* Tenant Management Emails are enabled ******* ");
+            }
+            log.debug("******* Tenant Registration Email Sender bundle is activated ******* ");
+        } catch (Throwable e) {
+            log.error("******* Tenant Registration Email Sender bundle failed activating ****", e);
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Email Sender bundle is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        DataHolder.setRegistryService(registryService);
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        DataHolder.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        DataHolder.setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        DataHolder.setRealmService(null);
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService service) {
+        DataHolder.setConfigurationContextService(service);
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService service) {
+        DataHolder.setConfigurationContextService(null);
+    }
+
+    protected void setEmailVerificationService(EmailVerifcationSubscriber emailService) {
+        DataHolder.setEmailVerificationService(emailService);
+    }
+
+    protected void unsetEmailVerificationService(EmailVerifcationSubscriber emailService) {
+        DataHolder.setEmailVerificationService(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/listener/EmailSenderListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/listener/EmailSenderListener.java b/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/listener/EmailSenderListener.java
new file mode 100644
index 0000000..8e01c13
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/listener/EmailSenderListener.java
@@ -0,0 +1,70 @@
+package org.apache.stratos.tenant.mgt.email.sender.listener;
+
+import org.apache.stratos.common.beans.TenantInfoBean;
+import org.apache.stratos.common.exception.StratosException;
+import org.apache.stratos.common.listeners.TenantMgtListener;
+import org.apache.stratos.tenant.mgt.email.sender.util.TenantMgtEmailSenderUtil;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class EmailSenderListener implements TenantMgtListener {
+    
+    private static final int EXEC_ORDER = 20;
+    private static final Log log = LogFactory.getLog(EmailSenderListener.class);
+
+    public void onTenantCreate(TenantInfoBean tenantInfoBean) throws StratosException {
+        try {
+            TenantMgtEmailSenderUtil.sendTenantCreationVerification(tenantInfoBean);
+        } catch (Exception e) {
+            String message = "Error sending tenant creation Mail to tenant domain " 
+                + tenantInfoBean.getTenantDomain();
+            log.error(message, e);
+            throw new StratosException(message, e);
+        }
+        TenantMgtEmailSenderUtil.notifyTenantCreationToSuperAdmin(tenantInfoBean);
+    }
+
+    public int getListenerOrder() {
+        return EXEC_ORDER;
+    }
+
+    public void onTenantRename(int tenantId, String oldDomainName, 
+                             String newDomainName) throws StratosException {
+        // Do nothing. 
+
+    }
+
+    public void onTenantUpdate(TenantInfoBean tenantInfoBean) throws StratosException {
+        if ((tenantInfoBean.getAdminPassword() != null) && 
+                (!tenantInfoBean.getAdminPassword().equals(""))) {
+            try {
+                TenantMgtEmailSenderUtil.notifyResetPassword(tenantInfoBean);
+            } catch (Exception e) {
+                String message = "Error sending tenant update Mail to tenant domain " 
+                    + tenantInfoBean.getTenantDomain();
+                log.error(message, e);
+                throw new StratosException(message, e);
+            }
+        }
+    }
+
+    public void onTenantInitialActivation(int tenantId) throws StratosException {
+     // send the notification message to the tenant admin
+        TenantMgtEmailSenderUtil.notifyTenantInitialActivation(tenantId);
+    }
+
+    public void onTenantActivation(int tenantId) throws StratosException {
+        // Do nothing. 
+    }
+
+    public void onTenantDeactivation(int tenantId) throws StratosException {
+        // Do nothing. 
+    }
+
+    public void onSubscriptionPlanChange(int tenentId, String oldPlan, 
+                                         String newPlan) throws StratosException {
+        // Do nothing. 
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/util/TenantMgtEmailSenderUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/util/TenantMgtEmailSenderUtil.java b/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/util/TenantMgtEmailSenderUtil.java
new file mode 100644
index 0000000..8fb9358
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt.email.sender/src/main/java/org/apache/stratos/tenant/mgt/email/sender/util/TenantMgtEmailSenderUtil.java
@@ -0,0 +1,482 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stratos.tenant.mgt.email.sender.util;
+
+import org.apache.stratos.tenant.mgt.email.sender.internal.DataHolder;
+import org.wso2.carbon.email.sender.api.EmailSender;
+import org.wso2.carbon.email.sender.api.EmailSenderConfiguration;
+import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber;
+import org.wso2.carbon.email.verification.util.EmailVerifierConfig;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.registry.core.utils.UUIDGenerator;
+import org.apache.stratos.common.beans.TenantInfoBean;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.util.ClaimsMgtUtil;
+import org.apache.stratos.common.util.CommonUtil;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.AuthenticationObserver;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.osgi.framework.BundleContext;
+import org.osgi.util.tracker.ServiceTracker;
+
+/**
+ * Utility methods for the email sender component
+ */
+public class TenantMgtEmailSenderUtil {
+
+    private static final Log log = LogFactory.getLog(TenantMgtEmailSenderUtil.class);
+    
+    private static EmailSender successMsgSender;
+    private static EmailSender tenantCreationNotifier;
+    private static EmailSender tenantActivationNotifier;
+    private static EmailSender passwordResetMsgSender;
+    private static EmailVerifierConfig emailVerifierConfig;
+    private static EmailVerifierConfig superTenantEmailVerifierConfig = null;
+    
+    public static void init() {
+        initTenantActivatedEmailSender();
+        initSuperTenantNotificationEmailSender();
+        initEmailVerificationSender();
+        initPasswordResetEmailSender();
+    }
+    
+    /**
+     * Sends validation mail to the tenant admin upon the tenant creation
+     *
+     * @param tenantInfoBean    - registered tenant's details
+     * @throws Exception, if the sending mail failed
+     */
+    public static void sendTenantCreationVerification(
+                                              TenantInfoBean tenantInfoBean) throws Exception {
+        String confirmationKey = generateConfirmationKey(tenantInfoBean,
+                DataHolder.getRegistryService().getConfigSystemRegistry(
+                        MultitenantConstants.SUPER_TENANT_ID));
+
+        if (CommonUtil.isTenantActivationModerated()) {
+            requestSuperTenantModeration(tenantInfoBean, confirmationKey);
+        } else {
+            //request for verification
+            requestUserVerification(tenantInfoBean, confirmationKey);
+        }
+    }
+    
+    /**
+     * Emails the tenant admin notifying the account creation.
+     *
+     * @param tenantId tenant Id
+     */
+    public static void notifyTenantInitialActivation(int tenantId) {
+        TenantManager tenantManager = DataHolder.getTenantManager();
+        String firstName = "";
+        String domainName = "";
+        String adminName = "";
+        String email = "";
+        try {
+            Tenant tenant = tenantManager.getTenant(tenantId);
+            domainName = tenant.getDomain();
+            firstName = ClaimsMgtUtil.getFirstName(DataHolder.getRealmService(), tenantId);
+            adminName = tenant.getAdminName();
+            email = tenant.getEmail(); 
+        } catch (Exception e) {
+            String msg = "Unable to get the tenant with the tenant domain";
+            log.error(msg, e);
+            // just catch from here.
+        }
+
+        // load the mail configuration
+        Map<String, String> userParams = new HashMap<String, String>();
+        userParams.put("first-name", firstName);
+        userParams.put("user-name", adminName);
+        userParams.put("domain-name", domainName);
+
+        try {
+            successMsgSender.sendEmail(email, userParams);
+        } catch (Exception e) {
+            // just catch from here..
+            String msg = "Error in sending the notification email.";
+            log.error(msg, e);
+        }
+        
+        // send the notification message to the super tenant
+        notifyTenantActivationToSuperAdmin(domainName, adminName, email);
+    }
+    
+    /**
+     * Emails the super admin notifying the account creation for a new tenant.
+     *
+     * @param tenantInfoBean - tenant details
+     */
+    public static void notifyTenantCreationToSuperAdmin(TenantInfoBean tenantInfoBean) {
+        String notificationEmailAddress = CommonUtil.getNotificationEmailAddress();
+
+        if (notificationEmailAddress.trim().equals("")) {
+            if (log.isDebugEnabled()) {
+                log.debug("No super-admin notification email address is set to notify upon a" +
+                          " tenant registration");
+            }
+            return;
+        }
+
+        Map<String, String> userParams = initializeSuperTenantNotificationParams(
+                tenantInfoBean.getTenantDomain(), tenantInfoBean.getAdmin(), 
+                tenantInfoBean.getEmail());
+
+        try {
+            tenantCreationNotifier.sendEmail(notificationEmailAddress, userParams);
+        } catch (Exception e) {
+            // just catch from here..
+            String msg = "Error in sending the notification email.";
+            log.error(msg, e);
+        }
+    }
+    
+    public static void notifyResetPassword(TenantInfoBean tenantInfoBean) throws Exception {
+        int tenantId = tenantInfoBean.getTenantId();
+        String firstName = ClaimsMgtUtil.getFirstName(DataHolder.getRealmService(), tenantId);
+
+        // load the mail configuration
+        Map<String, String> userParams = new HashMap<String, String>();
+        userParams.put("user-name", tenantInfoBean.getAdmin());
+        userParams.put("first-name", firstName);
+        userParams.put("domain-name", tenantInfoBean.getTenantDomain());
+        userParams.put("password", tenantInfoBean.getAdminPassword());
+
+        try {
+            passwordResetMsgSender.sendEmail(tenantInfoBean.getEmail(), userParams);
+        } catch (Exception e) {
+            // just catch from here..
+            String msg = "Error in sending the notification email.";
+            log.error(msg, e);
+        }
+    }
+    
+    /**
+     * Emails the super admin notifying the account activation for an unactivated tenant.
+     *
+     * @param domainName tenant domain
+     * @param adminName  tenant admin
+     * @param email      tenant's email address
+     */
+    private static void notifyTenantActivationToSuperAdmin(String domainName, String adminName,
+                                                          String email) {
+        String notificationEmailAddress = CommonUtil.getNotificationEmailAddress();
+
+        if (notificationEmailAddress.trim().equals("")) {
+            if (log.isDebugEnabled()) {
+                log.debug("No super-admin notification email address is set to notify upon a"
+                          + " tenant activation");
+            }
+            return;
+        }
+
+        Map<String, String> userParams =
+                initializeSuperTenantNotificationParams(domainName, adminName, email);
+
+        try {
+            tenantActivationNotifier.sendEmail(notificationEmailAddress, userParams);
+        } catch (Exception e) {
+            // just catch from here..
+            String msg = "Error in sending the notification email.";
+            log.error(msg, e);
+        }
+    }
+    
+    /**
+     * generates the confirmation key for the tenant
+     *
+     * @param tenantInfoBean            - tenant details
+     * @param superTenantConfigSystemRegistry
+     *                          - super tenant config system registry.
+     * @return confirmation key
+     * @throws RegistryException if generation of the confirmation key failed.
+     */
+    private static String generateConfirmationKey(TenantInfoBean tenantInfoBean,
+                                                  UserRegistry superTenantConfigSystemRegistry
+                                                  ) throws RegistryException {
+        // generating the confirmation key
+        String confirmationKey = UUIDGenerator.generateUUID();
+        UserRegistry superTenantGovernanceSystemRegistry;
+        try {
+            superTenantGovernanceSystemRegistry =
+                DataHolder.getRegistryService().getGovernanceSystemRegistry(
+                        MultitenantConstants.SUPER_TENANT_ID);
+        } catch (RegistryException e) {
+            String msg = "Exception in getting the governance system registry for the super tenant";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+        Resource resource;
+        String emailVerificationPath = StratosConstants.ADMIN_EMAIL_VERIFICATION_FLAG_PATH +
+                                       RegistryConstants.PATH_SEPARATOR + 
+                                       tenantInfoBean.getTenantId();
+        try {
+            if (superTenantGovernanceSystemRegistry.resourceExists(emailVerificationPath)) {
+                resource = superTenantGovernanceSystemRegistry.get(emailVerificationPath);
+            } else {
+                resource = superTenantGovernanceSystemRegistry.newResource();
+            }
+            resource.setContent(confirmationKey);
+        } catch (RegistryException e) {
+            String msg = "Error in creating the resource or getting the resource" +
+                         "from the email verification path";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+        // email is not validated yet, this prop is used to activate the tenant later.
+        resource.addProperty(StratosConstants.IS_EMAIL_VALIDATED, "false");
+        resource.addProperty(StratosConstants.TENANT_ADMIN, tenantInfoBean.getAdmin());
+        try {
+            superTenantGovernanceSystemRegistry.put(emailVerificationPath, resource);
+        } catch (RegistryException e) {
+            String msg = "Error in putting the resource to the super tenant registry" +
+                         " for the email verification path";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+
+        // Used for * as a Service impl.
+        // Store the cloud service from which the register req. is originated.
+        if (tenantInfoBean.getOriginatedService() != null) {
+            String originatedServicePath =
+                    StratosConstants.ORIGINATED_SERVICE_PATH +
+                    StratosConstants.PATH_SEPARATOR +
+                    StratosConstants.ORIGINATED_SERVICE +
+                    StratosConstants.PATH_SEPARATOR + tenantInfoBean.getTenantId();
+            try {
+                Resource origServiceRes = superTenantConfigSystemRegistry.newResource();
+                origServiceRes.setContent(tenantInfoBean.getOriginatedService());
+                superTenantGovernanceSystemRegistry.put(originatedServicePath, origServiceRes);
+            } catch (RegistryException e) {
+                String msg = "Error in putting the originated service resource "
+                             + "to the governance registry";
+                log.error(msg, e);
+                throw new RegistryException(msg, e);
+            }
+        }
+        initializeRegistry(tenantInfoBean.getTenantId());
+        if (log.isDebugEnabled()) {
+            log.debug("Successfully generated the confirmation key.");
+        }
+        return confirmationKey;
+    }
+    
+    /**
+     * Sends mail for the super tenant for the account moderation. Once super tenant clicks the
+     * link provided in the email, the tenant will be activated.
+     *
+     * @param tenantInfoBean      - the tenant who registered an account
+     * @param confirmationKey confirmation key.
+     * @throws Exception if an exception is thrown from EmailVerificationSubscriber.
+     */
+    private static void requestSuperTenantModeration(TenantInfoBean tenantInfoBean, 
+                                                       String confirmationKey) throws Exception {
+        try {
+            Map<String, String> dataToStore = new HashMap<String, String>();
+            dataToStore.put("email", CommonUtil.getSuperAdminEmail());
+            dataToStore.put("first-name", tenantInfoBean.getFirstname());
+            dataToStore.put("userName", tenantInfoBean.getAdmin());
+            dataToStore.put("tenantDomain", tenantInfoBean.getTenantDomain());
+            dataToStore.put("confirmationKey", confirmationKey);
+
+            DataHolder.getEmailVerificationService().requestUserVerification(
+                    dataToStore, superTenantEmailVerifierConfig);
+            if (log.isDebugEnabled()) {
+                log.debug("Email verification for the tenant registration.");
+            }
+        } catch (Exception e) {
+            String msg = "Error in notifying the super tenant on the account creation for " +
+                         "the domain: " + tenantInfoBean.getTenantDomain();
+            log.error(msg);
+            throw new Exception(msg, e);
+        }
+    }
+    
+    /**
+     * request email verification from the user.
+     *
+     * @param tenantInfoBean - Tenant information
+     * @param confirmationKey confirmation key.
+     * @throws Exception if an exception is thrown from EmailVerificationSubscriber.
+     */
+    private static void requestUserVerification(TenantInfoBean tenantInfoBean, 
+                                                String confirmationKey) throws Exception {
+        try {
+            Map<String, String> dataToStore = new HashMap<String, String>();
+            dataToStore.put("email", tenantInfoBean.getEmail());
+            dataToStore.put("first-name", tenantInfoBean.getFirstname());
+            dataToStore.put("userName", tenantInfoBean.getAdmin());
+            dataToStore.put("tenantDomain", tenantInfoBean.getTenantDomain());
+            dataToStore.put("confirmationKey", confirmationKey);
+
+            EmailVerifcationSubscriber emailVerifier = DataHolder.getEmailVerificationService();
+            emailVerifier.requestUserVerification(dataToStore, emailVerifierConfig);
+            if (log.isDebugEnabled()) {
+                log.debug("Email verification for the tenant registration.");
+            }
+        } catch (Exception e) {
+            String msg = "Error in notifying tenant of domain: " + tenantInfoBean.getTenantDomain();
+            log.error(msg);
+            throw new Exception(msg, e);
+        }
+    }
+    
+    /**
+     * Initializes the registry for the tenant.
+     *
+     * @param tenantId tenant id.
+     */
+    private static void initializeRegistry(int tenantId) {
+        BundleContext bundleContext = DataHolder.getBundleContext();
+        if (bundleContext != null) {
+            ServiceTracker tracker =
+                    new ServiceTracker(bundleContext,
+                                       AuthenticationObserver.class.getName(),
+                                       null);
+            tracker.open();
+            Object[] services = tracker.getServices();
+            if (services != null) {
+                for (Object service : services) {
+                    ((AuthenticationObserver) service).startedAuthentication(tenantId);
+                }
+            }
+            tracker.close();
+        }
+    }
+    
+    /**
+     * loads the notification configurations for the mail to super tenant for account creations
+     * and activations.
+     */
+    private static void initSuperTenantNotificationEmailSender() {
+        // Tenant Registration Email Configurations
+        String tenantRegistrationEmailConfFile =
+                CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                        StratosConstants.EMAIL_CONFIG + File.separator +
+                        "email-new-tenant-registration.xml";
+        EmailSenderConfiguration newTenantRegistrationEmailConf =
+                EmailSenderConfiguration.loadEmailSenderConfiguration(
+                        tenantRegistrationEmailConfFile);
+        tenantCreationNotifier = new EmailSender(newTenantRegistrationEmailConf);
+
+        // Tenant Activation Email Configurations
+        String tenantActivationEmailConfFile =
+                CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                        StratosConstants.EMAIL_CONFIG + File.separator +
+                        "email-new-tenant-activation.xml";
+        EmailSenderConfiguration newTenantActivationEmailConf =
+                EmailSenderConfiguration
+                        .loadEmailSenderConfiguration(tenantActivationEmailConfFile);
+        tenantActivationNotifier = new EmailSender(newTenantActivationEmailConf);
+    }
+    
+    /**
+     * loads the Email configuration files to be sent on the tenant registrations.
+     */
+    private static void initEmailVerificationSender() {
+        String confXml =
+                CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                        StratosConstants.EMAIL_CONFIG + File.separator + "email-registration.xml";
+        try {
+            emailVerifierConfig = org.wso2.carbon.email.verification.util.Util
+                            .loadeMailVerificationConfig(confXml);
+        } catch (Exception e) {
+            String msg = "Email Registration Configuration file not found. "
+                            + "Pls check the repository/conf/email folder.";
+            log.error(msg);
+        }
+        String superTenantConfXml =
+                CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                        StratosConstants.EMAIL_CONFIG + File.separator +
+                        "email-registration-moderation.xml";
+        try {
+            superTenantEmailVerifierConfig = org.wso2.carbon.email.verification.util.Util
+                            .loadeMailVerificationConfig(superTenantConfXml);
+        } catch (Exception e) {
+            String msg =
+                    "Email Moderation Configuration file not found. "
+                            + "Pls check the repository/conf/email folder.";
+            log.error(msg);
+        }
+    }
+
+    /**
+     * loads the Email configuration files to be sent on the tenant activations.
+     */
+    private static void initTenantActivatedEmailSender() {
+        String confFilename =
+                CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                        StratosConstants.EMAIL_CONFIG + File.separator +
+                        "email-registration-complete.xml";
+        EmailSenderConfiguration successMsgConfig =
+                EmailSenderConfiguration.loadEmailSenderConfiguration(confFilename);
+        successMsgSender = new EmailSender(successMsgConfig);
+    }
+
+    private static void initPasswordResetEmailSender() {
+        String passwordResetConfigFileName = CarbonUtils.getCarbonConfigDirPath()+ File.separator + 
+                StratosConstants.EMAIL_CONFIG + File.separator + "email-password-reset.xml";
+        EmailSenderConfiguration passwordResetMsgConfig =
+            EmailSenderConfiguration.loadEmailSenderConfiguration(passwordResetConfigFileName);
+        passwordResetMsgSender = new EmailSender(passwordResetMsgConfig);
+    }
+
+    /**
+     * Initializes the super tenant notification parameters
+     *
+     * @param domainName - tenant domain
+     * @param adminName  - tenant admin
+     * @param email      - tenant email
+     * @return the parameters
+     */
+    private static Map<String, String> initializeSuperTenantNotificationParams(
+            String domainName, String adminName, String email) {
+        TenantManager tenantManager = DataHolder.getTenantManager();
+        String firstName = "";
+        String lastName = "";
+        try {
+            int tenantId = tenantManager.getTenantId(domainName);
+            firstName = ClaimsMgtUtil.getFirstName(DataHolder.getRealmService(), tenantId);
+            lastName = ClaimsMgtUtil.getLastName(DataHolder.getRealmService(), tenantId);
+
+        } catch (Exception e) {
+            String msg = "Unable to get the tenant with the tenant domain";
+            log.error(msg, e);
+            // just catch from here.
+        }
+
+        // load the mail configuration
+        Map<String, String> userParams = new HashMap<String, String>();
+        userParams.put("user-name", adminName);
+        userParams.put("domain-name", domainName);
+        userParams.put("email-address", email);
+        userParams.put("first-name", firstName);
+        userParams.put("last-name", lastName);
+        return userParams;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.ui/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.ui/2.1.0/pom.xml b/components/org.apache.stratos.tenant.mgt.ui/2.1.0/pom.xml
index d278f3c..6fbac66 100644
--- a/components/org.apache.stratos.tenant.mgt.ui/2.1.0/pom.xml
+++ b/components/org.apache.stratos.tenant.mgt.ui/2.1.0/pom.xml
@@ -1,19 +1,22 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
-# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-  -->
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.  
+-->
 <project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
@@ -21,12 +24,10 @@
         <groupId>org.apache.stratos</groupId>
         <artifactId>stratos-components-parent</artifactId>
         <version>3.0.0-SNAPSHOT</version>
-<relativePath>../../pom.xml</relativePath>
     </parent>
 
     <modelVersion>4.0.0</modelVersion>
-	<artifactId>org.apache.stratos.tenant.mgt.ui</artifactId>
-	<version>2.1.0</version>
+    <artifactId>org.apache.stratos.tenant.mgt.ui</artifactId>
     <packaging>bundle</packaging>
     <name>Apache Stratos - User Interface for Tenant CRUD operations</name>
 
@@ -66,12 +67,12 @@
         <dependency>
             <groupId>org.wso2.carbon</groupId>
             <artifactId>org.wso2.carbon.registry.common.ui</artifactId>
-            <version>${carbon.platform.version}</version>
+            <version>${wso2carbon.version}</version>
         </dependency>
         <dependency>
             <groupId>org.wso2.carbon</groupId>
             <artifactId>org.wso2.carbon.registry.core</artifactId>
-            <version>${carbon.platform.version}</version>
+            <version>${wso2carbon.version}</version>
         </dependency>
         <dependency>
             <groupId>commons-logging</groupId>
@@ -91,32 +92,32 @@
         <dependency>
             <groupId>org.apache.ws.commons.axiom.wso2</groupId>
             <artifactId>axiom</artifactId>
-	    <version>1.2.11.wso2v2</version>
+	    <version>${axiom.wso2.version}</version>
         </dependency>
         <dependency>
             <groupId>org.wso2.carbon</groupId>
             <artifactId>org.wso2.carbon.ui</artifactId>
-            <version>${carbon.platform.version}</version>
+            <version>${wso2carbon.version}</version>
         </dependency>
         <dependency>
             <groupId>org.wso2.carbon</groupId>
             <artifactId>org.wso2.carbon.tenant.mgt.stub</artifactId>
-            <version>${carbon.platform.version}</version>
+            <version>${wso2carbon.version}</version>
         </dependency>
         <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.stratos.common</artifactId>
-	    <version>2.1.0</version>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+	    <version>${apache.stratos.version}</version>
         </dependency>
         <dependency>
             <groupId>org.json.wso2</groupId>
             <artifactId>json</artifactId>
-   	    <version>1.0.0.wso2v1</version>
+   	    <version>${json.wso2.version}</version>
         </dependency>
         <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.stratos.common.stub</artifactId>
-            <version>${carbon.platform.version}</version>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common.stub</artifactId>
+            <version>${apache.stratos.version}</version>
         </dependency>
     </dependencies>
 </project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.ui/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/ui/clients/PackageInfoServiceClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.ui/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/ui/clients/PackageInfoServiceClient.java b/components/org.apache.stratos.tenant.mgt.ui/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/ui/clients/PackageInfoServiceClient.java
index 39dbf21..b0b692a 100644
--- a/components/org.apache.stratos.tenant.mgt.ui/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/ui/clients/PackageInfoServiceClient.java
+++ b/components/org.apache.stratos.tenant.mgt.ui/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/ui/clients/PackageInfoServiceClient.java
@@ -9,8 +9,8 @@ import org.apache.commons.logging.LogFactory;
 import org.json.JSONArray;
 import org.json.JSONObject;
 import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.stratos.common.packages.stub.PackageInfoServiceStub;
-import org.wso2.carbon.stratos.common.packages.stub.PackageInfo;
+import org.apache.stratos.common.packages.stub.PackageInfoServiceStub;
+import org.apache.stratos.common.packages.stub.PackageInfo;
 
 /**
  * PackageInfoService client

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/pom.xml b/components/org.apache.stratos.tenant.mgt/2.1.0/pom.xml
deleted file mode 100644
index 51a479e..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/pom.xml
+++ /dev/null
@@ -1,125 +0,0 @@
-<!--
-# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-  -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-<relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.tenant.mgt</artifactId>
-    <version>2.1.0</version>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Tenant Managment</name>
-
-    <build>
-
-        <plugins>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Private-Package>
-                            org.apache.stratos.tenant.mgt.internal.*,
-                            org.apache.stratos.tenant.mgt.persistence.*,
-                        </Private-Package>
-                        <Import-Package>
-                            org.apache.stratos.common.*,
-                            org.wso2.carbon.registry.core.*;version=1.0.1,
-                            org.wso2.carbon.captcha.mgt.*,
-                            !javax.xml.namespace,
-                            javax.xml.namespace; version=0.0.0,
-                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
-                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
-                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
-                            *;resolution:=optional
-                        </Import-Package>
-                        <Export-Package>
-                            org.apache.stratos.tenant.mgt.beans.*,
-                            org.apache.stratos.tenant.mgt.exception.*,
-                            org.apache.stratos.tenant.mgt.realm.*,
-                            org.apache.stratos.tenant.mgt.services.*,
-                            org.apache.stratos.tenant.mgt.util.*,
-                        </Export-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.user.core</artifactId>
-            <version>${carbon.platform.version}</version>
-        </dependency>
-        <dependency>
-           <groupId>org.wso2.carbon</groupId>
-           <artifactId>org.wso2.carbon.tenant.mgt.core</artifactId>
-	   <version>2.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.registry.core</artifactId>
-            <version>${carbon.platform.version}</version>
-        </dependency>
-        <dependency>
-           <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.um.ws.api</artifactId>
-            <version>${carbon.platform.version}</version>
-        </dependency>
-        <dependency>
-           <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.captcha.mgt</artifactId>
-            <version>${carbon.platform.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.stratos.common</artifactId>
-	    <version>2.1.0</version>
-        </dependency>
-       
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.admin.mgt</artifactId>
-	    <version>4.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.rampart.wso2</groupId>
-            <artifactId>rampart-policy</artifactId>
-	    <version>1.6.1.wso2v8</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.rampart.wso2</groupId>
-            <artifactId>rampart-core</artifactId>
-	    <version>1.6.1.wso2v8</version>
-        </dependency>
-    </dependencies>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/beans/PaginatedTenantInfoBean.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/beans/PaginatedTenantInfoBean.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/beans/PaginatedTenantInfoBean.java
deleted file mode 100644
index 3a55df6..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/beans/PaginatedTenantInfoBean.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.tenant.mgt.beans;
-
-import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
-import org.wso2.carbon.utils.Pageable;
-
-import java.util.List;
-
-/**
- * Bean for paginated tenant information
- */
-public class PaginatedTenantInfoBean implements Pageable {
-    private TenantInfoBean[] tenantInfoBeans;
-    private int numberOfPages;
-
-    public TenantInfoBean[] getTenantInfoBeans() {
-        return tenantInfoBeans;
-    }
-
-    public void setTenantInfoBeans(TenantInfoBean[] tenantInfoBeans) {
-        this.tenantInfoBeans = tenantInfoBeans;
-    }
-
-    public int getNumberOfPages() {
-        return numberOfPages;
-    }
-    
-    public void setNumberOfPages(int numberOfPages) {
-        this.numberOfPages = numberOfPages;
-    }
-
-    public <T> void set(List<T> items) {
-        this.tenantInfoBeans = items.toArray(new TenantInfoBean[items.size()]);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/exception/TenantManagementException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/exception/TenantManagementException.java b/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/exception/TenantManagementException.java
deleted file mode 100644
index 1207f5d..0000000
--- a/components/org.apache.stratos.tenant.mgt/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/exception/TenantManagementException.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- *  WSO2 Inc. licenses this file to you under the Apache License,
- *  Version 2.0 (the "License"); you may not use this file except
- *  in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- *
- */
-package org.apache.stratos.tenant.mgt.exception;
-
-/**
- * Tenant Management Specific Exception.
- */
-public class TenantManagementException extends Exception {
-
-    public TenantManagementException(String msg, Exception e) {
-        super(msg, e);
-    }
-    
-    public TenantManagementException(String msg) {
-        super(msg);
-    }
-}


[13/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/LoadBalancerConfiguration.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/LoadBalancerConfiguration.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/LoadBalancerConfiguration.java
new file mode 100644
index 0000000..0257b0e
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/LoadBalancerConfiguration.java
@@ -0,0 +1,1206 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.conf;
+
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.commons.util.PropertyHelper;
+import org.apache.stratos.lb.common.conf.structure.Node;
+import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
+import org.apache.stratos.lb.common.conf.util.Constants;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.apache.stratos.lb.common.conf.util.LoadBalancerConfigUtil;
+import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
+import java.io.*;
+import java.net.URL;
+import java.util.*;
+
+/**
+ * Data object which hold configuration data of the load analyzer task
+ */
+@SuppressWarnings("unused")
+public class LoadBalancerConfiguration implements Serializable {
+
+    protected static final long serialVersionUID = -5553545217542808233L;
+
+    private static final Log log = LogFactory.getLog(LoadBalancerConfiguration.class);
+
+    /**
+     * This map is there to speed up the lookup time.
+     * Key: domain
+     * <p/>
+     * Value: A map whose key is sub domain and value is ServiceConfiguration
+     */
+    private Map<String, Map<String, ServiceConfiguration>> serviceConfigurations =
+            new HashMap<String, Map<String, ServiceConfiguration>>();
+    
+    /**
+     * Key - host name
+     * Value - {@link HostContext}
+     */
+    private transient Map<String, HostContext> hostCtxt = new HashMap<String, HostContext>();
+    
+    /**
+     * This map is there to speed up the lookup time.
+     * Key: service name/cartridge type (Stratos2). NOTE: that this is not the service cluster domain.
+     * Value: list of {@link ServiceConfiguration} - corresponding objects under a service name.
+     */
+	private Map<String, List<ServiceConfiguration>> serviceNameToServiceConfigurations =
+			new HashMap<String, List<ServiceConfiguration>>();
+
+    /**
+     * This list will be used to identify host name duplications among different services.
+     * Within a service there can be duplications, but among different services you can't have duplications.
+     * Key - service name
+     * Value - hosts under the respective service.
+     */
+    private Map<String, Set<String>> hostNamesTracker = new HashMap<String, Set<String>>();
+
+    protected ServiceConfiguration defaultServiceConfig;
+    protected LBConfiguration lbConfig;
+
+    /**
+     * LBConfig file as a String
+     */
+    protected String lbConfigString;
+
+    /**
+     * Root node object for loadbalancer.conf
+     */
+    protected Node rootNode;
+
+    private LoadBalancerConfiguration(){
+        init(System.getProperty("loadbalancer.conf"));
+    }
+
+    private static LoadBalancerConfiguration instance ;
+    
+    public static LoadBalancerConfiguration getInstance(){
+        if(instance == null){
+            instance = new LoadBalancerConfiguration();
+        }
+        return instance;
+    }
+
+    /**
+     * Sample loadbalancer.conf:
+     * <p/>
+     * loadbalancer {
+     * # minimum number of load balancer instances
+     * instances           1;
+     * # whether autoscaling enable or not
+     * enable_autoscaler   true;
+     * # End point reference of the Autoscaler Service
+     * autoscaler_service_epr  https://10.100.3.81:9443/services/AutoscalerService/;
+     * # interval between two task executions in milliseconds
+     * autoscaler_task_interval 1000;
+     * # after an instance booted up, task will wait till this much of time and let the server started up
+     * server_startup_delay 15000;
+     * }
+     * <p/>
+     * services {
+     * defaults {
+     * min_app_instances       1;
+     * max_app_instances       5;
+     * queue_length_per_node   400;
+     * rounds_to_average       10;
+     * instances_per_scale_up  1;
+     * message_expiry_time     60000;
+     * }
+     * <p/>
+     * appserver {
+     * hosts                   appserver.cloud-test.wso2.com,as.cloud-test.wso2.com;
+     * domains   {
+     * wso2.as1.domain {
+     * tenant_range    1-100;
+     * }
+     * wso2.as2.domain {
+     * tenant_range    101-200;
+     * }
+     * wso2.as3.domain {
+     * tenant_range    *;
+     * }
+     * }
+     * }
+     * }
+     *
+     * @param configURL URL of the load balancer config
+     */
+    public void init(String configURL) {
+
+        if(configURL == null){
+            String msg = "Cannot locate the location of the loadbalancer.conf file." +
+                   " You need to set the 'loadbalancer.conf' system property.";
+            log.error(msg);
+            throw new RuntimeException(msg);
+        }
+        
+        if (configURL.startsWith("$system:")) {
+            configURL = System.getProperty(configURL.substring("$system:".length()));
+        }
+
+        try {
+
+            // get loadbalancer.conf file as a String
+            if (configURL.startsWith(File.separator)) {
+                lbConfigString = createLBConfigString(configURL);
+            } else {
+                lbConfigString = createLBConfigString(new URL(configURL).openStream());
+            }
+
+        } catch (Exception e) {
+            String msg = "Cannot read configuration file from " + configURL;
+            log.error(msg, e);
+            throw new RuntimeException(msg, e);
+        }
+
+        // build a Node object for whole loadbalancer.conf
+        rootNode = new Node();
+        rootNode.setName("root");
+        rootNode = NodeBuilder.buildNode(rootNode, lbConfigString);
+
+        // load 'loadbalancer' node
+        Node lbConfigNode = rootNode.findChildNodeByName(Constants.LOAD_BALANCER_ELEMENT);
+
+        if(lbConfigNode != null){
+        	createConfiguration(lbConfig = new LBConfiguration(), lbConfigNode);
+        }
+
+        // load services node
+        Node servicesConfigNode = rootNode.findChildNodeByName(Constants.SERVICES_ELEMENT);
+
+        if (servicesConfigNode == null) {
+            String msg = "Mandatory " + Constants.SERVICES_ELEMENT +
+                    " element can not be found in the configuration file.";
+            log.error(msg);
+            throw new RuntimeException(msg);
+        }
+
+        // Set services configuration
+        createServicesConfig(servicesConfigNode);
+
+    }
+
+
+    /**
+     * Process the content of the following 'services' element
+     * <p/>
+     * services {
+     * defaults {
+     * min_app_instances       1;
+     * max_app_instances       5;
+     * queue_length_per_node   400;
+     * rounds_to_average       10;
+     * instances_per_scale_up  1;
+     * message_expiry_time     60000;
+     * }
+     * <p/>
+     * appserver {
+     * hosts                   appserver.cloud-test.wso2.com,as.cloud-test.wso2.com;
+     * domains   {
+     * wso2.as1.domain {
+     * tenant_range    1-100;
+     * }
+     * wso2.as2.domain {
+     * tenant_range    101-200;
+     * }
+     * wso2.as3.domain {
+     * tenant_range    *;
+     * }
+     * }
+     * }
+     * }
+     *
+     * @param servicesConfigNode services element's Node
+     */
+    public List<ServiceConfiguration> createServicesConfig(Node servicesConfigNode) {
+
+        // current list of service configs
+        List<ServiceConfiguration> currentServiceConfigs = new ArrayList<ServiceConfiguration>();
+        
+        // Building default configuration
+        Node defaultNode = servicesConfigNode.findChildNodeByName(Constants.DEFAULTS_ELEMENT);
+
+        if (defaultNode != null) {
+
+            createConfiguration(defaultServiceConfig = new ServiceConfiguration(), defaultNode);
+        }
+
+        // Building custom services configuration
+        for (Node serviceNode : servicesConfigNode.getChildNodes()) {
+            //skip default node
+            if (serviceNode != defaultNode) {
+
+                String serviceName = serviceNode.getName();
+
+                // reading domains
+
+                Node domainsNode;
+
+                if (serviceNode.getChildNodes().isEmpty() ||
+                        !(domainsNode = serviceNode.getChildNodes().get(0)).getName().equals(
+                                Constants.DOMAIN_ELEMENT)) {
+
+                    String msg = "The mandatory domains element, child of the " + serviceName +
+                            " element is not specified in the configuration file. \n"+
+                            serviceNode.toString();
+                    log.error(msg);
+                    throw new RuntimeException(msg);
+                }
+
+                if (domainsNode.getChildNodes().isEmpty()) {
+                    // this is probably a mistake, so we don't proceed
+                    String msg = "No domain is specified under " + Constants.DOMAIN_ELEMENT +
+                            " of " + serviceName + " element.";
+                    log.error(msg);
+                    throw new RuntimeException(msg);
+                }
+
+                ServiceConfiguration serviceConfig;
+
+                // iterates through all the service domain specified in this service element. 
+                for (Node domain : domainsNode.getChildNodes()) {
+
+                    // create a new service configuration
+                    serviceConfig = new ServiceConfiguration();
+
+                    // set service name
+                    serviceConfig.setServiceName(serviceName);
+                    
+                    // set domain name
+                    serviceConfig.setDomain(domain.getName());
+
+                    // let's set properties common to all domains specified in this service element.
+                    createConfiguration(serviceConfig, serviceNode);
+
+                    // load properties specified under this service domain element.
+                    createConfiguration(serviceConfig, domain);
+
+                    // check host name duplication 
+                    if(isDuplicatedHost(serviceNode.getName(), serviceConfig)){
+                        // this is probably a mistake, so we don't proceed
+                        String msg = "Duplicated host names detected for different service domains.\n" +
+                                "Element: \n"+serviceNode.toString();
+                        log.error(msg);
+                        throw new RuntimeException(msg);
+                    }
+                    
+                    currentServiceConfigs.add(serviceConfig);
+
+                }
+            }
+        }
+
+        for (ServiceConfiguration serviceConfiguration : currentServiceConfigs) {
+            
+            // add the built ServiceConfiguration, to the map
+            addServiceConfiguration(serviceConfiguration);
+            
+        }
+        
+        return currentServiceConfigs;
+
+    }
+
+
+    public boolean addServiceConfiguration(ServiceConfiguration serviceConfig) {
+
+        Map<String, ServiceConfiguration> map;
+        String domain = serviceConfig.getDomain();
+        
+        if(domain == null){
+            String msg = "Domain of a Service Configuration cannot be null. Hence this " +
+            		"Configuration will be neglected.";
+            log.error(msg);
+            return false;
+        }
+        
+        String subDomain = serviceConfig.getSubDomain();
+
+        if (serviceConfigurations.containsKey(domain)) {
+            map = serviceConfigurations.get(domain);
+        } else {
+            map = new HashMap<String, ServiceConfiguration>();
+        }
+        // put this serviceConfig
+        map.put(subDomain, serviceConfig);
+
+        // update the parent map
+        serviceConfigurations.put(domain, map);
+        
+        // add to serviceNameToServiceConfiguration map
+        List<ServiceConfiguration> configs;
+        if(serviceNameToServiceConfigurations.get(serviceConfig.getServiceName()) == null){
+        	configs = new ArrayList<ServiceConfiguration>();
+        	
+        }else{
+        	configs = serviceNameToServiceConfigurations.get(serviceConfig.getServiceName());
+        }
+        
+        if(!configs.contains(serviceConfig)){
+        	configs.add(serviceConfig);
+        }
+        serviceNameToServiceConfigurations.put(serviceConfig.getServiceName(), configs);
+        
+        return true;
+    }
+    
+    public ServiceConfiguration removeServiceConfiguration(String domain, String subDomain) {
+
+        Map<String, ServiceConfiguration> map;
+        ServiceConfiguration serviceConfig = null;
+        
+        if(domain == null){
+            String msg = "Domain of a Service Configuration cannot be null. Hence this " +
+            		"Configuration will be neglected.";
+            log.error(msg);
+            return null;
+        }
+
+        if (serviceConfigurations.containsKey(domain)) {
+            map = serviceConfigurations.get(domain);
+            
+            if(map != null){
+            	serviceConfig = map.remove(subDomain);
+            }
+        } 
+        
+        if(serviceConfig == null){
+        	String msg = "No matching service configuration found for domain: "+domain+
+        			", sub domain: "+subDomain;
+            log.error(msg);
+        	return null;
+        }
+        
+        String serviceName = serviceConfig.getServiceName();
+        
+        if (serviceName != null && serviceNameToServiceConfigurations.containsKey(serviceName)) {
+            if(serviceConfig != null){
+            	List<ServiceConfiguration> list = serviceNameToServiceConfigurations.get(serviceName);
+            	
+            	list.remove(serviceConfig);
+            	
+            	serviceNameToServiceConfigurations.put(serviceName, list);
+            }
+        } 
+        
+        Set<String> allHosts;
+
+        if (hostNamesTracker.containsKey(serviceName)) {
+            allHosts = hostNamesTracker.get(serviceName);
+            
+            for (String hostName : serviceConfig.getHosts()) {
+	            
+				if (hostName != null) {
+					
+					allHosts.remove(hostName);
+
+					hostCtxt.remove(hostName);
+				}
+            }
+        }
+        
+        return serviceConfig;
+    }
+    
+    public void resetData(){
+    	serviceConfigurations =
+                new HashMap<String, Map<String, ServiceConfiguration>>();
+    	
+    	serviceNameToServiceConfigurations =
+    			new HashMap<String, List<ServiceConfiguration>>();
+    	
+    }
+
+
+    /**
+     * Duplications can only be seen, when you traverse down the configuration file.
+     * 
+     */
+    public boolean isDuplicatedHost(String name, ServiceConfiguration serviceConfig) {
+
+        /**
+         * This will be populated with host names of all other services other than the
+         * service subjected to the test.
+         */
+        List<String> hostsOtherThanMine = new ArrayList<String>(hostNamesTracker.values().size());
+
+        for (Map.Entry<String, Set<String>> entry : hostNamesTracker.entrySet()) {
+            if (!entry.getKey().equals(name)) {
+                hostsOtherThanMine.addAll(entry.getValue());
+            }
+        }
+
+        for (String host : serviceConfig.getHosts()) {
+            if (!hostsOtherThanMine.isEmpty() && hostsOtherThanMine.contains(host)) {
+                return true;
+            }
+        }
+
+        addToHostNameTrackerMap(name, serviceConfig.getHosts());
+
+        return false;
+    }
+
+
+    public void addToHostNameTrackerMap(String name, List<String> hosts) {
+
+        Set<String> allHosts;
+
+        if (hostNamesTracker.containsKey(name)) {
+            allHosts = hostNamesTracker.get(name);
+            allHosts.addAll(hosts);
+        } else {
+            allHosts = new HashSet<String>(hosts);
+        }
+        hostNamesTracker.put(name, allHosts);
+    }
+    
+    public void addToHostContextMap(String hostName, HostContext ctxt) {
+
+        if (hostName != null && ctxt != null) {
+            hostCtxt.put(hostName, ctxt);
+        }
+    }
+    
+    /**
+     * Return a map of {@link HostContext}.
+     * @return
+     */
+    public Map<String, HostContext> getHostContextMap() {
+
+        List<Integer> tenantIds;
+        Map<String, String> URLSuffixes;
+
+        // FIXME if possible! I couldn't think of any other way to do this, at this moment.
+        // Note: some of these for-loops are pretty small, thus no considerable performance overhead.
+        // iterate through each service
+        for (Iterator<Set<String>> it = hostNamesTracker.values().iterator(); it.hasNext();) {
+
+            // iterate through host names of this service
+            for (String hostName : ((Set<String>) it.next())) {
+                                                                  
+                // building HostContext
+                HostContext ctxt = new HostContext(hostName);
+
+                // iterate through domains of this host
+                for (Map.Entry<String, Map<String, ServiceConfiguration>> parentMap : serviceConfigurations.entrySet()) {
+
+                    // iterate through sub domain of this domain
+                    for (Map.Entry<String, ServiceConfiguration> childMap : parentMap.getValue()
+                            .entrySet()) {
+                        // iterate through hosts of this
+                        for (String host : childMap.getValue().getHosts()) {
+                            // if a matching Service configuration is found.
+                            if (host.equals(hostName)) {
+                                
+                                String tenantRange = childMap.getValue().getTenantRange();
+                                String domain = parentMap.getKey();
+                                String subDomain = childMap.getKey();
+                                          
+                                ctxt.addTenantDomainContexts(LoadBalancerConfigUtil.getTenantDomainContexts(tenantRange, domain, subDomain));
+
+                                break;
+                            }
+                        }
+                        
+                        //iterate through URL suffixes
+                        for(Map.Entry<String, String> entry : childMap.getValue().getUrl_suffix().entrySet()) {
+                            if(entry.getKey().equals(hostName)) {
+                                
+                                ctxt.setUrlSuffix(entry.getValue());
+                                
+                                break;
+                            }
+
+                        }
+                    }
+                }
+
+                // add this hostCtxt
+                hostCtxt.put(hostName, ctxt);
+            }
+
+        }
+
+        return hostCtxt;
+
+    }
+
+    protected void createConfiguration(Configuration config, Node node) {
+
+        if (node == null) {
+            String msg = "The configuration element for " +
+                    config.getClass().getName() + " is null.";
+            throw new RuntimeException(msg);
+        }
+
+        try {
+            // load properties
+            for (Map.Entry<String, String> entry : node.getProperties().entrySet()) {
+                String key = entry.getKey();
+                String value = entry.getValue();
+
+                PropertyHelper.setInstanceProperty(key, value, config);
+            }
+
+        } catch (Exception e) {
+            String msg = "Error setting values to " + config.getClass().getName();
+            log.error(msg, e);
+            throw new RuntimeException(msg, e);
+        }
+    }
+
+    public LBConfiguration getLoadBalancerConfig() {
+        return lbConfig;
+    }
+
+    public String[] getServiceDomains() {
+
+        Object[] objs = serviceConfigurations.keySet().toArray();
+
+        return Arrays.copyOf(objs, objs.length, String[].class);
+
+    }
+
+    public String[] getServiceSubDomains(String domain) {
+
+        if (serviceConfigurations.get(domain) != null) {
+            Object[] objs = serviceConfigurations.get(domain).keySet().toArray();
+            return Arrays.copyOf(objs, objs.length, String[].class);
+        }
+
+        return new String[0];
+    }
+
+    public ServiceConfiguration getServiceConfig(String domain, String subDomain) {
+        if (serviceConfigurations.get(domain) != null) {
+            return serviceConfigurations.get(domain).get(subDomain);
+        }
+        return null;
+    }
+    
+    
+    public List<ServiceConfiguration> getServiceConfigs(String serviceName) {
+        return serviceNameToServiceConfigurations.get(serviceName);
+    }
+
+    /**
+     * Convert given configuration file to a single String
+     *
+     * @param configFileName - file name to convert
+     * @return String with complete lb configuration
+     * @throws FileNotFoundException
+     */
+    public String createLBConfigString(String configFileName) throws FileNotFoundException {
+        StringBuilder lbConfigString = new StringBuilder("");
+
+        File configFile = new File(configFileName);
+        Scanner scanner;
+
+        scanner = new Scanner(configFile);
+
+        while (scanner.hasNextLine()) {
+            lbConfigString.append(scanner.nextLine().trim() + "\n");
+        }
+
+        return lbConfigString.toString().trim();
+    }
+
+    public String createLBConfigString(InputStream configFileName) throws IOException {
+
+        // read the stream with BufferedReader
+        BufferedReader br = new BufferedReader(new InputStreamReader(configFileName));
+
+        StringBuilder sb = new StringBuilder();
+
+        String line;
+        while ((line = br.readLine()) != null) {
+            sb.append(line.trim() + "\n");
+        }
+
+        return sb.toString().trim();
+    }
+
+    public abstract class Configuration implements Serializable {
+
+        private static final long serialVersionUID = -5433889427746551250L;
+        protected String imageId = System.getenv("ami_id");
+        protected String payload;
+        protected boolean payloadSet;
+
+        protected String availability_zone = "us-east-1c";
+        protected boolean availabilityZoneSet;
+
+        protected String[] security_groups = new String[]{"default"};
+        protected boolean securityGroupsSet;
+
+        protected String instance_type = "m1.large";
+        protected boolean instanceTypeSet;
+
+        protected String additional_info;
+
+        public String getImageId() {
+            return imageId;
+        }
+
+        public String getAdditionalInfo() {
+            return additional_info;
+        }
+
+        public String getAvailability_zone() {
+            if (this instanceof LBConfiguration) {
+                return availability_zone;
+            }
+            if (availabilityZoneSet) {
+                return availability_zone;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.availabilityZoneSet) {
+                return defaultServiceConfig.availability_zone;
+            }
+            return availability_zone;
+        }
+
+        public String[] getSecurityGroups() {
+            if (this instanceof LBConfiguration) {
+                return security_groups;
+            }
+            if (securityGroupsSet) {
+                return security_groups;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.securityGroupsSet) {
+                return defaultServiceConfig.security_groups;
+            }
+            return security_groups;
+        }
+
+        public String getInstanceType() {
+            if (this instanceof LBConfiguration) {
+                return instance_type;
+            }
+            if (instanceTypeSet) {
+                return instance_type;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.instanceTypeSet) {
+                return defaultServiceConfig.instance_type;
+            }
+            return instance_type;
+        }
+
+
+        public String getUserData() {
+            if (payload == null) {
+                payload = LoadBalancerConfigUtil.getUserData("resources/cluster_node.zip");
+            }
+            if (this instanceof LBConfiguration) {
+                return payload;
+            }
+            if (payloadSet) {
+                return payload;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.payloadSet) {
+                return defaultServiceConfig.payload;
+            }
+            return payload;
+        }
+
+        public void setPayload(String payload) {
+            this.payload = LoadBalancerConfigUtil.getUserData(LoadBalancerConfigUtil.replaceVariables(payload));
+            this.payloadSet = true;
+        }
+
+        public void setAvailability_zone(String availabilityZone) {
+            this.availability_zone = LoadBalancerConfigUtil.replaceVariables(availabilityZone);
+            this.availabilityZoneSet = true;
+        }
+
+        public void setSecurity_groups(String securityGroups) {
+            this.security_groups = LoadBalancerConfigUtil.replaceVariables(securityGroups).split(",");
+            this.securityGroupsSet = true;
+        }
+
+        public void setInstance_type(String instanceType) {
+            this.instance_type = LoadBalancerConfigUtil.replaceVariables(instanceType);
+            this.instanceTypeSet = true;
+        }
+
+    }
+
+    public class LBConfiguration extends Configuration implements Serializable {
+
+        private static final long serialVersionUID = 1357143883932816418L;
+        private String elasticIP;//= LoadBalancerConfigUtil.replaceVariables("${ELASTIC_IP}");
+        private int instances = 1;
+        private boolean isAutoscaleEnabled;
+        private int autoscalerTaskInterval = 30000;
+        private String autoscalerServiceEpr;
+        private int serverStartupDelay = 60000;
+        private int sizeOfCache = 0 ;
+        private boolean failOver;
+        private int sessionTimeOut = -1;
+        private String groupManagementAgentClass;
+        private String autoscalerTaskClass;
+        private String mbServerUrl;
+        private boolean useEmbeddedAutoscaler = true;
+        private String algorithm = "org.apache.synapse.endpoints.algorithms.RoundRobin";
+
+        public String getElasticIP() {
+            return elasticIP;
+        }
+
+        public int getInstances() {
+            return instances;
+        }
+
+        public boolean isAutoscaleEnabled() {
+            return isAutoscaleEnabled;
+        }
+        
+        public boolean useEmbeddedAutoscaler() {
+            return useEmbeddedAutoscaler;
+        }
+        
+        public boolean getFailOver() {
+            return failOver;
+        }
+
+        public String getAutoscalerServiceEpr() {
+            return autoscalerServiceEpr;
+        }
+
+        public int getAutoscalerTaskInterval() {
+            return autoscalerTaskInterval;
+        }
+
+        public int getServerStartupDelay() {
+            return serverStartupDelay;
+        }
+        
+        public int getSessionTimeOut() {
+            return sessionTimeOut;
+        }
+
+        public void setElasticIP(String elasticIP) {
+            this.elasticIP = LoadBalancerConfigUtil.replaceVariables(elasticIP);
+        }
+
+        public void setInstances(int instances) {
+            this.instances = instances;
+        }
+
+        public void setEnable_autoscaler(String isEnabled) {
+            this.isAutoscaleEnabled = Boolean.parseBoolean(isEnabled);
+        }
+        
+        public void setUse_embedded_autoscaler(String use) {
+            this.useEmbeddedAutoscaler = Boolean.parseBoolean(use);
+        }
+        
+        public void setFail_over(String isEnabled) {
+            this.failOver = Boolean.parseBoolean(isEnabled);
+        }
+
+        public void setAutoscaler_service_epr(String epr) {
+            this.autoscalerServiceEpr = epr;
+        }
+
+        public void setMb_server_url(String url) {
+            this.mbServerUrl = url;
+        }
+        
+        public String getMbServerUrl() {
+        	return mbServerUrl;
+        }
+
+		public void setAutoscaler_task_interval(String interval) {
+            this.autoscalerTaskInterval = Integer.parseInt(interval);
+        }
+
+        public void setServer_startup_delay(String delay) {
+            this.serverStartupDelay = Integer.parseInt(delay);
+        }
+        
+        public void setSession_timeout(String timeout) {
+            this.sessionTimeOut = Integer.parseInt(timeout);
+        }
+
+        public String getAlgorithm() {
+            return algorithm;
+        }
+
+        public void setAlgorithm(String algorithm) {
+            if (algorithm != null) {
+                this.algorithm = algorithm;
+            }
+        }
+
+        public int getSizeOfCache() {
+            return sizeOfCache;
+        }
+
+        public void setSize_of_cache(int sizeOfCache) {
+            this.sizeOfCache = sizeOfCache;
+        }
+
+        public String getGroupManagementAgentClass() {
+            return groupManagementAgentClass;
+        }
+        
+        public String getAutoscalerTaskClass() {
+            return autoscalerTaskClass;
+        }
+
+        public void setGroup_mgt_agent(String groupManagementAgentClass){
+            this.groupManagementAgentClass = groupManagementAgentClass;
+        }
+        
+        public void setAutoscaler_task(String autoscalerTaskClass){
+            this.autoscalerTaskClass = autoscalerTaskClass;
+        }
+    }
+
+    public class ServiceConfiguration extends Configuration implements Serializable {
+
+    	private String serviceName;
+    	
+        public String getServiceName() {
+        	return serviceName;
+        }
+
+		public void setServiceName(String name) {
+        	this.serviceName = name;
+        }
+		
+		public String getPublicIp() {
+        	return publicIp;
+        }
+
+		public void setPublic_ip(String publicIp) {
+        	this.publicIp = publicIp;
+        }
+
+		private String publicIp;
+
+		private static final long serialVersionUID = 8707314702788040116L;
+        private int minAppInstances = 1;
+        private boolean minAppInstancesSet;
+
+        private int maxAppInstances = 3;
+        private boolean maxAppInstancesSet;
+
+        private int maxRequestsPerSecond = 100;
+        private boolean maxRequestsPerSecondSet;
+        
+        private double alarmingUpperRate = 0.7;
+        private boolean alarmingUpperRateSet;
+
+        private double alarmingLowerRate = 0.2;
+        private boolean alarmingLowerRateSet;
+        
+        private double scaleDownFactor = 0.25;
+        private boolean scaleDownFactorSet;
+        
+        private int roundsToAverage = 10;
+        private boolean roundsToAverageSet;
+
+        private int instancesPerScaleUp = 1;
+        private boolean instancesPerScaleUpSet;
+
+        private int messageExpiryTime = 60000; // milliseconds
+        private boolean messageExpiryTimeSet;
+
+        private List<String> hosts = new ArrayList<String>();
+        private Map<String, String> urlSuffixes = new HashMap<String, String>();
+        private boolean hostsSet;
+
+        private String domain;
+
+        private String tenantRange;
+        private boolean tenantRangeSet;
+
+        private String subDomain = Constants.DEFAULT_SUB_DOMAIN;
+        private boolean subDomainSet;
+
+        public String getTenantRange() {
+            if (tenantRangeSet) {
+                return tenantRange;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.tenantRangeSet) {
+                return defaultServiceConfig.tenantRange;
+            }
+            return tenantRange;
+        }
+
+        public String getDomain() {
+            return domain;
+        }
+
+        public List<String> getHosts() {
+            if (hostsSet) {
+                return hosts;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.hostsSet) {
+                return defaultServiceConfig.hosts;
+            }
+            return hosts;
+        }
+
+        public int getMinAppInstances() {
+            if (minAppInstancesSet) {
+                return minAppInstances;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.minAppInstancesSet) {
+                return defaultServiceConfig.minAppInstances;
+            }
+            return minAppInstances;
+        }
+
+        public int getMaxAppInstances() {
+            if (maxAppInstancesSet) {
+                return maxAppInstances;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.maxAppInstancesSet) {
+                return defaultServiceConfig.maxAppInstances;
+            }
+            return maxAppInstances;
+        }
+
+        public int getMaxRequestsPerSecond() {
+            if (maxRequestsPerSecondSet) {
+                return maxRequestsPerSecond;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.maxRequestsPerSecondSet) {
+                return defaultServiceConfig.maxRequestsPerSecond;
+            }
+            return maxRequestsPerSecond;
+        }
+
+        public int getRoundsToAverage() {
+            if (roundsToAverageSet) {
+                return roundsToAverage;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.roundsToAverageSet) {
+                return defaultServiceConfig.roundsToAverage;
+            }
+            return roundsToAverage;
+        }
+
+        public int getInstancesPerScaleUp() {
+            if (instancesPerScaleUpSet) {
+                return instancesPerScaleUp;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.instancesPerScaleUpSet) {
+                return defaultServiceConfig.instancesPerScaleUp;
+            }
+            return instancesPerScaleUp;
+        }
+
+        public int getMessageExpiryTime() {
+            if (messageExpiryTimeSet) {
+                return messageExpiryTime;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.messageExpiryTimeSet) {
+                return defaultServiceConfig.messageExpiryTime;
+            }
+            return messageExpiryTime;
+        }
+
+        public String getSubDomain() {
+            if (subDomainSet) {
+                return subDomain;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.subDomainSet) {
+                return defaultServiceConfig.subDomain;
+            }
+            return subDomain;
+        }
+
+        public void setMin_app_instances(int minAppInstances) {
+//            if (minAppInstances < 1) {
+//                LoadBalancerConfigUtil.handleException("minAppInstances in the autoscaler task configuration " +
+//                        "should be at least 1");
+//            }
+            this.minAppInstances = minAppInstances;
+            this.minAppInstancesSet = true;
+        }
+
+        public void setMax_app_instances(int maxAppInstances) {
+            if (maxAppInstances < 1) {
+                LoadBalancerConfigUtil.handleException("maxAppInstances in the autoscaler task configuration " +
+                        "should be at least 1");
+            }
+            this.maxAppInstances = maxAppInstances;
+            this.maxAppInstancesSet = true;
+        }
+        
+		public void setAlarming_upper_rate(double rate) {
+			if (rate > 0 && rate <= 1) {
+				this.alarmingUpperRate = rate;
+				this.alarmingUpperRateSet = true;
+			}
+		}
+
+        public void setAlarming_lower_rate(double rate) {
+			if (rate > 0 && rate <= 1) {
+				this.alarmingLowerRate = rate;
+				this.alarmingLowerRateSet = true;
+			}
+        }
+        
+		public void setScale_down_factor(double factor) {
+			if (factor > 0 && factor <= 1) {
+				this.scaleDownFactor = factor;
+				this.scaleDownFactorSet = true;
+			}
+		}
+        
+        public void setMax_requests_per_second(int rps) {
+            this.maxRequestsPerSecond = rps;
+            this.maxRequestsPerSecondSet = true;
+        }
+
+        public void setRounds_to_average(int roundsToAverage) {
+            this.roundsToAverage = roundsToAverage;
+            this.roundsToAverageSet = true;
+        }
+
+        public void setInstances_per_scale_up(int instancesPerScaleUp) {
+            if (instancesPerScaleUp < 1) {
+                LoadBalancerConfigUtil.handleException("instancesPerScaleUp in the autoscaler task configuration " +
+                        "should be at least 1");
+            }
+            this.instancesPerScaleUp = instancesPerScaleUp;
+            this.instancesPerScaleUpSet = true;
+        }
+
+        public void setMessage_expiry_time(int messageExpiryTime) {
+            if (messageExpiryTime < 1) {
+                LoadBalancerConfigUtil.handleException("messageExpiryTime in the autoscaler task configuration " +
+                        "should be at least 1");
+            }
+            this.messageExpiryTime = messageExpiryTime;
+            this.messageExpiryTimeSet = true;
+        }
+
+        public void setHosts(String hostsStr) {
+            // clear all unnecessary values --> property will get overwritten
+            hosts = new ArrayList<String>();
+            // there can be multiple hosts, let's find out.
+            String[] host = hostsStr.split(Constants.HOSTS_DELIMITER);
+
+            for (String string : host) {
+                if (!string.isEmpty()) {
+                    this.hosts.add(string);
+                }
+            }
+
+        }
+
+        public void setUrl_suffix(String suffix) {
+            // clear all unnecessary values --> property will get overwritten
+            //hosts = new ArrayList<String>();
+            // there can be multiple hosts, let's find out.
+            String[] suffixes = suffix.split(Constants.HOSTS_DELIMITER);
+            int count = 0;
+            if(suffixes.length == this.hosts.size()) {
+                for (String string : suffixes) {
+                    if (!string.isEmpty()) {
+                        this.urlSuffixes.put(this.hosts.get(count), string);
+                        count++;
+                    }
+                }
+            
+            } else {
+                //Error
+            }
+        }
+
+        public Map<String, String> getUrl_suffix() {
+            return this.urlSuffixes;
+        }
+
+        public void setTenant_range(String range) {
+            this.tenantRange = range;
+        }
+
+        public void setSub_domain(String subDomain) {
+            this.subDomain = subDomain;
+            this.subDomainSet = true;
+        }
+
+        public void setDomain(String domain) {
+            this.domain = domain;
+        }
+        
+        public boolean equals(ServiceConfiguration config) {
+            return this.domain.equals(config.getDomain()) &&
+                    this.subDomain.equals(config.getSubDomain());
+        }
+        
+        public int hashCode() {
+            return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
+                    append(domain).
+                    append(subDomain).
+                    toHashCode();
+        }
+
+        public double getAlarmingUpperRate() {
+            if (alarmingUpperRateSet) {
+                return alarmingUpperRate;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.alarmingUpperRateSet) {
+                return defaultServiceConfig.alarmingUpperRate;
+            }
+            return alarmingUpperRate;
+        }
+
+        public double getAlarmingLowerRate() {
+            if (alarmingLowerRateSet) {
+                return alarmingLowerRate;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.alarmingLowerRateSet) {
+                return defaultServiceConfig.alarmingLowerRate;
+            }
+            return alarmingLowerRate;
+        }
+
+        public double getScaleDownFactor() {
+            if (scaleDownFactorSet) {
+                return scaleDownFactor;
+            } else if (defaultServiceConfig != null && defaultServiceConfig.scaleDownFactorSet) {
+                return defaultServiceConfig.scaleDownFactor;
+            }
+            return scaleDownFactor;
+        }
+    }
+
+    public Map<String, Set<String>> getHostNamesTracker() {
+        return hostNamesTracker;
+    }
+
+
+    public Map<String, Map<String, ServiceConfiguration>> getServiceConfigurations() {
+        return serviceConfigurations;
+    }
+
+
+    public Node getRootNode() {
+        return rootNode;
+    }
+
+
+    public void setRootNode(Node rootNode) {
+        this.rootNode = rootNode;
+    }
+
+    public static void setInstance(LoadBalancerConfiguration instance) {
+        LoadBalancerConfiguration.instance = instance;
+    }
+
+	public Map<String, List<ServiceConfiguration>> getServiceNameToServiceConfigurations() {
+    	return serviceNameToServiceConfigurations;
+    }
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
new file mode 100644
index 0000000..ab58e12
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
@@ -0,0 +1,51 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.conf.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.apache.stratos.lb.common.service.impl.LoadBalancerConfigurationServiceImpl;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.apache.stratos.lb.common.service.impl.LoadBalancerConfigurationServiceImpl;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.apache.stratos.lb.common.service.impl.LoadBalancerConfigurationServiceImpl;
+
+/**
+ * Registering {@link org.apache.stratos.lb.common.service.LoadBalancerConfigurationService} .
+ * @scr.component name="org.wso2.carbon.lb.common" immediate="true"
+ */
+public class LoadBalancerConfigurationDSComponent {
+
+    private static final Log log = LogFactory.getLog(LoadBalancerConfigurationDSComponent.class);
+
+    protected void activate(ComponentContext context) {
+        try {
+            BundleContext bundleContext = context.getBundleContext();
+            bundleContext.registerService(LoadBalancerConfigurationService.class.getName(),
+                                          new LoadBalancerConfigurationServiceImpl(), null);
+
+            log.debug("******* Load Balancer Configuration Service bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("******* Load Balancer Configuration Service bundle is failed to activate ****", e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/structure/Node.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/structure/Node.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/structure/Node.java
new file mode 100644
index 0000000..579eda5
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/structure/Node.java
@@ -0,0 +1,356 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.conf.structure;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.commons.lang.builder.HashCodeBuilder;
+
+/**
+ * This is the basic data structure which holds a <i>Nginx</i> formatted configuration file.
+ * 
+ */
+public class Node implements Serializable{
+
+    private static final long serialVersionUID = 4071569903421115370L;
+
+    /**
+     * Name of this Node element
+     */
+    private String name;
+
+    /**
+     * Every node can have 0..n child nodes. 
+     * They are kept in a List.
+     */
+    private List<Node> childNodes = new ArrayList<Node>();
+
+    /**
+     * Every node can have 0..n properties. 
+     * They are kept in a Map, in the order they appear.
+     * Key: property name
+     * Value: property value
+     */
+    private Map<String, String> properties = new LinkedHashMap<String, String>();
+
+    public void setChildNodes(List<Node> childNodes) {
+        this.childNodes = childNodes;
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+
+    /**
+     * This will convert each child Node of this Node to a String.
+     * @return a string which represents child nodes of this node.
+     */
+    public String childNodesToString(int indentation) {
+        StringBuilder childNodesString = new StringBuilder();
+        indentation++;
+        
+        for (Node node : childNodes) {
+            childNodesString.append(node.toString(indentation)+"\n");
+        }
+        
+        return childNodesString.toString();
+    }
+
+    /**
+     * This will try to find a child Node of this Node, which has the given name.
+     * @param name name of the child node to find.
+     * @return child Node object if found or else <code>null</code>.
+     */
+    public Node findChildNodeByName(String name) {
+        for (Node aNode : childNodes) {
+            if (aNode.getName().equals(name)) {
+                return aNode;
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Returns the name of this Node. 
+     * @return name of the node.
+     */
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * Returns child nodes List of this Node.
+     * @return List of Node
+     */
+    public List<Node> getChildNodes() {
+        return childNodes;
+    }
+
+    /**
+     * Returns properties Map of this Node.
+     * @return Map whose keys and values are String.  
+     */
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+
+    /**
+     * Returns the value of a given property.
+     * @param key name of a property.
+     * @return trimmed value if the property is found in this Node, or else <code>null</code>. 
+     */
+    public String getProperty(String key) {
+        if (properties.get(key) == null) {
+            return null;
+        }
+        return properties.get(key).trim();
+    }
+
+    /**
+     * Returns all the properties of this Node as a String.
+     * Key and value of the property is separated by a tab (\t) character and
+     * each property is separated by a new line character.
+     * @param indentation relative number of tabs 
+     * @return properties of this node as a String.
+     */
+    public String propertiesToString(int indentation) {
+        
+        String indent = getIndentation(indentation);
+        
+        StringBuilder sb = new StringBuilder();
+        for (Map.Entry<String, String> entry : properties.entrySet()) {
+            // hack to get a quick fix in.
+            if (!"tenant_id".equals(entry.getKey()) && !"alias".equals(entry.getKey())) {
+                sb.append(indent + entry.getKey() + "\t" + entry.getValue() + ";\n");
+            }
+        }
+        return sb.toString();
+    }
+    
+    /**
+     * Removes the first occurrence of a node having the given name
+     * and returns the removed {@link Node}.
+     * @param name name of the child node to be removed.
+     * @return removed {@link Node} or else <code>null</code>.
+     */
+    public Node removeChildNode(String name) {
+        Node aNode = findChildNodeByName(name);
+        
+        if(aNode != null){
+            if(childNodes.remove(aNode)){
+                return aNode;
+            }
+        }
+        
+        return null;
+    }
+
+    /**
+     * Removes the first occurrence of a node equals to the given node.
+     * @param node {@link Node} to be removed.
+     * @return whether the removal is successful or not.
+     */
+    public boolean removeChildNode(Node node){
+
+        return childNodes.remove(node);
+    }
+    
+    /**
+     * Sets the name of this Node.
+     * @param name String to be set as the name.
+     */
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    /**
+     * Appends a child node at the end of the List of child nodes of this Node, if 
+     * a similar node is not already present as a child node.
+     * @param aNode child Node to be appended.
+     */
+    public void appendChild(Node aNode) {
+        if (aNode != null && !nodeAlreadyPresent(aNode)) {
+            childNodes.add(aNode);
+        }
+    }
+    
+    /**
+     * Adds a new property to properties Map of this Node if and only if 
+     * key is not <code>null</code>.
+     * @param key name of the property to be added.
+     * @param value value of the property to be added.
+     */
+    public void addProperty(String key, String value) {
+        if (key != null) {
+            properties.put(key, value);
+        }
+    }
+    
+    /**
+     * Convert this Node to a String which is in <i>Nginx</i> format.
+     * <br/>
+     * Sample:
+     * <br></br>
+     * <code>
+     * ij {
+     * <br/>
+     * klm n;
+     * <br/>
+     * pq {
+     * <br/>
+     * rst u;
+     * <br/>
+     * }
+     * <br/>
+     * }
+     * <br/>
+     * </code>
+     */
+    public String toString() {
+        
+        String nodeString = 
+                getName()+" {\n" +
+                (propertiesToString(1)) +
+                (childNodesToString(1)) +
+                "}";
+        
+        return nodeString;
+    }
+    
+    public boolean equals(Object node) {
+        
+        if(node instanceof Node){
+            return this.getName().equals(((Node) node).getName()) &&
+                    isIdenticalProperties(this.getProperties(), ((Node) node).getProperties()) &&
+                    isIdenticalChildren(this.getChildNodes(), ((Node) node).getChildNodes());
+        }
+        
+        return false;
+        
+    }
+    
+    public int hashCode() {
+        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
+            append(name).
+            append(properties).
+            append(childNodes).
+            toHashCode();
+    }
+    
+    private boolean isIdenticalChildren(List<Node> childNodes1, List<Node> childNodes2) {
+        
+        if(childNodes1.size() != childNodes2.size()){
+            return false;
+        }
+        
+        for (Node node1 : childNodes1) {
+            int i=0;
+            for (Node node2 : childNodes2) {
+                
+                i++;
+                if(node1.equals(node2)){
+                    break;
+                }
+                
+                if(i == childNodes1.size()){
+                    return false;
+                }
+                
+            }
+        }
+        
+        return true;
+    }
+    
+    private boolean nodeAlreadyPresent(Node aNode){
+        
+        for(Node node : this.childNodes){
+            if(node.equals(aNode)){
+                return true;
+            }
+        }
+        
+        return false;
+    }
+
+    private boolean isIdenticalProperties(Map<String, String> map1,
+        Map<String, String> map2) {
+        
+        if(map1.size() != map2.size()){
+            return false;
+        }
+        
+        for (Iterator<Entry<String, String>> iterator1 = map1.entrySet().iterator(); iterator1.hasNext();) {
+            Map.Entry<String, String> entry1 = (Map.Entry<String, String>) iterator1.next();
+            
+            int i=0;
+            
+            for(Iterator<Entry<String, String>> iterator2 = map2.entrySet().iterator(); iterator2.hasNext();) {
+                Map.Entry<String, String> entry2 = (Map.Entry<String, String>) iterator2.next();
+                
+                i++;
+                
+                if((entry1.getKey().equals(entry2.getKey()) &&
+                        entry1.getValue().equals(entry2.getValue()))){
+                    
+                    break;
+                }
+                
+                if(i == map1.size()){
+                    return false;
+                }
+                
+            }
+        }
+        
+        return true;
+    }
+
+    private String toString(int indentation){
+        
+        String indent = getIndentation(indentation-1);
+        
+        String nodeString = 
+                indent + getName()+" {\n" +
+                (propertiesToString(indentation)) +
+                (childNodesToString(indentation)) +
+                indent + "}";
+        
+        return nodeString;
+    }
+    
+    private String getIndentation(int tabs){
+        
+        StringBuilder indent = new StringBuilder("");
+        
+        for (int i = 0; i < tabs; i++) {
+            indent.append("\t");
+        }
+                
+        return indent.toString();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/structure/NodeBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/structure/NodeBuilder.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/structure/NodeBuilder.java
new file mode 100644
index 0000000..4801c1d
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/structure/NodeBuilder.java
@@ -0,0 +1,140 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.conf.structure;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.common.conf.util.Constants;
+
+/**
+ * This responsible for build up a Node object from a given content.
+ * Every closing brace should be in a new line.
+ */
+public class NodeBuilder {
+    
+    private static final Log log = LogFactory.getLog(NodeBuilder.class);
+
+    /**
+     * This method is useful when you do not have a root node in your content.
+     * @param aNode
+     *            Node object whose name set.
+     * @param content
+     *            should be something similar to following.
+     * 
+     *            abc d;
+     *            efg h;
+     *            # comment 
+     *            ij { # comment
+     *              klm n;
+     * 
+     *              pq {
+     *                  rst u;
+     *              }
+     *            }
+     * 
+     * @return fully constructed Node
+     */
+    public static Node buildNode(Node aNode, String content) {
+
+    	if(content == null || content.isEmpty()){
+    		return aNode;
+    	}
+    	
+        String[] lines = content.split("\n");
+
+        for (int i = 0; i < lines.length; i++) {
+            String line = lines[i].trim();
+
+            // avoid line comments
+            if (!line.startsWith(Constants.NGINX_COMMENT)) {
+                
+                // skip comments in-line 
+                if(line.contains(Constants.NGINX_COMMENT)){
+                    line = line.substring(0, line.indexOf(Constants.NGINX_COMMENT));
+                }
+                
+                // another node is detected and it is not a variable starting from $
+                if (line.contains(Constants.NGINX_NODE_START_BRACE) && 
+                        !line.contains(Constants.NGINX_VARIABLE)) {
+                    
+                    try {
+                        Node childNode = new Node();
+                        childNode.setName(line.substring(0, line.indexOf(Constants.NGINX_NODE_START_BRACE)).trim());
+
+                        StringBuilder sb = new StringBuilder();
+
+                        int matchingBraceTracker = 1;
+
+                        while (!line.contains(Constants.NGINX_NODE_END_BRACE) || matchingBraceTracker != 0) {
+                            i++;
+                            if (i == lines.length) {
+                                break;
+                            }
+                            line = lines[i];
+                            if (line.contains(Constants.NGINX_NODE_START_BRACE)) {
+                                matchingBraceTracker++;
+                            }
+                            if (line.contains(Constants.NGINX_NODE_END_BRACE)) {
+                                matchingBraceTracker--;
+                            }
+                            sb.append(line + "\n");
+                        }
+
+                        childNode = buildNode(childNode, sb.toString());
+						if (aNode == null) {
+							aNode = childNode;
+						} else {
+							aNode.appendChild(childNode);
+						}
+
+                    } catch (Exception e) {
+                        String msg = "Malformatted element is defined in the configuration file. [" +
+                                i + "] \n";
+                        log.error(msg , e);
+                        throw new RuntimeException(msg + line, e);
+                    }
+
+                }
+                // this is a property
+                else {
+                    if (!line.isEmpty() && !Constants.NGINX_NODE_END_BRACE.equals(line)) {
+                        String[] prop = line.split(Constants.NGINX_SPACE_REGEX);
+                        String value = line.substring(prop[0].length(), line.indexOf(Constants.NGINX_LINE_DELIMITER)).trim();
+                        try {
+                            aNode.addProperty(prop[0], value);
+                        } catch (Exception e) {
+                            String msg = "Malformatted property is defined in the configuration file. [" +
+                                    i + "] \n";
+                            log.error(msg, e);
+                            throw new RuntimeException(msg + line, e);
+                        }
+                    }
+                }
+            
+            }
+        }
+
+        return aNode;
+
+    }
+    
+    public static Node buildNode(String content) {
+	    return buildNode(null, content);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/Constants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/Constants.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/Constants.java
new file mode 100644
index 0000000..8cf6c2f
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/Constants.java
@@ -0,0 +1,50 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.conf.util;
+
+/**
+ * This keeps the element names used in loadbalancer.conf file
+ */
+public class Constants {
+    
+    public static final String LOAD_BALANCER_ELEMENT = "loadbalancer";
+    public static final String SERVICES_ELEMENT = "services";
+    public static final String DEFAULTS_ELEMENT = "defaults";
+    public static final String HOSTS_ELEMENT = "hosts";
+    public static final String HOSTS_DELIMITER = ",";
+    public static final String DOMAIN_ELEMENT = "domains";
+    public static final String TENANT_RANGE_ELEMENT = "tenant_range";
+    public static final String SUB_DOMAIN_ELEMENT = "sub_domain";
+    public static final String TENANT_RANGE_DELIMITER = "-";
+    public static final String UNLIMITED_TENANT_RANGE = "*";
+    public static final String AUTOSCALER_ENABLE_ELEMENT = "enable_autoscaler";
+    public static final String SUB_DOMAIN_DELIMITER = "#";
+    public static final String DEFAULT_SUB_DOMAIN = "__$default";
+    
+    /* Nginx format related constants */
+    
+    public static final String NGINX_COMMENT = "#";
+    public static final String NGINX_NODE_START_BRACE = "{";
+    public static final String NGINX_NODE_END_BRACE = "}";
+    public static final String NGINX_VARIABLE = "${";
+    public static final String NGINX_LINE_DELIMITER = ";";
+    public static final String NGINX_SPACE_REGEX = "[\\s]+";
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/HostContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/HostContext.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/HostContext.java
new file mode 100644
index 0000000..d9ad14a
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/HostContext.java
@@ -0,0 +1,161 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.conf.util;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.synapse.endpoints.algorithms.AlgorithmContext;
+import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
+
+/**
+ * For each unique host name defined in loadbalancer configuration, we'll generate
+ * this object. 
+ */
+public class HostContext {
+    
+    /**
+     * A unique identifier to identify this {@link #HostContext()}
+     */
+    private String hostName;
+    
+    /**
+     * Key - tenant id
+     * Value - <code>TenantDomainContext</code> of the corresponding tenant
+     */
+    private Map<Integer, TenantDomainContext> tenantIdToTenantDomainContextMap = new HashMap<Integer, TenantDomainContext>();
+    
+    /**
+     * AlgorithmContext of this host
+     */
+    private AlgorithmContext algorithmContext;
+    
+    /**
+     * Load balance algorithm of this host
+     */
+    private LoadbalanceAlgorithm algorithm;
+    
+    private String urlSuffix;
+    
+    public HostContext(String hostName) {
+        this.hostName = hostName;
+    }
+    
+    public void addTenantDomainContexts(List<TenantDomainContext> ctxts) {
+        
+        for (TenantDomainContext tenantDomainContext : ctxts) {
+            tenantIdToTenantDomainContextMap.put(tenantDomainContext.getTenantId(), tenantDomainContext);
+        }
+    }
+    
+    @Deprecated
+    public void addTenantDomainContext(TenantDomainContext ctxt) {
+        tenantIdToTenantDomainContextMap.put(ctxt.getTenantId(), ctxt);
+    }
+    
+    public TenantDomainContext getTenantDomainContext(int tenantId) {
+        return tenantIdToTenantDomainContextMap.get(tenantId);
+    }
+    
+    /**
+     * Returns all the {@link TenantDomainContext} entries.
+     */
+    public Collection<TenantDomainContext> getTenantDomainContexts() {
+        return tenantIdToTenantDomainContextMap.values();
+    }
+    
+    /**
+     * Given a tenant id, this will return its domain.
+     * @param tenantId 
+     * @return domain if this tenant has a dedicated one, it will be returned.
+     * If not, and there's a default (*) domain, it will be returned.
+     * If neither of the above is defined, null will be returned.
+     */
+    public String getDomainFromTenantId(int tenantId) {
+        if (tenantIdToTenantDomainContextMap.get(tenantId) == null) {
+            // if there's no specific domain for this tenant, we will redirect it to the default
+            // cluster
+            
+            if(tenantIdToTenantDomainContextMap.get(0) == null){
+                return null;
+            }
+            
+            return tenantIdToTenantDomainContextMap.get(0).getDomain();
+        }
+
+        return tenantIdToTenantDomainContextMap.get(tenantId).getDomain();
+    }
+    
+    /**
+     * Given a tenant id, this will return its sub domain.
+     * @param tenantId 
+     * @return sub_domain if this tenant has a dedicated one, it will be returned.
+     * If not, and there's a default (*) sub domain, it will be returned.
+     * If neither of the above is defined, null will be returned.
+     */
+    public String getSubDomainFromTenantId(int tenantId) {
+        if (tenantIdToTenantDomainContextMap.get(tenantId) == null) {
+            // if there's no specific domain for this tenant, we will redirect it to the default
+            // cluster
+            
+            if(tenantIdToTenantDomainContextMap.get(0) == null){
+                return null;
+            }
+            
+            return tenantIdToTenantDomainContextMap.get(0).getSubDomain();
+        }
+
+        return tenantIdToTenantDomainContextMap.get(tenantId).getSubDomain();
+    }
+
+    public String getHostName() {
+        return hostName;
+    }
+    
+    public LoadbalanceAlgorithm getAlgorithm() {
+        return algorithm;
+    }
+
+    public AlgorithmContext getAlgorithmContext() {
+        return algorithmContext;
+    }
+
+    public void setAlgorithmContext(AlgorithmContext algorithmContext) {
+        this.algorithmContext = algorithmContext;
+    }
+
+    public void setAlgorithm(LoadbalanceAlgorithm algorithm) {
+        this.algorithm = algorithm;
+    }
+
+    public Map<Integer, TenantDomainContext> getTenantIdToTenantDomainContextMap() {
+        return tenantIdToTenantDomainContextMap;
+    }
+    
+    public void setUrlSuffix(String suffix)  {
+        this.urlSuffix = suffix;
+    }
+
+    public String getUrlSuffix() {
+        return this.urlSuffix;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/LoadBalancerConfigUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/LoadBalancerConfigUtil.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/LoadBalancerConfigUtil.java
new file mode 100644
index 0000000..61eceb4
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/LoadBalancerConfigUtil.java
@@ -0,0 +1,291 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.conf.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import sun.misc.BASE64Encoder;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Utility methods for Autoscale mediator
+ */
+public final class LoadBalancerConfigUtil {
+
+    private static final Log log = LogFactory.getLog(LoadBalancerConfigUtil.class);
+
+    private LoadBalancerConfigUtil() {
+    }
+
+    /**
+     * handles the exception
+     * 
+     * @param msg
+     *            exception message
+     */
+    public static void handleException(String msg) {
+        log.error(msg);
+        throw new RuntimeException(msg);
+    }
+
+    /**
+     * handles the exception
+     * 
+     * @param msg
+     *            exception message
+     * @param e
+     *            exception
+     */
+    public static void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new SynapseException(msg, e);
+    }
+
+    /**
+     * Replaces the variables
+     * 
+     * @param text
+     *            input string
+     * @return output String
+     */
+    public static String replaceVariables(String text) {
+        int indexOfStartingChars;
+        int indexOfClosingBrace;
+
+        // The following condition deals with properties.
+        // Properties are specified as ${system.property},
+        // and are assumed to be System properties
+        if ((indexOfStartingChars = text.indexOf("${")) != -1 &&
+            (indexOfClosingBrace = text.indexOf("}")) != -1) { // Is a property used?
+            String var = text.substring(indexOfStartingChars + 2, indexOfClosingBrace);
+
+            String propValue = System.getProperty(var);
+            if (propValue == null) {
+                propValue = System.getenv(var);
+            }
+            if (propValue != null) {
+                text =
+                       text.substring(0, indexOfStartingChars) + propValue +
+                               text.substring(indexOfClosingBrace + 1);
+            }
+        }
+        return text;
+    }
+
+    public static String getUserData(String payloadFileName) {
+        String userData = null;
+        try {
+            File file = new File(payloadFileName);
+            if (!file.exists()) {
+                handleException("Payload file " + payloadFileName + " does not exist");
+            }
+            if (!file.canRead()) {
+                handleException("Payload file " + payloadFileName + " does cannot be read");
+            }
+            byte[] bytes = LoadBalancerConfigUtil.getBytesFromFile(file);
+            if (bytes != null) {
+                BASE64Encoder encoder = new BASE64Encoder();
+                userData = encoder.encode(bytes);
+            }
+        } catch (Exception e) {
+            LoadBalancerConfigUtil.handleException("Cannot read data from payload file " +
+                                                   payloadFileName, e);
+
+        }
+        return userData;
+    }
+
+    /**
+     * Returns the contents of the file in a byte array
+     * 
+     * @param file
+     *            - Input File
+     * @return Bytes from the file
+     * @throws java.io.IOException
+     *             , if retrieving the file contents failed.
+     */
+    public static byte[] getBytesFromFile(File file) throws IOException {
+        if (!file.exists()) {
+            log.error("Payload file " + file.getAbsolutePath() + " does not exist");
+            return null;
+        }
+        InputStream is = new FileInputStream(file);
+        byte[] bytes;
+
+        try {
+            // Get the size of the file
+            long length = file.length();
+
+            // You cannot create an array using a long type.
+            // It needs to be an int type.
+            // Before converting to an int type, check
+            // to ensure that file is not larger than Integer.MAX_VALUE.
+            if (length > Integer.MAX_VALUE) {
+                if (log.isDebugEnabled()) {
+                    log.debug("File is too large");
+                }
+            }
+
+            // Create the byte array to hold the data
+            bytes = new byte[(int) length];
+
+            // Read in the bytes
+            int offset = 0;
+            int numRead;
+            while (offset < bytes.length &&
+                   (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
+                offset += numRead;
+            }
+
+            // Ensure all the bytes have been read in
+            if (offset < bytes.length) {
+                throw new IOException("Could not completely read file " + file.getName());
+            }
+        } finally {
+            // Close the input stream and return bytes
+            is.close();
+        }
+
+        return bytes;
+    }
+
+    /**
+     * @deprecated
+     *             Extract the domain part given a string which is in
+     *             &lt;sub_domain&gt;#&lt;domain&gt; format.
+     * @param str
+     *            in &lt;sub_domain&gt;#&lt;domain&gt; format.
+     * @return the domain part. If # is not present this will return the trimmed
+     *         input string.
+     */
+    public static String getDomain(String str) {
+        str = str.trim();
+        if (!str.contains(Constants.SUB_DOMAIN_DELIMITER)) {
+            return str;
+        }
+        return str.substring(str.indexOf(Constants.SUB_DOMAIN_DELIMITER) + 1);
+    }
+
+    /**
+     * @deprecated
+     *             Extract the sub_domain part given a string which is in
+     *             &lt;sub_domain&gt;#&lt;domain&gt; format.
+     * @param str
+     *            in &lt;sub_domain&gt;#&lt;domain&gt; format.
+     * @return the sub_domain part. If # is not present this will return <code>null</code>.
+     */
+    public static String getSubDomain(String str) {
+        str = str.trim();
+        if (!str.contains(Constants.SUB_DOMAIN_DELIMITER)) {
+            return null;
+        }
+        return str.substring(0, str.indexOf(Constants.SUB_DOMAIN_DELIMITER));
+    }
+
+    // public static EC2InstanceManager createEC2InstanceManager(String accessKey,
+    // String secretKey,
+    // String instanceMgtEPR) {
+    // AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
+    // AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentials);
+    // ec2Client.setEndpoint(instanceMgtEPR);
+    // return new EC2InstanceManager(ec2Client);
+    // }
+
+    public static List<TenantDomainContext> getTenantDomainContexts(String tenantRange, String domain, String subDomain) {
+        
+        List<TenantDomainContext> ctxts = new ArrayList<TenantDomainContext>();
+        List<Integer> tenantIds = getTenantIds(tenantRange);
+        
+        // iterate through all tenant ids under this host
+        for (Integer tId : tenantIds) {
+
+            // create a new TenantDomainContext
+            TenantDomainContext tenantCtxt =
+                                             new TenantDomainContext(
+                                                                     tId,
+                                                                     domain,
+                                                                     subDomain);
+            // add it to the list
+            ctxts.add(tenantCtxt);
+        }
+        
+        return ctxts;
+        
+    }
+    
+    /**
+     * This method will read the tenant range string and return a list of tenant ids
+     * which is derived from tenant range string.
+     * 
+     * @param tenantRange
+     * @return list of tenant ids.
+     */
+    public static List<Integer> getTenantIds(String tenantRange) {
+
+        List<Integer> tenantIds = new ArrayList<Integer>();
+
+        String[] parsedLine = tenantRange.trim().split("-");
+
+        if (parsedLine[0].equalsIgnoreCase("*")) {
+            tenantIds.add(0);
+
+        } else if (parsedLine.length == 1) {
+            try {
+                int tenantId = Integer.parseInt(tenantRange);
+                tenantIds.add(tenantId);
+
+            } catch (NumberFormatException e) {
+                String msg = "Invalid tenant range is specified : " + tenantRange;
+                log.error(msg, e);
+                throw new RuntimeException(msg, e);
+            }
+        } else if (parsedLine.length == 2) {
+            try {
+
+                int startIndex = Integer.parseInt(parsedLine[0]);
+                int endIndex = Integer.parseInt(parsedLine[1]);
+
+                for (int tenantId = startIndex; tenantId <= endIndex; tenantId++) {
+
+                    tenantIds.add(tenantId);
+                }
+
+            } catch (NumberFormatException e) {
+                String msg = "Invalid tenant range is specified : " + tenantRange;
+                log.error(msg, e);
+                throw new RuntimeException(msg, e);
+            }
+
+        } else {
+            String msg = "Invalid tenant range is specified : " + tenantRange;
+            log.error(msg);
+            throw new RuntimeException(msg);
+        }
+
+        return tenantIds;
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/TenantDomainContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/TenantDomainContext.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/TenantDomainContext.java
new file mode 100644
index 0000000..65a4b45
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/conf/util/TenantDomainContext.java
@@ -0,0 +1,80 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.conf.util;
+
+/**
+ * This object will hold all the data related to a tenant.
+ */
+public class TenantDomainContext {
+    
+    /**
+     * this is the unique identifier for this object
+     */
+    private int tenantId;
+    
+    /**
+     * Domain, which this tenant belongs to.
+     */
+    private String domain;
+    
+    /**
+     * Sub domain, which this tenant belongs to.
+     */
+    private String subDomain;
+    
+    public TenantDomainContext(int tenantId, String domain, String subDomain) {
+        this.tenantId = tenantId;
+        this.domain = domain;
+        this.subDomain = subDomain;
+    }
+    
+    
+    /** Getters and Setters **/
+
+    public int getTenantId() {
+        return tenantId;
+    }
+
+    public void setTenantId(int tenantId) {
+        this.tenantId = tenantId;
+    }
+
+    public String getDomain() {
+        return domain;
+    }
+
+    public void setDomain(String domain) {
+        this.domain = domain;
+    }
+
+    public String getSubDomain() {
+        return subDomain;
+    }
+
+    public void setSubDomain(String subDomain) {
+        this.subDomain = subDomain;
+    }
+    
+    
+    /** End of Getters and Setters **/
+    
+    
+    
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
new file mode 100644
index 0000000..4341728
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
@@ -0,0 +1,58 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.group.mgt;
+
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.management.DefaultGroupManagementAgent;
+import org.apache.synapse.endpoints.dispatch.SALSessions;
+import org.apache.stratos.lb.common.conf.util.Constants;
+
+/**
+ * This GroupManagementAgent can handle group membership based on cluster sub-domains.
+ */
+public class SubDomainAwareGroupManagementAgent extends DefaultGroupManagementAgent {
+
+    private String subDomain;
+
+    public SubDomainAwareGroupManagementAgent(String subDomain) {
+        this.subDomain = subDomain;
+    }
+
+    @Override
+    public void applicationMemberAdded(Member member) {
+        String subDomain = member.getProperties().getProperty("subDomain");
+        if ((subDomain == null && Constants.DEFAULT_SUB_DOMAIN.equals(this.subDomain)) ||
+            subDomain.equals(this.subDomain)) {
+            super.applicationMemberAdded(member);
+        }
+    }
+
+    @Override
+    public void applicationMemberRemoved(Member member) {
+        
+        // remove the sessions bound with this member
+        SALSessions.getInstance().removeSessionsOfMember(member);
+        
+        String subDomain = member.getProperties().getProperty("subDomain");
+        if ((subDomain == null && Constants.DEFAULT_SUB_DOMAIN.equals(this.subDomain)) ||
+            subDomain.equals(this.subDomain)) {
+            super.applicationMemberRemoved(member);
+        }
+    }
+}


[33/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/Repository.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/Repository.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/Repository.java
deleted file mode 100644
index a951e78..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/Repository.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.dao;
-
-public class Repository {
-	private int repoId;
-	private String repoName;
-    private String repoUserName;
-    private String repoUserPassword;
-
-	public int getRepoId() {
-		return repoId;
-	}
-
-	public void setRepoId(int repoId) {
-		this.repoId = repoId;
-	}
-
-	public String getRepoName() {
-		return repoName;
-	}
-
-	public void setRepoName(String repoName) {
-		this.repoName = repoName;
-	}
-
-    public String getRepoUserName() {
-        return repoUserName;
-    }
-
-    public void setRepoUserName(String repoUserName) {
-        this.repoUserName=repoUserName;
-    }
-
-    public String getRepoUserPassword() {
-        return repoUserPassword;
-    }
-
-    public void setRepoUserPassword(String repoUserPassword) {
-        this.repoUserPassword=repoUserPassword;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/RepositoryCredentials.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/RepositoryCredentials.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/RepositoryCredentials.java
deleted file mode 100644
index 90670e7..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dao/RepositoryCredentials.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package org.apache.stratos.adc.mgt.dao;
-
-public class RepositoryCredentials {
-
-	private String url;
-	private String userName;
-	private String password;
-	public String getUrl() {
-    	return url;
-    }
-	public void setUrl(String url) {
-    	this.url = url;
-    }
-	public String getUserName() {
-    	return userName;
-    }
-	public void setUserName(String userName) {
-    	this.userName = userName;
-    }
-	public String getPassword() {
-    	return password;
-    }
-	public void setPassword(String password) {
-    	this.password = password;
-    }
-	
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dns/DNSManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dns/DNSManager.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dns/DNSManager.java
deleted file mode 100644
index ceb77fb..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dns/DNSManager.java
+++ /dev/null
@@ -1,86 +0,0 @@
- /*
-  * Copyright WSO2, Inc. (http://wso2.com)
-  *
-  * Licensed under the Apache License, Version 2.0 (the "License");
-  * you may not use this file except in compliance with the License.
-  * You may obtain a copy of the License at
-  *
-  * http://www.apache.org/licenses/LICENSE-2.0
-  *
-  * Unless required by applicable law or agreed to in writing, software
-  * distributed under the License is distributed on an "AS IS" BASIS,
-  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  * See the License for the specific language governing permissions and
-  * limitations under the License.
-  */
-
-package org.apache.stratos.adc.mgt.dns;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.utils.CartridgeConstants;
-
-/**
- * This class is for handling dns entries.
- */
-public class DNSManager {
-	private static final Log log = LogFactory.getLog(DNSManager.class);
-
-    /**
-   	 * This is get called when there is a need of adding new sub domain to
-   	 * exciting domain.
-   	 * It will append required text to bind9 zone file and reload bind9 server.
-   	 * Note: make sure the user who run ADC has got rights to run sudo scripts
-   	 * without password
-   	 *
-   	 * @param subDomain
-   	 *            will be added in front of domain
-   	 */
-   	public void addNewSubDomain(String subDomain, String ip) {
-   		try {
-   			Runtime.getRuntime()
-   			       .exec(CartridgeConstants.SUDO_SH + " " +
-             // script script file that will be used to edit
-             // required files
-             System.getProperty(CartridgeConstants.APPEND_SCRIPT) + " " +
-             subDomain + " " +
-             // machineIp ip of the machine DNS bind service
-             // is running
-             ip + " " +
-             // bindFile the file which we edit to append
-             // the DNS entry
-             System.getProperty(CartridgeConstants.BIND_FILE_PATH));
-   			log.info("New sub domain is added to zone file");
-   		} catch (Exception e) {
-   			log.error(e.getMessage());
-   			throw new RuntimeException(e);
-   		}
-   	}
-    /**
-   	 * This is get called when there is a need of remove a sub domain.
-   	 * It will remove required text from bind9 zone file and reload bind9 server.
-   	 * Note: make sure the user who run ADC has got rights to run sudo scripts
-   	 * without password
-   	 *
-   	 * @param subDomain
-   	 *            will be used to delete the entry related to this
-   	 */
-   	public void removeSubDomain(String subDomain) {
-   		try {
-   			Runtime.getRuntime()
-   			       .exec(CartridgeConstants.SUDO_SH + " " +
-             // script script file that will be used to edit
-             // required files
-             System.getProperty(CartridgeConstants.REMOVE_SCRIPT) + " " +
-             subDomain + " " +
-             // bindFile the file which we edit to remove
-             // the DNS entry
-             System.getProperty(CartridgeConstants.BIND_FILE_PATH));
-   			log.info("Sub domain is removed from zone file");
-   		} catch (Exception e) {
-   			log.error(e.getMessage());
-   			throw new RuntimeException(e);
-   		}
-   	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/AppRepo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/AppRepo.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/AppRepo.java
deleted file mode 100644
index facfbe3..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/AppRepo.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.dto;
-
-public class AppRepo {
-
-	private int tenantId;
-	private String repoName;
-	private String cartridge;
-	private String appName;
-	private boolean isWebRoot;
-	private String tenantPubKey;
-	private String tenantCartridgePubKey;
-
-	public int getTenantId() {
-		return tenantId;
-	}
-
-	public void setTenantId(int tenantId) {
-		this.tenantId = tenantId;
-	}
-
-	public String getRepoName() {
-		return repoName;
-	}
-
-	public void setRepoName(String repoName) {
-		this.repoName = repoName;
-	}
-
-	public String getCartridge() {
-		return cartridge;
-	}
-
-	public void setCartridge(String cartridge) {
-		this.cartridge = cartridge;
-	}
-
-	public String getAppName() {
-		return appName;
-	}
-
-	public void setAppName(String appName) {
-		this.appName = appName;
-	}
-
-	public boolean isWebRoot() {
-		return isWebRoot;
-	}
-
-	public void setWebRoot(boolean isWebRoot) {
-		this.isWebRoot = isWebRoot;
-	}
-
-	public String getTenantPubKey() {
-		return tenantPubKey;
-	}
-
-	public void setTenantPubKey(String tenantPubKey) {
-		this.tenantPubKey = tenantPubKey;
-	}
-
-	public String getTenantCartridgePubKey() {
-		return tenantCartridgePubKey;
-	}
-
-	public void setTenantCartridgePubKey(String tenantCartridgePubKey) {
-		this.tenantCartridgePubKey = tenantCartridgePubKey;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/Cartridge.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/Cartridge.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/Cartridge.java
deleted file mode 100644
index 4d990ce..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/Cartridge.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.dto;
-
-public class Cartridge implements Comparable<Cartridge> {
-
-    private String displayName;
-    private String description;
-	private String cartridgeAlias;
-	private String cartridgeType;
-	private int activeInstances;
-	private String status;
-	private String ip;
-	private String password;
-	private String provider;
-	private String version;
-	private boolean multiTenant;
-	private String hostName;
-	private String policy;
-	private String policyDescription;
-	private String repoURL;
-	private String dbUserName;
-	private String mappedDomain;
-
-	private String[] accessURLs;
-
-	public String getDisplayName() {
-		return displayName;
-	}
-
-	public void setDisplayName(String displayName) {
-		this.displayName = displayName;
-	}
-
-	public String getDescription() {
-		return description;
-	}
-
-	public void setDescription(String description) {
-		this.description = description;
-	}
-
-	public String getCartridgeAlias() {
-		return cartridgeAlias;
-	}
-
-	public void setCartridgeAlias(String cartridgeAlias) {
-		this.cartridgeAlias = cartridgeAlias;
-	}
-
-	public String getCartridgeType() {
-		return cartridgeType;
-	}
-
-	public void setCartridgeType(String cartridgeType) {
-		this.cartridgeType = cartridgeType;
-	}
-
-	public int getActiveInstances() {
-		return activeInstances;
-	}
-
-	public void setActiveInstances(int activeInstances) {
-		this.activeInstances = activeInstances;
-	}
-
-	public String getStatus() {
-		return status;
-	}
-
-	public void setStatus(String status) {
-		this.status = status;
-	}
-
-	public String getIp() {
-		return ip;
-	}
-
-	public void setIp(String ip) {
-		this.ip = ip;
-	}
-
-	public String getPassword() {
-		return password;
-	}
-
-	public void setPassword(String password) {
-		this.password = password;
-	}
-
-	public String getProvider() {
-    	return provider;
-    }
-
-	public void setProvider(String provider) {
-    	this.provider = provider;
-    }
-
-	public String getVersion() {
-    	return version;
-    }
-
-	public void setVersion(String version) {
-    	this.version = version;
-    }
-
-	public boolean isMultiTenant() {
-		return multiTenant;
-	}
-
-	public void setMultiTenant(boolean multiTenant) {
-		this.multiTenant = multiTenant;
-	}
-
-	public String getHostName() {
-    	return hostName;
-    }
-
-	public void setHostName(String hostName) {
-    	this.hostName = hostName;
-    }
-
-	public String getPolicy() {
-		return policy;
-	}
-
-	public void setPolicy(String policy) {
-		this.policy = policy;
-	}
-
-	public String getPolicyDescription() {
-		return policyDescription;
-	}
-
-	public void setPolicyDescription(String policyDescription) {
-		this.policyDescription = policyDescription;
-	}
-
-	public String getRepoURL() {
-    	return repoURL;
-    }
-
-	public void setRepoURL(String repoURL) {
-    	this.repoURL = repoURL;
-    }
-
-	public String getDbUserName() {
-    	return dbUserName;
-    }
-
-	public String[] getAccessURLs() {
-		return accessURLs;
-	}
-
-	public void setAccessURLs(String[] accessURLs) {
-		this.accessURLs = accessURLs;
-	}
-
-	public void setDbUserName(String dbUserName) {
-    	this.dbUserName = dbUserName;
-    }
-
-	public String getMappedDomain() {
-		return mappedDomain;
-	}
-
-	public void setMappedDomain(String mappedDomain) {
-		this.mappedDomain = mappedDomain;
-	}
-
-	@Override
-	public int compareTo(Cartridge o) {
-		int compare = 0;
-		if (cartridgeAlias != null && o.cartridgeAlias != null) {
-			compare = cartridgeAlias.compareTo(o.cartridgeAlias);
-		}
-		if (compare == 0 && cartridgeType != null && o.cartridgeType != null) {
-			compare = cartridgeType.compareTo(o.cartridgeType);
-		}
-		return compare;
-	}
-	
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeDetail.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeDetail.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeDetail.java
deleted file mode 100644
index 48a0086..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeDetail.java
+++ /dev/null
@@ -1 +0,0 @@
-package org.apache.stratos.adc.mgt.dto;

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeInformation.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeInformation.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeInformation.java
deleted file mode 100644
index 48a0086..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeInformation.java
+++ /dev/null
@@ -1 +0,0 @@
-package org.apache.stratos.adc.mgt.dto;

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeWrapper.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeWrapper.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeWrapper.java
deleted file mode 100644
index 1339a16..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/CartridgeWrapper.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*                                                                             
- * Copyright 2004,2005 The Apache Software Foundation.                         
- *                                                                             
- * Licensed under the Apache License, Version 2.0 (the "License");             
- * you may not use this file except in compliance with the License.            
- * You may obtain a copy of the License at                                     
- *                                                                             
- *      http://www.apache.org/licenses/LICENSE-2.0                             
- *                                                                             
- * Unless required by applicable law or agreed to in writing, software         
- * distributed under the License is distributed on an "AS IS" BASIS,           
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.    
- * See the License for the specific language governing permissions and         
- * limitations under the License.                                              
- */
-package org.apache.stratos.adc.mgt.dto;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.wso2.carbon.utils.Pageable;
-
-/**
- * This class holds paginated information about cartridges
- */
-public final class CartridgeWrapper implements Pageable {
-
-	private Cartridge[] cartridges;
-	private int numberOfPages;
-
-	public CartridgeWrapper() {
-	}
-
-	public int getNumberOfPages() {
-		return numberOfPages;
-	}
-
-	public void setNumberOfPages(int numberOfPages) {
-		this.numberOfPages = numberOfPages;
-	}
-
-	public <T> void set(List<T> items) {
-		this.cartridges = items.toArray(new Cartridge[items.size()]);
-	}
-
-	public Cartridge[] getCartridges() {
-		return cartridges != null ? Arrays.copyOf(cartridges, cartridges.length) : null;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/Policy.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/Policy.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/Policy.java
deleted file mode 100644
index 451618d..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/Policy.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.dto;
-
-import java.io.Serializable;
-import java.math.BigDecimal;
-
-public class Policy implements Serializable {
-
-	private static final long serialVersionUID = 1L;
-
-	private String name;
-	private String description;
-	private boolean defaultPolicy;
-
-	private Integer minAppInstances;
-	private Integer maxAppInstances;
-	private Integer maxRequestsPerSecond;
-	private BigDecimal alarmingUpperRate;
-	private BigDecimal alarmingLowerRate;
-	private BigDecimal scaleDownFactor;
-	private Integer roundsToAverage;
-
-	public Policy() {
-	}
-
-	public String getName() {
-		return name;
-	}
-
-	public void setName(String name) {
-		this.name = name;
-	}
-
-	public String getDescription() {
-		return description;
-	}
-
-	public void setDescription(String description) {
-		this.description = description;
-	}
-
-	public boolean isDefaultPolicy() {
-		return defaultPolicy;
-	}
-
-	public void setDefaultPolicy(boolean defaultPolicy) {
-		this.defaultPolicy = defaultPolicy;
-	}
-
-	public Integer getMinAppInstances() {
-		return minAppInstances;
-	}
-
-	public void setMinAppInstances(Integer minAppInstances) {
-		this.minAppInstances = minAppInstances;
-	}
-
-	public Integer getMaxAppInstances() {
-		return maxAppInstances;
-	}
-
-	public void setMaxAppInstances(Integer maxAppInstances) {
-		this.maxAppInstances = maxAppInstances;
-	}
-
-	public Integer getMaxRequestsPerSecond() {
-		return maxRequestsPerSecond;
-	}
-
-	public void setMaxRequestsPerSecond(Integer maxRequestsPerSecond) {
-		this.maxRequestsPerSecond = maxRequestsPerSecond;
-	}
-
-	public BigDecimal getAlarmingUpperRate() {
-		return alarmingUpperRate;
-	}
-
-	public void setAlarmingUpperRate(BigDecimal alarmingUpperRate) {
-		this.alarmingUpperRate = alarmingUpperRate;
-	}
-
-	public BigDecimal getAlarmingLowerRate() {
-		return alarmingLowerRate;
-	}
-
-	public void setAlarmingLowerRate(BigDecimal alarmingLowerRate) {
-		this.alarmingLowerRate = alarmingLowerRate;
-	}
-
-	public BigDecimal getScaleDownFactor() {
-		return scaleDownFactor;
-	}
-
-	public void setScaleDownFactor(BigDecimal scaleDownFactor) {
-		this.scaleDownFactor = scaleDownFactor;
-	}
-
-	public Integer getRoundsToAverage() {
-		return roundsToAverage;
-	}
-
-	public void setRoundsToAverage(Integer roundsToAverage) {
-		this.roundsToAverage = roundsToAverage;
-	}
-
-	@Override
-	public int hashCode() {
-		final int prime = 31;
-		int result = 1;
-		result = prime * result + ((name == null) ? 0 : name.hashCode());
-		return result;
-	}
-
-	@Override
-	public boolean equals(Object obj) {
-		if (this == obj)
-			return true;
-		if (obj == null)
-			return false;
-		if (!(obj instanceof Policy))
-			return false;
-		Policy other = (Policy) obj;
-		if (name == null) {
-			if (other.name != null)
-				return false;
-		} else if (!name.equals(other.name))
-			return false;
-		return true;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/PolicyDefinition.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/PolicyDefinition.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/PolicyDefinition.java
deleted file mode 100644
index b21df4f..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/PolicyDefinition.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.dto;
-
-import java.io.Serializable;
-
-public class PolicyDefinition implements Serializable {
-
-	private static final long serialVersionUID = 1L;
-
-	private String name;
-	private String description;
-	private boolean defaultPolicy;
-
-	public PolicyDefinition() {
-	}
-
-	public String getName() {
-		return name;
-	}
-
-	public void setName(String name) {
-		this.name = name;
-	}
-
-	public String getDescription() {
-		return description;
-	}
-
-	public void setDescription(String description) {
-		this.description = description;
-	}
-
-	public boolean isDefaultPolicy() {
-		return defaultPolicy;
-	}
-
-	public void setDefaultPolicy(boolean defaultPolicy) {
-		this.defaultPolicy = defaultPolicy;
-	}
-
-	@Override
-	public int hashCode() {
-		final int prime = 31;
-		int result = 1;
-		result = prime * result + ((name == null) ? 0 : name.hashCode());
-		return result;
-	}
-
-	@Override
-	public boolean equals(Object obj) {
-		if (this == obj)
-			return true;
-		if (obj == null)
-			return false;
-		if (!(obj instanceof PolicyDefinition))
-			return false;
-		PolicyDefinition other = (PolicyDefinition) obj;
-		if (name == null) {
-			if (other.name != null)
-				return false;
-		} else if (!name.equals(other.name))
-			return false;
-		return true;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/RepositoryInformation.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/RepositoryInformation.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/RepositoryInformation.java
deleted file mode 100644
index 3a88700..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/RepositoryInformation.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.dto;
-
-import java.io.Serializable;
-
-public class RepositoryInformation implements Serializable {
-
-	private static final long serialVersionUID = 1L;
-
-	private String repoURL;
-	private String[] refName;
-
-	public String getRepoURL() {
-		return repoURL;
-	}
-
-	public void setRepoURL(String repoURL) {
-		this.repoURL = repoURL;
-	}
-
-	public String[] getRefName() {
-		return refName;
-	}
-
-	public void setRefName(String[] refName) {
-		this.refName = refName;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/SubscriptionInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/SubscriptionInfo.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/SubscriptionInfo.java
deleted file mode 100644
index 39e3ae2..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/dto/SubscriptionInfo.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.dto;
-
-import java.io.Serializable;
-
-public class SubscriptionInfo implements Serializable {
-
-	private static final long serialVersionUID = 1L;
-
-	private String hostname;
-	private String repositoryURL;
-
-	public String getHostname() {
-		return hostname;
-	}
-
-	public void setHostname(String hostname) {
-		this.hostname = hostname;
-	}
-
-	public String getRepositoryURL() {
-		return repositoryURL;
-	}
-
-	public void setRepositoryURL(String repositoryURL) {
-		this.repositoryURL = repositoryURL;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/ADCException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/ADCException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/ADCException.java
deleted file mode 100644
index d9dbfdf..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/ADCException.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class ADCException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private String message;
-
-	public ADCException() {
-		super();
-	}
-
-	public ADCException(String message, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-	}
-
-	public ADCException(String message) {
-		super(message);
-		this.message = message;
-	}
-
-	public ADCException(Throwable cause) {
-		super(cause);
-	}
-
-	public String getMessage() {
-		return message;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/AlreadySubscribedException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/AlreadySubscribedException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/AlreadySubscribedException.java
deleted file mode 100644
index 954a71b..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/AlreadySubscribedException.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class AlreadySubscribedException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private final String message;
-
-	private final String cartridgeType;
-
-	public AlreadySubscribedException(String message, String cartridgeType, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-		this.cartridgeType = cartridgeType;
-	}
-
-	public AlreadySubscribedException(String message, String cartridgeType) {
-		super(message);
-		this.message = message;
-		this.cartridgeType = cartridgeType;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-
-	public String getCartridgeType() {
-		return cartridgeType;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/DomainMappingExistsException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/DomainMappingExistsException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/DomainMappingExistsException.java
deleted file mode 100644
index 9287a86..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/DomainMappingExistsException.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class DomainMappingExistsException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private final String message;
-
-	private final String domain;
-
-	public DomainMappingExistsException(String message, String domain, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-		this.domain = domain;
-	}
-
-	public DomainMappingExistsException(String message, String domain) {
-		super(message);
-		this.message = message;
-		this.domain = domain;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-
-	public String getDomain() {
-		return domain;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/DuplicateCartridgeAliasException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/DuplicateCartridgeAliasException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/DuplicateCartridgeAliasException.java
deleted file mode 100644
index 94aa14c..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/DuplicateCartridgeAliasException.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class DuplicateCartridgeAliasException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private final String message;
-
-	private final String cartridgeType;
-
-	private final String cartridgeAlias;
-
-	public DuplicateCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-		this.cartridgeType = cartridgeType;
-		this.cartridgeAlias = cartridgeAlias;
-	}
-
-	public DuplicateCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias) {
-		super(message);
-		this.message = message;
-		this.cartridgeType = cartridgeType;
-		this.cartridgeAlias = cartridgeAlias;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-
-	public String getCartridgeType() {
-		return cartridgeType;
-	}
-
-	public String getCartridgeAlias() {
-		return cartridgeAlias;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidCartridgeAliasException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidCartridgeAliasException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidCartridgeAliasException.java
deleted file mode 100644
index 0fed41b..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidCartridgeAliasException.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class InvalidCartridgeAliasException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private final String message;
-
-	private final String cartridgeType;
-
-	private final String cartridgeAlias;
-
-	public InvalidCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-		this.cartridgeType = cartridgeType;
-		this.cartridgeAlias = cartridgeAlias;
-	}
-
-	public InvalidCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias) {
-		super(message);
-		this.message = message;
-		this.cartridgeType = cartridgeType;
-		this.cartridgeAlias = cartridgeAlias;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-
-	public String getCartridgeType() {
-		return cartridgeType;
-	}
-
-	public String getCartridgeAlias() {
-		return cartridgeAlias;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidRepositoryException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidRepositoryException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidRepositoryException.java
deleted file mode 100644
index c545b9e..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/InvalidRepositoryException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class InvalidRepositoryException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private String message;
-
-	public InvalidRepositoryException(String message, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/NotSubscribedException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/NotSubscribedException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/NotSubscribedException.java
deleted file mode 100644
index 74aef20..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/NotSubscribedException.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class NotSubscribedException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private final String message;
-
-	private final String cartridgeAlias;
-
-	public NotSubscribedException(String message, String cartridgeAlias, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-		this.cartridgeAlias = cartridgeAlias;
-	}
-
-	public NotSubscribedException(String message, String cartridgeAlias) {
-		super(message);
-		this.message = message;
-		this.cartridgeAlias = cartridgeAlias;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-
-	public String getCartridgeAlias() {
-		return cartridgeAlias;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/PolicyException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/PolicyException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/PolicyException.java
deleted file mode 100644
index 2ad3117..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/PolicyException.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class PolicyException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private final String message;
-
-	public PolicyException(String message, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-	}
-
-	public PolicyException(String message) {
-		super(message);
-		this.message = message;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryCredentialsRequiredException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryCredentialsRequiredException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryCredentialsRequiredException.java
deleted file mode 100644
index 2de1899..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryCredentialsRequiredException.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class RepositoryCredentialsRequiredException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private String message;
-
-	public RepositoryCredentialsRequiredException(String message, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-	}
-
-	public RepositoryCredentialsRequiredException(String message) {
-		super(message);
-		this.message = message;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryRequiredException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryRequiredException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryRequiredException.java
deleted file mode 100644
index 553dfc2..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryRequiredException.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class RepositoryRequiredException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private String message;
-
-	public RepositoryRequiredException(String message, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-	}
-
-	public RepositoryRequiredException(String message) {
-		super(message);
-		this.message = message;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryTransportException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryTransportException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryTransportException.java
deleted file mode 100644
index 5b5036a..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/RepositoryTransportException.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class RepositoryTransportException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private final String message;
-
-	public RepositoryTransportException(String message, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-	}
-
-	public RepositoryTransportException(String message) {
-		super(message);
-		this.message = message;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/UnregisteredCartridgeException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/UnregisteredCartridgeException.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/UnregisteredCartridgeException.java
deleted file mode 100644
index fb1f656..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/exception/UnregisteredCartridgeException.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2013, WSO2, Inc. http://wso2.org
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *     http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package org.apache.stratos.adc.mgt.exception;
-
-public class UnregisteredCartridgeException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	private final String message;
-
-	private final String cartridgeType;
-
-	public UnregisteredCartridgeException(String message, String cartridgeType, Throwable cause) {
-		super(message, cause);
-		this.message = message;
-		this.cartridgeType = cartridgeType;
-	}
-
-	public UnregisteredCartridgeException(String message, String cartridgeType) {
-		super(message);
-		this.message = message;
-		this.cartridgeType = cartridgeType;
-	}
-
-	public String getMessage() {
-		return message;
-	}
-
-	public String getCartridgeType() {
-		return cartridgeType;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java
deleted file mode 100644
index 48cfc2a..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/ADCManagementServerComponent.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
-        * Copyright WSO2, Inc. (http://wso2.com)
-        *
-        * Licensed under the Apache License, Version 2.0 (the "License");
-        * you may not use this file except in compliance with the License.
-        * You may obtain a copy of the License at
-        *
-        * http://www.apache.org/licenses/LICENSE-2.0
-        *
-        * Unless required by applicable law or agreed to in writing, software
-        * distributed under the License is distributed on an "AS IS" BASIS,
-        * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-        * See the License for the specific language governing permissions and
-        * limitations under the License.
-        */
-package org.apache.stratos.adc.mgt.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.utils.CartridgeConfigFileReader;
-import org.apache.stratos.adc.mgt.utils.StratosDBUtils;
-import org.osgi.service.component.ComponentContext;
-import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-/**
- * @scr.component name=
- *                "org.wso2.carbon.hosting.mgt.internal.ADCManagementServerComponent"
- *                immediate="true"
- * @scr.reference name="config.context.service"
- *                interface="org.wso2.carbon.utils.ConfigurationContextService"
- *                cardinality="1..1" policy="dynamic"
- *                bind="setConfigurationContextService"
- *                unbind="unsetConfigurationContextService"
- * @scr.reference name="user.realmservice.default"
- *                interface="org.wso2.carbon.user.core.service.RealmService"
- *                cardinality="1..1" policy="dynamic" bind="setRealmService"
- *                unbind="unsetRealmService"
- * @scr.reference name="registry.service"
- *                interface=
- *                "org.wso2.carbon.registry.core.service.RegistryService"
- *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
- *                unbind="unsetRegistryService"
- * @scr.reference name="topology.mgt.service"
- *                interface=
- *                "org.apache.stratos.adc.topology.mgt.service.TopologyManagementService"
- *                cardinality="1..1" policy="dynamic"
- *                bind="setTopologyManagementService"
- *                unbind="unsetTopologyManagementService"
- */
-
-public class ADCManagementServerComponent {
-    private static final Log log = LogFactory.getLog(ADCManagementServerComponent.class);
-
-	protected void activate(ComponentContext componentContext) throws Exception {
-		if (log.isInfoEnabled()) {
-			log.info("ADC Management Server Component activated");
-		}
-
-		try {
-			CartridgeConfigFileReader.readProperties();
-			StratosDBUtils.initialize();
-		} catch (Exception e) {
-			log.fatal("Error while initializing the ADC Management Server Component", e);
-		}
-	}
-
-    protected void setConfigurationContextService(ConfigurationContextService contextService) {
-        DataHolder.setClientConfigContext(contextService.getClientConfigContext());
-        DataHolder.setServerConfigContext(contextService.getServerConfigContext());
-
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
-        DataHolder.setClientConfigContext(null);
-        DataHolder.setServerConfigContext(null);
-    }
-
-    protected void setRealmService(RealmService realmService) {
-        // keeping the realm service in the DataHolder class
-        DataHolder.setRealmService(realmService);
-    }
-
-    protected void unsetRealmService(RealmService realmService) {
-    }
-
-    protected void setRegistryService(RegistryService registryService) {
-        try {
-            DataHolder.setRegistry(registryService.getGovernanceSystemRegistry());
-        } catch (Exception e) {
-            log.error("Cannot  retrieve governance Registry", e);
-        }
-    }
-
-    protected void unsetRegistryService(RegistryService registryService) {
-    }
-
-    protected void setTopologyManagementService(TopologyManagementService topologyMgtService) {
-        DataHolder.setTopologyMgtService(topologyMgtService);
-    }
-
-    protected void unsetTopologyManagementService(TopologyManagementService topologyMgtService) {
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java
deleted file mode 100644
index 392489b..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/DataHolder.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.internal;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.wso2.carbon.registry.core.Registry;
-import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.utils.CarbonUtils;
-
-/**
- * Holds the some of the data required by the webapps component
- */
-public class DataHolder {
-	private static ConfigurationContext clientConfigContext;
-	private static ConfigurationContext serverConfigContext;
-
-	private static RealmService realmService;
-	private static Registry registry;
-	private static TopologyManagementService topologyMgtService;
-
-	public static RealmService getRealmService() {
-		return realmService;
-	}
-
-	public static void setRealmService(RealmService realmService) {
-		DataHolder.realmService = realmService;
-	}
-
-	public static Registry getRegistry() {
-		return registry;
-	}
-
-	public static ConfigurationContext getClientConfigContext() {
-		CarbonUtils.checkSecurity();
-		return clientConfigContext;
-	}
-
-	public static void setClientConfigContext(ConfigurationContext clientConfigContext) {
-		DataHolder.clientConfigContext = clientConfigContext;
-	}
-
-	public static ConfigurationContext getServerConfigContext() {
-		CarbonUtils.checkSecurity();
-		return serverConfigContext;
-	}
-
-	public static void setServerConfigContext(ConfigurationContext serverConfigContext) {
-		DataHolder.serverConfigContext = serverConfigContext;
-	}
-
-	public static void setRegistry(Registry registry) {
-		DataHolder.registry = registry;
-	}
-
-	public static TopologyManagementService getTopologyMgtService() {
-		return topologyMgtService;
-	}
-
-	public static void setTopologyMgtService(TopologyManagementService topologyMgtService) {
-		DataHolder.topologyMgtService = topologyMgtService;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/HostingConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/HostingConstants.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/HostingConstants.java
deleted file mode 100644
index 9259ea6..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/HostingConstants.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.internal;
-
-/**
- * Web Application Constants
- */
-public final class HostingConstants {
-	public static final String WEBAPP_PREFIX = "webapps";
-	public static final String WEBAPP_DEPLOYMENT_FOLDER = "webapps";
-	public static final String WEBAPP_EXTENSION = "war";
-
-	public static final class WebappState {
-		public static final String STARTED = "started";
-		public static final String STOPPED = "stopped";
-
-		private WebappState() {
-		}
-	}
-
-	private HostingConstants() {
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/HostingManagementActivator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/HostingManagementActivator.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/HostingManagementActivator.java
deleted file mode 100644
index 2e61894..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/internal/HostingManagementActivator.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.wso2.carbon.utils.CarbonUtils;
-
-/**
- * Activator for the Webapp Management Bundle
- */
-public class HostingManagementActivator implements BundleActivator {
-	private static final Log log = LogFactory.getLog(HostingManagementActivator.class);
-
-	@Override
-	public void start(final BundleContext bundleContext) {
-
-		// If Carbon is running as a webapp within some other servlet container,
-		// then we should
-		// uninstall this component
-		if (!CarbonUtils.isRunningInStandaloneMode()) {
-			Thread th = new Thread() {
-				@Override
-				public void run() {
-					try {
-						bundleContext.getBundle().uninstall();
-					} catch (Throwable e) {
-						log.warn("Error occurred while uninstalling hosting.mgt UI bundle", e);
-					}
-				}
-			};
-			try {
-				th.join();
-			} catch (InterruptedException ignored) {
-			}
-			th.start();
-		}
-	}
-
-	@Override
-	public void stop(BundleContext bundleContext) {
-		// No implementation required for this method
-	}
-}


[22/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java
new file mode 100644
index 0000000..fc1569b
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/ServiceTemplate.java
@@ -0,0 +1,84 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.stratos.lb.common.conf.util.Constants;
+
+/**
+ * We keep details under a service element of jcoluds configuration file,
+ * in this object.
+ */
+public class ServiceTemplate implements Cloneable {
+
+    private String domainName;
+    private String subDomainName = Constants.DEFAULT_SUB_DOMAIN;
+    private Map<String, String> properties = new HashMap<String, String>();
+    
+    public String getDomainName() {
+        return domainName;
+    }
+    
+    public boolean setDomainName(String domainName) {
+        if (!"".equals(domainName)) {
+            this.domainName = domainName;
+            return true;
+        }
+        
+        return false;
+    }
+    
+    public void setProperty(String key, String value) {
+        properties.put(key, value);
+    }
+    
+    public String getProperty(String key) {
+        
+        if(properties.containsKey(key)){
+            return properties.get(key);
+        }
+        
+        return "";
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+    
+    public String getSubDomainName() {
+        return subDomainName;
+    }
+
+    public void setSubDomainName(String subDomainName) {
+        if(subDomainName == null || "".equals(subDomainName)){
+            return;
+        }
+        this.subDomainName = subDomainName;
+    }
+    
+    public Object clone() throws CloneNotSupportedException {
+        return super.clone();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java
new file mode 100644
index 0000000..a40cf41
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReader.java
@@ -0,0 +1,557 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.xml;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.apache.stratos.autoscaler.service.exception.MalformedConfigurationFileException;
+import org.apache.stratos.autoscaler.service.util.AutoscalerConstant;
+import org.apache.stratos.autoscaler.service.util.IaasProvider;
+import org.apache.stratos.autoscaler.service.util.ServiceTemplate;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.securevault.SecretResolver;
+import org.wso2.securevault.SecretResolverFactory;
+
+/**
+ * Responsible for reading the Elastic scaler configuration file.
+ * Following is a sample XML.
+ *
+ * &lt;elasticScalerConfig&gt;
+ *      &lt;iaasProviders&gt;
+ *          &lt;iaasProvider name="ec2"&gt;
+ *              &lt;provider&gt;aws-ec2&lt;/provider&gt;
+ *              &lt;identity&gt;aaa&lt;/identity&gt;
+ *              &lt;credential&gt;aaaa&lt;/credential&gt;
+ *              &lt;scaleUpOrder&gt;1&lt;/scaleUpOrder&gt;
+ *              &lt;scaleDownOrder&gt;2&lt;/scaleDownOrder&gt;
+ *              &lt;property name="A" value="a"/&gt;
+ *              &lt;property name="B" value="b"/&gt;
+ *              &lt;template&gt;temp1&lt;/template&gt;
+ *          &lt;/iaasProvider&gt;
+ *          
+ *          &lt;iaasProvider name="lxc"&gt;
+ *              &lt;provider&gt;aws-ec2&lt;/provider&gt;
+ *              &lt;identity&gt;aaa&lt;/identity&gt;
+ *              &lt;credential&gt;aaaa&lt;/credential&gt;
+ *              &lt;scaleUpOrder&gt;2&lt;/scaleUpOrder&gt;
+ *              &lt;scaleDownOrder&gt;1&lt;/scaleDownOrder&gt;
+ *              &lt;property name="X" value="x"/&gt;
+ *              &lt;property name="Y" value="y"/&gt;
+ *              &lt;template&gt;temp2&lt;/template&gt;
+ *          &lt;/iaasProvider&gt;
+ *      &lt;/iaasProviders&gt;
+ *      $lt;services&gt;
+ *          $lt;default&gt;
+ *              $lt;property name="availabilityZone" value="us-east-1c"/&gt;
+ *              $lt;property name="securityGroups" value="manager,cep,mb,default"/&gt;
+ *              $lt;property name="instanceType" value="m1.large"/&gt;
+ *              $lt;property name="keyPair" value="aa"/&gt;
+ *          $lt;/default&gt;
+ *          $lt;service domain="wso2.as.domain"&gt;
+ *              $lt;property name="securityGroups" value="manager,default"/&gt;
+ *              $lt;property name="payload" value="resources/as.zip"/&gt;
+ *          $lt;/service&gt;
+ *      $lt;/services&gt;
+ *  &lt;/elasticScalerConfig&gt;
+ */
+public class ElasticScalerConfigFileReader {
+	
+	private static final Log log = LogFactory.getLog(ElasticScalerConfigFileReader.class);
+
+	//get the factory
+	private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+	private Document dom;
+	private Element docEle;
+
+	/**
+	 * Path to elastic-scaler-config XML file, which specifies the Iaas specific details and 
+	 * services related details.
+	 */
+	private String elasticScalerConfigFile;
+	
+	
+	public ElasticScalerConfigFileReader(){
+	    
+	    elasticScalerConfigFile = CarbonUtils.getCarbonConfigDirPath() +
+	            File.separator + "elastic-scaler-config.xml";
+	    
+		/**
+		 * Parse the configuration file.
+		 */
+		try {
+			//Using factory, get an instance of document builder
+			DocumentBuilder db = dbf.newDocumentBuilder();
+
+			//parse using builder to get DOM representation of the XML file
+			dom = db.parse(elasticScalerConfigFile);
+			
+
+		}catch(Exception ex) {
+			String msg = "Error occurred while parsing the "+elasticScalerConfigFile+".";
+			handleException(msg, ex);
+		}
+	}
+	
+	/**
+	 * Constructor to be used in the test cases.
+	 * @param file path to elastic-scaler-config xml file.
+	 */
+	public ElasticScalerConfigFileReader(String file) {
+        
+        /**
+         * Parse the configuration file.
+         */
+        try {
+            //Using factory, get an instance of document builder
+            DocumentBuilder db = dbf.newDocumentBuilder();
+            
+            //parse using builder to get DOM representation of the XML file
+            dom = db.parse(file);
+            
+
+        }catch(Exception ex) {
+            String msg = "Error occurred when parsing the "+file+".";
+            handleException(msg, ex);
+        }
+    }
+	
+	/**
+	 * Returns the serialization directory specified in the configuration file.
+	 * @return the path to the directory or an empty string if element cannot be found.
+	 */
+	public String getSerializationDir() {
+        
+	    docEle = dom.getDocumentElement();
+	    NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.SERIALIZATION_DIR_ELEMENT);
+
+        // there should be only one serializationDir element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                return prop.getTextContent();
+
+            }
+        }
+        
+        return "";
+    }
+	
+	/**
+	 * Load all IaasProviders from the configuration file and returns a list.
+	 * @return a list of IaasProvider instances.
+	 */
+	public List<IaasProvider> getIaasProvidersList() {
+	    List<IaasProvider> iaasProviders = new ArrayList<IaasProvider>();
+	    
+	    docEle = dom.getDocumentElement();
+	    NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.IAAS_PROVIDER_ELEMENT);
+	    
+	    if (nl != null && nl.getLength() > 0) {
+	        
+	        for(int i=0; i< nl.getLength() ; i++){
+	            iaasProviders.add(getIaasProvider(nl.item(i)));
+	        }
+	        
+	    }
+	    else{
+	        String msg = "Essential '"+AutoscalerConstant.IAAS_PROVIDER_ELEMENT+"' element cannot" +
+	        		" be found in "+elasticScalerConfigFile;
+	        handleException(msg);
+	    }
+	    
+	    return iaasProviders;
+	    
+    }
+
+    private IaasProvider getIaasProvider(Node item) {
+
+        IaasProvider iaas = new IaasProvider();
+        
+        if (item.getNodeType() == Node.ELEMENT_NODE) {
+            Element iaasElt = (Element) item;
+            iaas.setType(iaasElt.getAttribute(AutoscalerConstant.IAAS_PROVIDER_TYPE_ATTR));
+            
+            if("".equals(iaas.getType())){
+                String msg = "'"+AutoscalerConstant.IAAS_PROVIDER_ELEMENT+"' element's '"+
+            AutoscalerConstant.IAAS_PROVIDER_TYPE_ATTR+"' attribute should be specified!";
+                
+                handleException(msg);
+
+            }
+            
+            // this is not mandatory
+            iaas.setName(iaasElt.getAttribute(AutoscalerConstant.IAAS_PROVIDER_NAME_ATTR));
+            
+            iaas.setProperties(loadProperties(iaasElt));
+            loadTemplate(iaas, iaasElt);
+            loadScalingOrders(iaas, iaasElt);
+            loadProvider(iaas, iaasElt);
+            loadIdentity(iaas, iaasElt);
+            loadCredentials(iaas, iaasElt);
+        }
+        
+        
+        return iaas;
+    }
+    
+    /**
+     * Load all ServiceTemplates from the configuration file and returns a list.
+     * @return a list of ServiceTemplate instances.
+     */
+    public List<ServiceTemplate> getTemplates() {
+        
+        List<ServiceTemplate> templates = new ArrayList<ServiceTemplate>();
+        
+        // build default template object
+        ServiceTemplate template = new ServiceTemplate();
+        
+        Element docEle = dom.getDocumentElement();
+        NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.DEFAULT_SERVICE_ELEMENT);
+        
+        if (nl != null && nl.getLength() > 0) {
+
+            Node item = nl.item(0);
+
+            if (item.getNodeType() == Node.ELEMENT_NODE) {
+                Element defaultElt = (Element) item;
+                template.setProperties(loadProperties(defaultElt));
+            }
+
+        }
+        
+        // append / overwrite the default template object with values in each domain
+        nl = docEle.getElementsByTagName(AutoscalerConstant.SERVICE_ELEMENT);
+        
+        if (nl != null && nl.getLength() > 0) {
+
+            for (int i = 0; i < nl.getLength(); i++) {
+                Node item = nl.item(i);
+
+                // clone the default template to an independent object
+                try {
+                    ServiceTemplate temp = (ServiceTemplate) template.clone();
+
+                    if (item.getNodeType() == Node.ELEMENT_NODE) {
+                        Element imageElt = (Element) item;
+
+                        if ("".equals(imageElt.getAttribute(
+                                             AutoscalerConstant.SERVICE_DOMAIN_ATTR))) {
+                            String msg =
+                                "Essential '"+AutoscalerConstant.SERVICE_DOMAIN_ATTR+"' " +
+                                		"attribute of '"+AutoscalerConstant.SERVICE_ELEMENT+
+                                		"' element cannot be found in " + elasticScalerConfigFile;
+
+                            handleException(msg);
+                        }
+
+                        // set domain name
+                        temp.setDomainName(imageElt.getAttribute(AutoscalerConstant.SERVICE_DOMAIN_ATTR));
+                        
+                        // set sub domain
+                        temp.setSubDomainName(imageElt.getAttribute(
+                                              AutoscalerConstant.SERVICE_SUB_DOMAIN_ATTR));
+                        
+                        // load custom properties
+                        Map<String, String> customProperties = loadProperties(imageElt);
+                        
+                        // add custom properties (overwrite default properties where necessary)
+                        for (Entry<String, String> pair : customProperties.entrySet()) {
+                            temp.setProperty(pair.getKey(), pair.getValue());
+                        }
+
+                    }
+                    
+                    // add each domain specific template to list
+                    templates.add(temp);
+
+                } catch (CloneNotSupportedException e) {
+                    String msg = "This is extraordinary!! ";
+                    handleException(msg, e);
+                }
+            }
+        }
+        
+        return templates;
+    }
+    
+    private void loadCredentials(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.CREDENTIAL_ELEMENT);
+
+        // there should be only one credential element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                         AutoscalerConstant.CREDENTIAL_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+
+                // retrieve the value using secure vault
+                SecretResolver secretResolver = SecretResolverFactory.create(docEle, false);
+                String alias;
+
+                // FIXME following is a hack to find the correct alias.
+                if (iaas.getProvider().contains("ec2")) {
+                    alias = AutoscalerConstant.EC2_CREDENTIAL_ALIAS;
+                } else {
+                    alias = AutoscalerConstant.OPENSTACK_CREDENTIAL_ALIAS;
+                }
+
+                // retrieve the secured password
+                if (secretResolver != null && secretResolver.isInitialized() && 
+                        secretResolver.isTokenProtected(alias)) {
+
+                    iaas.setCredential(secretResolver.resolve(alias));
+
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.CREDENTIAL_ELEMENT+"' element" +
+            		" has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadIdentity(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.IDENTITY_ELEMENT);
+
+        // there should be only one identity element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.IDENTITY_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+
+                // retrieve the value using secure vault
+                SecretResolver secretResolver = SecretResolverFactory.create(docEle, false);
+                String alias;
+                
+                //FIXME following is a hack to find the correct alias.
+                if(iaas.getProvider().contains("ec2")){
+                    alias = AutoscalerConstant.EC2_IDENTITY_ALIAS;
+                }
+                else{
+                    alias = AutoscalerConstant.OPENSTACK_IDENTITY_ALIAS;
+                }
+
+                // retrieve the secured password
+                if (secretResolver != null && secretResolver.isInitialized() && 
+                        secretResolver.isTokenProtected(alias)) {
+
+                    iaas.setIdentity(secretResolver.resolve(alias));
+
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.IDENTITY_ELEMENT+"' element" +
+            		" has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadProvider(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.PROVIDER_ELEMENT);
+
+        // there should be only one provider element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.PROVIDER_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                iaas.setProvider(prop.getTextContent());
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.PROVIDER_ELEMENT+"' element " +
+            		"has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadScalingOrders(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.SCALE_UP_ORDER_ELEMENT);
+
+        // there should be only one scaleUpOrder element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                try {
+                    iaas.setScaleUpOrder(Integer.parseInt(prop.getTextContent()));
+                }catch (NumberFormatException e) {
+                    String msg = AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+" element contained" +
+                    		" in "+elasticScalerConfigFile +"" +
+                    		" has a value which is not an Integer value.";
+                    handleException(msg, e);
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+"' element" +
+            		" has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+        
+        
+        nl = iaasElt.getElementsByTagName(AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT);
+
+        // there should be only one scaleDownOrder element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                try {
+                    iaas.setScaleDownOrder(Integer.parseInt(prop.getTextContent()));
+                }catch (NumberFormatException e) {
+                    String msg = AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+" element contained" +
+                            " in "+elasticScalerConfigFile +"" +
+                            " has a value which is not an Integer value.";
+                    handleException(msg, e);
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+"' element" +
+                    " has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadTemplate(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.IMAGE_ID_ELEMENT);
+
+        // there should be only one imageId element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.IMAGE_ID_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                iaas.setTemplate(prop.getTextContent());
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.IMAGE_ID_ELEMENT+"' element" +
+                    " has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private Map<String, String> loadProperties(Element iaasElt) {
+
+        Map<String, String> propertyMap = new HashMap<String, String>();
+        
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.PROPERTY_ELEMENT);
+        
+        if (nl != null && nl.getLength() > 0) {
+            for(int i=0; i< nl.getLength() ; i++){
+                
+                if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
+                    Element prop = (Element) nl.item(i);
+                    
+                    if("".equals(prop.getAttribute(AutoscalerConstant.PROPERTY_NAME_ATTR)) ||
+                            "".equals(prop.getAttribute(AutoscalerConstant.PROPERTY_VALUE_ATTR))){
+                        
+                        String msg ="Property element's, name and value attributes should be specified " +
+                        		"in "+elasticScalerConfigFile;
+
+                        handleException(msg);
+                    }
+                    propertyMap.put(prop.getAttribute(AutoscalerConstant.PROPERTY_NAME_ATTR), 
+                                    prop.getAttribute(AutoscalerConstant.PROPERTY_VALUE_ATTR));
+                    
+                }
+            }
+        }
+        
+        return propertyMap;
+    }
+    
+    private void handleException(String msg){
+        log.error(msg);
+        throw new MalformedConfigurationFileException(msg);
+    }
+    
+    private void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new MalformedConfigurationFileException(msg, e);
+    }
+	
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.autoscaler.service/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..04dd8d8
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/resources/META-INF/services.xml
@@ -0,0 +1,9 @@
+<serviceGroup>
+    <service name="AutoscalerService" scope="application">
+        <parameter name="ServiceClass">org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImplpl</parameter>
+        <messageReceivers>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
+    </messageReceivers>
+    </service>
+</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java b/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java
new file mode 100644
index 0000000..9a742ee
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextComparatorTest.java
@@ -0,0 +1,98 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.util;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.IaasContextComparator;
+import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
+
+import junit.framework.TestCase;
+
+public class IaasContextComparatorTest extends TestCase {
+    
+    List<IaasContext> iaasContexts = new ArrayList<IaasContext>();
+    
+    @Override
+    protected void setUp() throws Exception {
+        IaasContext a = new IaasContext(Iaases.ec2, null);
+        a.setScaleUpOrder(1);
+        a.setScaleDownOrder(5);
+        
+        IaasContext b = new IaasContext(Iaases.openstack, null);
+        b.setScaleUpOrder(3);
+        b.setScaleDownOrder(0);
+        
+        iaasContexts.add(a);
+        iaasContexts.add(b);
+        
+        super.setUp();
+    }
+
+    public void testSort() {
+        
+        // scale up order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_UP_SORT)));
+        
+        assertEquals("ec2", iaasContexts.get(0).getName().toString());
+        assertEquals("openstack", iaasContexts.get(1).getName().toString());
+        
+        // scale down order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_DOWN_SORT)));
+        
+        assertEquals("openstack", iaasContexts.get(0).getName().toString());
+        assertEquals("ec2", iaasContexts.get(1).getName().toString());
+        
+        
+        IaasContext c = new IaasContext(Iaases.ec2, null);
+        c.setScaleUpOrder(0);
+        c.setScaleDownOrder(4);
+        
+        iaasContexts.add(c);
+        
+        // scale up order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_UP_SORT)));
+        
+        assertEquals("ec2", iaasContexts.get(0).getName().toString());
+        assertEquals("ec2", iaasContexts.get(1).getName().toString());
+        
+        // scale down order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_DOWN_SORT)));
+        
+        assertEquals("openstack", iaasContexts.get(0).getName().toString());
+        assertEquals("ec2", iaasContexts.get(1).getName().toString());
+        
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java b/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java
new file mode 100644
index 0000000..2297a6f
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/util/IaasContextTest.java
@@ -0,0 +1,113 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.NodeMetadataBuilder;
+import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
+import org.apache.stratos.lb.common.conf.util.Constants;
+
+import junit.framework.TestCase;
+
+public class IaasContextTest extends TestCase {
+
+    IaasContext ctx;
+    NodeMetadata node1, node2, node3, node4;
+    
+    String[] domains = {"wso2.a", "wso2.b", "wso2.c"};
+    String[] subDomains = {"mgt", "worker"};
+    String[] nodeIds = {"1", "2", "3", "4", "5"};
+    String[] ips = {"192.168.1.2", "192.168.1.3", "192.168.1.4"};
+
+    public IaasContextTest(String name) {
+        super(name);
+    }
+
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        node1 = new NodeMetadataBuilder().id("1")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .publicAddresses(new ArrayList<String>(Arrays.asList("192.168.1.2")))
+                                         .build();
+        node2 = new NodeMetadataBuilder().id("2")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .build();
+        node3 = new NodeMetadataBuilder().id("3")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .build();
+        node4 = new NodeMetadataBuilder().id("4")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .build();
+
+        ctx = new IaasContext(Iaases.ec2, null);
+        
+        
+        ctx.addInstanceContext(new InstanceContext(domains[0], subDomains[0], null));
+        ctx.addInstanceContext(new InstanceContext(domains[1], subDomains[1], null));
+        ctx.addInstanceContext(new InstanceContext(domains[2], subDomains[0], null));
+        ctx.addInstanceContext(new InstanceContext(domains[2], Constants.DEFAULT_SUB_DOMAIN, null));
+        
+        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[0], "");
+        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[1], ips[0]);
+        ctx.addNodeDetails(domains[1], subDomains[1], nodeIds[2], ips[1]);
+        ctx.addNodeDetails(domains[2], subDomains[0], nodeIds[3], ips[2]);
+        ctx.addNodeDetails(domains[2], Constants.DEFAULT_SUB_DOMAIN, nodeIds[4], "");
+        
+        
+//        ctx.addNodeIdToDomainMap(node1.getId(), "wso2.a");
+//        ctx.addPublicIpToDomainMap("192.168.1.2", "wso2.a");
+//        ctx.addPublicIpToNodeIdMap("192.168.1.2", node1.getId());
+//        ctx.addNodeIdToDomainMap(node2.getId(), "wso2.b");
+//        ctx.addNodeIdToDomainMap(node3.getId(), "wso2.a");
+//        ctx.addPublicIpToDomainMap("192.168.1.3", "wso2.a");
+//        ctx.addPublicIpToNodeIdMap("192.168.1.3", node3.getId());
+//        ctx.addNodeIdToDomainMap(node4.getId(), "wso2.c");
+    }
+
+    public final void testGetLastMatchingNode() {
+
+        assertEquals(nodeIds[1], ctx.getLastMatchingNode(domains[0], subDomains[0]));
+        ctx.removeNodeId(nodeIds[1]);
+        assertEquals(nodeIds[0], ctx.getLastMatchingNode(domains[0], subDomains[0]));
+        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[1], ips[0]);
+    }
+
+    public final void testGetFirstMatchingNode() {
+        assertEquals(nodeIds[0], ctx.getFirstMatchingNode(domains[0], subDomains[0]));
+    }
+    
+    public final void testGetLastMatchingPublicIp() {
+        assertEquals(ips[0], ctx.getLastMatchingPublicIp(domains[0], subDomains[0]));
+        assertEquals(null, ctx.getLastMatchingPublicIp(domains[2], Constants.DEFAULT_SUB_DOMAIN));
+    }
+
+    public final void testGetNodeWithPublicIp() {
+        assertEquals(nodeIds[3], ctx.getNodeWithPublicIp(ips[2]));
+    }
+
+    public final void testGetNodeIds() {
+        assertEquals(new ArrayList<String>(Arrays.asList(nodeIds[0], nodeIds[1])), ctx.getNodeIds(domains[0], subDomains[0]));
+        assertEquals(new ArrayList<String>(Arrays.asList(nodeIds[2])), ctx.getNodeIds(domains[1], subDomains[1]));
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java b/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
new file mode 100644
index 0000000..54502b7
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/test/java/org/apache/stratos/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
@@ -0,0 +1,60 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.xml;
+
+import java.util.List;
+import org.apache.stratos.autoscaler.service.util.IaasProvider;
+import junit.framework.TestCase;
+
+public class ElasticScalerConfigFileReaderTest extends TestCase {
+
+    public void testGetIaasProvidersListy() throws Exception {
+        
+        String file = "src/test/resources/elastic-scaler-config.xml";
+        ElasticScalerConfigFileReader reader = new ElasticScalerConfigFileReader(file);
+        
+        List<IaasProvider> list =reader.getIaasProvidersList();
+        
+        assertEquals(2, list.size());
+        
+        assertEquals("ec2", list.get(0).getType());
+        //assertEquals("cdcd", list.get(0).getIdentity());
+        assertEquals(2, list.get(0).getScaleDownOrder());
+        assertEquals(1, list.get(0).getScaleUpOrder());
+        assertEquals("a", list.get(0).getProperties().get("A.x"));
+        assertEquals("b", list.get(0).getProperties().get("B"));
+        assertEquals(null, list.get(0).getProperties().get("AA"));
+        
+        assertEquals("openstack", list.get(1).getType());
+        //assertEquals("bebbe", list.get(1).getIdentity());
+        assertEquals(1, list.get(1).getScaleDownOrder());
+        assertEquals(2, list.get(1).getScaleUpOrder());
+        assertEquals("x", list.get(1).getProperties().get("X"));
+        assertEquals("y", list.get(1).getProperties().get("Y"));
+        assertEquals(null, list.get(1).getProperties().get("x"));
+        
+        
+        List<org.apache.stratos.autoscaler.service.util.ServiceTemplate> temps =reader.getTemplates();
+      
+        assertEquals("wso2.as.domain", temps.get(0).getDomainName());
+        assertEquals("manager,default", temps.get(0).getProperty("securityGroups"));
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/test/resources/elastic-scaler-config.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/test/resources/elastic-scaler-config.xml b/components/org.apache.stratos.autoscaler.service/src/test/resources/elastic-scaler-config.xml
new file mode 100644
index 0000000..d05bb14
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/test/resources/elastic-scaler-config.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+
+<!--
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+  -->
+
+<elasticScalerConfig xmlns:svns="http://org.wso2.securevault/configuration">
+
+<svns:secureVault provider="org.wso2.securevault.secret.handler.SecretManagerSecretCallbackHandler"/>
+	<iaasProviders>
+		<iaasProvider type="ec2" name="EC2 specific details">
+			<provider>aws-ec2</provider>
+			<identity svns:secretAlias="elastic.scaler.ec2.identity">cdcd</identity>
+			<credential svns:secretAlias="elastic.scaler.ec2.credential">cdccdc</credential>
+			<scaleUpOrder>1</scaleUpOrder>
+			<scaleDownOrder>2</scaleDownOrder>
+			<property name="A.x" value="a"/>
+			<property name="B" value="b"/>
+			<imageId>tempEC2</imageId>
+		</iaasProvider>
+		<iaasProvider type="openstack" >
+			<provider>lxc</provider>
+			<identity svns:secretAlias="elastic.scaler.openstack.identity">bebbe</identity>
+			<credential svns:secretAlias="elastic.scaler.openstack.credential">bebebe</credential>
+			<scaleUpOrder>2</scaleUpOrder>
+			<scaleDownOrder>1</scaleDownOrder>
+			<property name="X" value="x"/>
+			<property name="Y" value="y"/>
+			<imageId>tempLXC</imageId>
+		</iaasProvider>
+	</iaasProviders>
+	
+	<services>
+		<default>
+			<property name="availabilityZone" value="us-east-1c"/>
+			<property name="securityGroups" value="manager,cep,mb,default"/>
+            <property name="instanceType.ec2" value="m1.large"/>
+            <property name="instanceType.openstack" value="1"/>
+            <property name="minAppInstances" value="1"/>
+            <property name="maxAppInstances" value="5"/>
+            <property name="queueLengthPerNode" value="50"/>
+            <property name="roundsToAverage" value="100"/>
+            <property name="instancesPerScaleUp" value="1"/>
+            <property name="messageExpiryTime" value="60000"/>
+            <property name="keyPair" value="aa"/>
+		</default>
+		<service domain="wso2.as.domain" subDomain="mgt">
+			<property name="securityGroups" value="manager,default"/>
+            <property name="availabilityZone" value="us-east-1c"/>
+            <property name="payload" value="resources/as.zip"/>
+		</service>
+	</services>
+
+</elasticScalerConfig>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/pom.xml b/components/org.apache.stratos.cartridge.agent/2.1.3/pom.xml
deleted file mode 100644
index cadcdc7..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/pom.xml
+++ /dev/null
@@ -1,129 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
-     ~  Licensed to the Apache Software Foundation (ASF) under one
-     ~  or more contributor license agreements.  See the NOTICE file
-     ~  distributed with this work for additional information
-     ~  regarding copyright ownership.  The ASF licenses this file
-     ~  to you under the Apache License, Version 2.0 (the
-     ~  "License"); you may not use this file except in compliance
-     ~  with the License.  You may obtain a copy of the License at
-     ~
-     ~    http://www.apache.org/licenses/LICENSE-2.0
-     ~
-     ~  Unless required by applicable law or agreed to in writing,
-     ~  software distributed under the License is distributed on an
-     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-     ~  KIND, either express or implied.  See the License for the
-     ~  specific language governing permissions and limitations
-     ~  under the License.
-     ~
- -->
-	
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-	<parent>
-		<groupId>org.apache.stratos</groupId>
-		<artifactId>stratos-components-parent</artifactId>
-		<version>3.0.0-SNAPSHOT</version>
-                <relativePath>../../pom.xml</relativePath>
-	</parent>
-
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>org.apache.stratos.cartridge.agent</artifactId>
-        <packaging>bundle</packaging>
-        <version>2.1.3</version>
-	<name>Apache Stratos Cartridge Agent - agent</name>
-
-	<dependencies>
-		<dependency>
-		<groupId>org.apache.stratos</groupId>
-		<artifactId>org.apache.stratos.cartridge.messages</artifactId>
-                <version>${apache.stratos.version}</version>
-		</dependency>
-		<dependency>
-			<groupId>org.apache.axis2.wso2</groupId>
-			<artifactId>axis2</artifactId>
-			<version>${axis2.wso2.version}</version>
-		</dependency>
-		<dependency>
-			<groupId>org.apache.ws.commons.axiom.wso2</groupId>
-			<artifactId>axiom</artifactId>
-		        <version>${orbit.version.axiom}</version>
-		</dependency>
-		<dependency>
-			<groupId>commons-logging</groupId>
-			<artifactId>commons-logging</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.wso2.carbon</groupId>
-			<artifactId>org.wso2.carbon.adc.instanceinfo.mgt.stub</artifactId>
-			<version>4.1.1</version>
-		</dependency>
-        <dependency>
-            <groupId>org.eclipse.osgi</groupId>
-            <artifactId>org.eclipse.osgi</artifactId>
-            <version>3.5.0.v20090311-1300</version>
-        </dependency>
-        <dependency>
-            <groupId>org.eclipse.osgi</groupId>
-            <artifactId>org.eclipse.osgi.services</artifactId>
-            <version>3.3.0.v20110513</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.utils</artifactId>
-            <version>4.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.adc.instanceinfo.mgt.stub</artifactId>
-            <version>4.1.1</version>
-        </dependency>
-
-    </dependencies>
-
-    <build>
-        <plugins>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                <version>1.4.0</version>
-                <extensions>true</extensions>
-
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Private-Package>
-                            org.apache.stratos.cartridge.agent.internal.*,
-                            !org.apache.stratos.cartridge.agent.service.*
-                        </Private-Package>
-                        <Export-Package>
-                            org.apache.stratos.cartridge.agent.service.*,
-                            org.apache.stratos.cartridge.agent.client.*,
-                            org.apache.stratos.cartridge.agent.registrant.*,
-                            org.apache.stratos.cartridge.agent.exception.*,
-                            org.apache.stratos.cartridge.agent.*
-                        </Export-Package>
-                        <Import-Package>
-                            org.apache.axis2.*; version="${axis2.osgi.version.range}",
-                            org.apache.axiom.*;
-                            version="${axiom.osgi.version.range}",
-                            org.apache.neethi.*;
-                            version="${neethi.osgi.version.range.service-mgt}",
-                            javax.xml.stream.*; version="1.0.1",
-                            javax.wsdl.*; version="1.6.2",
-                            org.osgi.framework.*,
-                            *;resolution:=optional
-                        </Import-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/ClusteringClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/ClusteringClient.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/ClusteringClient.java
deleted file mode 100644
index b81b542..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/ClusteringClient.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent;
-
-import org.apache.axiom.om.impl.builder.StAXOMBuilder;
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.clustering.*;
-import org.apache.axis2.clustering.tribes.TribesClusteringAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.description.Parameter;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cartridge.agent.exception.CartridgeAgentException;
-import org.apache.stratos.cartridge.agent.registrant.PortMapping;
-import org.apache.stratos.cartridge.agent.registrant.Registrant;
-import org.apache.stratos.cartridge.agent.registrant.RegistrantDatabase;
-import org.apache.stratos.cartridge.agent.registrant.RegistrantUtil;
-import org.apache.stratos.cartridge.messages.CreateClusterDomainMessage;
-import org.apache.stratos.cartridge.messages.CreateRemoveClusterDomainMessage;
-
-import javax.xml.stream.XMLStreamException;
-import java.io.ByteArrayInputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-import java.util.Random;
-
-/**
- * This class is used for all Axis2 clustering related activities such as joining the load balancer
- * & joining registrants to clustering groups.
- */
-public class ClusteringClient {
-    private static final Log log = LogFactory.getLog(ClusteringClient.class);
-    public static final Random RANDOM = new Random();
-    private Properties conf;
-    private RegistrantDatabase registrantDatabase;
-    private ClusteringAgent loadBalancerAgent;
-
-    public ClusteringClient(RegistrantDatabase registrantDatabase) {
-        this.registrantDatabase = registrantDatabase;
-    }
-
-    public void init(Properties conf,
-                     ConfigurationContext configurationContext,
-                     MembershipListener membershipListener) throws CartridgeAgentException {
-        try {
-            this.conf = conf;
-            joinLoadBalancer(configurationContext, membershipListener);
-        } catch (Exception e) {
-            String msg = "Cannot initialize ClusteringClient";
-            log.error(msg, e);
-            throw new CartridgeAgentException(msg, e);
-        }
-    }
-
-    private void joinLoadBalancer(ConfigurationContext configurationContext,
-                                  MembershipListener membershipListener)
-            throws CartridgeAgentException {
-
-        try {
-            loadBalancerAgent = createClusteringAgent(configurationContext,
-                                                      conf.getProperty("loadBalancerDomain"));
-            List<MembershipListener> membershipListeners = new ArrayList<MembershipListener>();
-            membershipListeners.add(membershipListener);
-            ((TribesClusteringAgent) loadBalancerAgent).setMembershipListeners(membershipListeners);
-            loadBalancerAgent.init();
-        } catch (Exception e) {
-            String msg = "Cannot join LB group";
-            log.error(msg, e);
-            throw new CartridgeAgentException(msg, e);
-        }
-    }
-
-    /**
-     * Join a cluster group of the Elastic Load Balancer
-     *
-     * @param registrant           Registrant
-     * @param configurationContext ConfigurationContext
-     * @throws CartridgeAgentException If an error occurs while joining a cluster group
-     */
-    public void joinGroup(Registrant registrant,
-                          ConfigurationContext configurationContext) throws CartridgeAgentException {
-        if (registrantDatabase.containsActive(registrant)) {
-            throw new CartridgeAgentException("Active registrant with key " +
-                                              registrant.getKey() + " already exists");
-        }
-        registrantDatabase.add(registrant);
-
-        if (!RegistrantUtil.isHealthy(registrant)) {
-            String msg = "Couldn't add registrant " + registrant + " due to a health check failure";
-            log.error(msg);
-            return;
-            //throw new CartridgeAgentException(msg);
-        }
-        try {
-            List<ClusteringCommand> clusteringCommands =
-                    loadBalancerAgent.sendMessage(new CreateClusterDomainMessage(registrant.getService(),
-                                                                                 registrant.retrieveClusterDomain(),
-                                                                                 registrant.getHostName(),
-                                                                                 registrant.getTenantRange(),
-                                                                                 registrant.getMinInstanceCount(),
-                                                                                 registrant.getMaxInstanceCount(),
-                                                                                 registrant.getMaxRequestsPerSecond(),
-                                                                                 registrant.getRoundsToAverage(),
-                                                                                 registrant.getAlarmingUpperRate(),
-                                                                                 registrant.getAlarmingLowerRate(),
-                                                                                 registrant.getScaleDownFactor()),
-                                                  true);
-            if (clusteringCommands != null && !clusteringCommands.isEmpty()) {
-                for (ClusteringCommand clusteringCommand : clusteringCommands) {
-                    clusteringCommand.execute(configurationContext);
-                }
-            } else {
-                return;
-            }
-
-        } catch (ClusteringFault e) {
-            handleException("Cannot send CreateClusterDomainMessage to ELB", e);
-        }
-        ClusteringAgent agent;
-        try {
-            agent = createClusteringAgent(configurationContext,
-                                          registrant.retrieveClusterDomain());
-            
-        } catch (ClusteringFault e) {
-            handleException("Cannot create ClusteringAgent for registrant", e);
-            return;
-        }
-
-        //Add port.mapping.<port> entries to member
-        /*
-       <parameter name="properties">
-           <property name="port.mapping.8281" value="9768"/>
-           <property name="port.mapping.8244" value="9448"/>
-       </parameter>
-        */
-        Parameter propsParam = new Parameter();
-        propsParam.setName("properties");
-
-        StringBuilder propertiesPayload = new StringBuilder("<parameter name=\"properties\">");
-        int httpPort = -1;
-        int httpsPort = -1;
-        for (PortMapping portMapping : registrant.getPortMappings()) {
-            propertiesPayload.append("<property name=\"portMapping.mapping.").append(portMapping.getProxyPort()).
-                    append("\" value=\"").append(portMapping.getPrimaryPort()).append("\" />");
-            if (portMapping.getType().equals(PortMapping.PORT_TYPE_HTTP)) {
-                httpPort = portMapping.getPrimaryPort();
-            } else if (portMapping.getType().equals(PortMapping.PORT_TYPE_HTTPS)) {
-                httpsPort = portMapping.getPrimaryPort();
-            }
-        }
-
-        String remoteHost = registrant.getRemoteHost();
-        propertiesPayload.append("<property name=\"httpPort\" value=\"").append(httpPort).append("\" />");
-        propertiesPayload.append("<property name=\"httpsPort\" value=\"").append(httpsPort).append("\" />");
-        propertiesPayload.append("<property name=\"remoteHost\" value=\"").append(remoteHost).append("\" />");
-        propertiesPayload.append("<property name=\"subDomain\" value=\"__$default\" />");
-        propertiesPayload.append("</parameter>");
-
-        try {
-            StAXOMBuilder builder = new StAXOMBuilder(new ByteArrayInputStream(propertiesPayload.toString().getBytes()));
-            propsParam.setParameterElement(builder.getDocumentElement());
-            agent.addParameter(propsParam);
-        } catch (XMLStreamException e) {
-            handleException("Cannot create properties ClusteringAgent parameter", e);
-        } catch (AxisFault ignored) { // will not occur
-        }
-
-        int newMemberPort = Integer.parseInt(conf.getProperty("clustering.localMemberPort")) +
-                            RANDOM.nextInt(5000) + 27;
-        addParameter(agent, "localMemberPort", newMemberPort + "");
-        try {
-            synchronized (registrant) {
-                if(!registrant.running()) {
-                    registrant.start(agent);
-                }
-            }
-        } catch (ClusteringFault e) {
-            handleException("Cannot start registrant", e);
-        }
-        
-        // Update instance state in stratos database, with active
-        new Thread(new InstanceStateNotificationClientThread(registrant, "ACTIVE")).start();
-    }
-    
-    
-    public void removeClusterDomain(String domain,
-                                    String subDomain,
-                                    String hostName,
-                                    ConfigurationContext configurationContext) throws CartridgeAgentException {
-    	try {
-            List<ClusteringCommand> clusteringCommands =
-                    loadBalancerAgent.sendMessage(new CreateRemoveClusterDomainMessage(domain, subDomain, hostName),
-                                                  true);
-            if (clusteringCommands != null && !clusteringCommands.isEmpty()) {
-                for (ClusteringCommand clusteringCommand : clusteringCommands) {
-                    clusteringCommand.execute(configurationContext);
-                }
-            } else {
-                return;
-            }
-        } catch (ClusteringFault e) {
-            handleException("Cannot send CreateClusterDomainMessage to ELB", e);
-        }
-    }
-
-    private void handleException(String msg, Exception e) throws CartridgeAgentException {
-        log.error(msg, e);
-        throw new CartridgeAgentException(msg, e);
-    }
-
-    private ClusteringAgent createClusteringAgent(ConfigurationContext configurationContext,
-                                                  String clusterDomain) throws ClusteringFault {
-        TribesClusteringAgent agent = new TribesClusteringAgent();
-        addParameter(agent, "AvoidInitiation", "true");
-        for (String key : conf.stringPropertyNames()) {
-            if (key.startsWith("clustering.")) {
-                addParameter(agent,
-                             key.substring(key.indexOf(".") + 1),
-                             conf.getProperty(key));
-            }
-        }
-
-        List<Member> members = new ArrayList<Member>();
-        for (int i = 1; i < Integer.MAX_VALUE; i++) {
-            String host = conf.getProperty("members." + i + ".host");
-            String port = conf.getProperty("members." + i + ".port");
-            if (host == null || port == null) {
-                break;
-            }
-            members.add(new Member(host, Integer.parseInt(port)));
-        }
-        agent.setMembers(members);
-
-        addParameter(agent, "domain", clusterDomain);
-        agent.setConfigurationContext(configurationContext);
-
-        List<MembershipListener> membershipListeners = new ArrayList<MembershipListener>();
-        membershipListeners.add(new RegistrantMembershipListener(this, configurationContext));
-        agent.setMembershipListeners(membershipListeners);
-        return agent;
-    }
-
-    private static void addParameter(ClusteringAgent agent,
-                                     String paramName, String paramValue) {
-        Parameter parameter = new Parameter(paramName, paramValue);
-        try {
-            agent.removeParameter(parameter);
-            agent.addParameter(parameter);
-        } catch (AxisFault ignored) {
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/ELBMembershipListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/ELBMembershipListener.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/ELBMembershipListener.java
deleted file mode 100644
index ca2cd96..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/ELBMembershipListener.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent;
-
-import org.apache.axis2.clustering.Member;
-import org.apache.axis2.clustering.MembershipListener;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cartridge.agent.exception.CartridgeAgentException;
-import org.apache.stratos.cartridge.agent.registrant.RegistrantDatabase;
-import org.apache.stratos.cartridge.agent.registrant.RegistrantHealthChecker;
-import org.apache.stratos.cartridge.agent.registrant.RegistrantUtil;
-
-/**
- * This membership listener will get notified when the Elastic Load Balancer (ELB) joins or
- * leaves the cluster
- *
- * When the ELB leaves the cluster, we have to disconnect all Registrants, and when the ELB rejoins,
- * we have to reconnect all the Registrants to the ELB
- */
-public class ELBMembershipListener implements MembershipListener {
-    private static final Log log = LogFactory.getLog(ELBMembershipListener.class);
-
-    private ClusteringClient clusteringClient;
-    private ConfigurationContext configurationContext;
-    private RegistrantDatabase registrantDatabase;
-    private RegistrantHealthChecker healthChecker;
-
-    public ELBMembershipListener(ClusteringClient clusteringClient,
-                                 ConfigurationContext configurationContext,
-                                 RegistrantDatabase registrantDatabase,
-                                 RegistrantHealthChecker healthChecker) {
-        this.clusteringClient = clusteringClient;
-        this.configurationContext = configurationContext;
-        this.registrantDatabase = registrantDatabase;
-        this.healthChecker = healthChecker;
-    }
-
-    public void memberAdded(Member member, boolean b) {
-        log.info("ELB Member [" + member + "] joined cluster");
-        Runnable runnable = new Runnable() {
-            public void run() {
-                try {
-                    try {
-                        Thread.sleep(5000);
-                    } catch (InterruptedException ignored) {
-                    }
-                    RegistrantUtil.reloadRegistrants(clusteringClient,
-                                                     configurationContext,
-                                                     registrantDatabase);
-                    healthChecker.setELBRunning(true);
-                } catch (CartridgeAgentException e) {
-                    log.error("Could not reload registrants", e);
-                }
-            }
-        };
-        new Thread(runnable).start();
-    }
-
-    public void memberDisappeared(Member member, boolean b) {
-        log.info("ELB Member [" + member + "] left cluster");
-        healthChecker.setELBRunning(false);
-        registrantDatabase.stopAll();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/InstanceStateNotificationClientThread.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/InstanceStateNotificationClientThread.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/InstanceStateNotificationClientThread.java
deleted file mode 100644
index 8d3839d..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/InstanceStateNotificationClientThread.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent;
-
-import org.apache.axis2.AxisFault;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cartridge.agent.registrant.Registrant;
-import org.wso2.carbon.adc.instanceinfo.mgt.stub.InstanceInformationManagementServiceStub;
-
-import java.rmi.RemoteException;
-
-public class InstanceStateNotificationClientThread implements Runnable {
-
-	private Registrant registrant;
-	private String state;
-
-	private static final Log log = LogFactory
-			.getLog(InstanceStateNotificationClientThread.class);
-
-	public InstanceStateNotificationClientThread(Registrant registrant,
-			String state) {
-		this.registrant = registrant;
-		this.state = state;
-	}
-
-	public void run() {
-		try {
-			log.info("Instance State is updated to " + state + " "
-					+ registrant.getRemoteHost());
-			String serviceURL = "https://" + System.getProperty("adc.host")
-					+ ":" + System.getProperty("adc.port")
-					+ "/services/InstanceInformationManagementService";
-			InstanceInformationManagementServiceStub stub = new InstanceInformationManagementServiceStub(
-					serviceURL);
-			stub.updateInstanceState(registrant.getRemoteHost(), 123,
-					registrant.retrieveClusterDomain(), "__$default",
-					registrant.getService(), state);
-		} catch (AxisFault e) {
-            log.warn("Error notifying state " + state + " of registrant " + registrant + " to ADC", e);
-		} catch (RemoteException e) {
-            log.warn("Error notifying state " + state + " of registrant " + registrant + " to ADC", e);
-		}
-
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/Main.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/Main.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/Main.java
deleted file mode 100644
index f091e0b..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/Main.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.engine.AxisServer;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cartridge.agent.internal.CartridgeAgentConstants;
-import org.apache.stratos.cartridge.agent.registrant.RegistrantDatabase;
-import org.apache.stratos.cartridge.agent.registrant.RegistrantHealthChecker;
-import org.apache.stratos.cartridge.agent.service.CartridgeAgentService;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.Properties;
-
-/**
- * The main class which starts up the Cartridge agent
- */
-//public class Main {
-//    private static final Log log = LogFactory.getLog(Main.class);
-//    private static RegistrantHealthChecker healthChecker;
-//    public static void main(String[] args) {
-//        FileInputStream confFileIPStream = null;
-//        try {
-//            long start = System.currentTimeMillis();
-//            log.info("Starting WSO2 Cartridge Agent...");
-//            Properties conf = new Properties();
-//            confFileIPStream = new FileInputStream("conf" + File.separator + "agent.properties");
-//            conf.load(confFileIPStream);
-//            RegistrantDatabase registrantDatabase = new RegistrantDatabase();
-//            AxisServer axisServer = new AxisServer();
-//            ConfigurationContext configurationContext = axisServer.getConfigurationContext();
-//            ClusteringClient clusteringClient = new ClusteringClient(registrantDatabase);
-//            configurationContext.setProperty(CartridgeAgentConstants.CLUSTERING_CLIENT, clusteringClient);
-//            String healthCheckInterval = conf.getProperty("registrant.heathCheckInterval");
-//            String threadPoolSize = conf.getProperty("registrant.healthCheckThreadPoolSize");
-//            int healthCheckIntervalInt =
-//                    (healthCheckInterval == null) ? 2000 : Integer.parseInt(healthCheckInterval);
-//            int threadPoolSizeInt =
-//                    (threadPoolSize == null) ? 10 : Integer.parseInt(healthCheckInterval);
-//            log.info("Registrant health check interval: " + healthCheckIntervalInt + "s");
-//            healthChecker = new RegistrantHealthChecker(registrantDatabase,
-//                                                        clusteringClient,
-//                                                        configurationContext,
-//                                                        healthCheckIntervalInt,
-//                                                        threadPoolSizeInt
-//                                                        );
-//            clusteringClient.init(conf,
-//                                  configurationContext,
-//                                  new ELBMembershipListener(clusteringClient,
-//                                                            configurationContext,
-//                                                            registrantDatabase,
-//                                                            healthChecker));
-//            healthChecker.startAll();
-//            axisServer.deployService(CartridgeAgentService.class.getName());
-//
-//
-//            // Starting cliet..
-//            String trustStorePath = conf.getProperty("wso2.carbon.truststore");
-//            System.setProperty("javax.net.ssl.trustStore", trustStorePath);
-//            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
-//            // new InstanceStateNotificationClient().notify(null, null);
-//
-//            System.setProperty("adc.host",  conf.getProperty("adc.host"));
-//            System.setProperty("adc.port",  conf.getProperty("adc.port"));
-//            // ----------------------
-//
-//            writePID(".");
-//            Runtime.getRuntime().addShutdownHook(new Thread(){
-//
-//                @Override
-//                public void run() {
-//                    log.info("Shutting down WSO2 Cartridge Agent...");
-//                }
-//            });
-//            log.info("Started Cartridge Agent in " + (System.currentTimeMillis() - start) + "ms");
-//        } catch (Exception e) {
-//            log.fatal("Could not start Cartridge Agent", e);
-//            System.exit(1);
-//        } finally {
-//            if (confFileIPStream != null) {
-//                try {
-//                    confFileIPStream.close();
-//                } catch (IOException e) {
-//                    log.error("Cannot close agent.properties file", e);
-//                }
-//            }
-//        }
-//    }
-//
-//    public static RegistrantHealthChecker getHealthChecker(){
-//        return healthChecker;
-//    }
-//    /**
-//     * Write the process ID of this process to the file
-//     *
-//     * @param carbonHome carbon.home sys property value.
-//     */
-//    private static void writePID(String carbonHome) {
-//        byte[] bo = new byte[100];
-//        String[] cmd = {"bash", "-c", "echo $PPID"};
-//        Process p;
-//        try {
-//            p = Runtime.getRuntime().exec(cmd);
-//        } catch (IOException e) {
-//            //ignored. We might be invoking this on a Window platform. Therefore if an error occurs
-//            //we simply ignore the error.
-//            return;
-//        }
-//
-//        try {
-//            int bytes = p.getInputStream().read(bo);
-//        } catch (IOException e) {
-//            log.error(e.getMessage(), e);
-//        }
-//
-//        String pid = new String(bo);
-//        if (pid.length() != 0) {
-//            BufferedWriter out = null;
-//            try {
-//                FileWriter writer = new FileWriter(carbonHome + File.separator + "wso2carbon.pid");
-//                out = new BufferedWriter(writer);
-//                out.write(pid);
-//            } catch (IOException e) {
-//                log.warn("Cannot write wso2carbon.pid file");
-//            } finally {
-//                if (out != null) {
-//                    try {
-//                        out.close();
-//                    } catch (IOException ignored) {
-//                    }
-//                }
-//            }
-//        }
-//    }
-//}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/RegistrantMembershipListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/RegistrantMembershipListener.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/RegistrantMembershipListener.java
deleted file mode 100644
index 05ff859..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/RegistrantMembershipListener.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent;
-
-import org.apache.axis2.clustering.Member;
-import org.apache.axis2.clustering.MembershipListener;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cartridge.agent.registrant.Registrant;
-
-/**
- * @author wso2
- *
- */
-public class RegistrantMembershipListener implements MembershipListener{
-	
-	private ClusteringClient clusteringClient;
-	private ConfigurationContext configurationContext;
-
-	private static final Log log = LogFactory.getLog(RegistrantMembershipListener.class);
-	
-	public RegistrantMembershipListener(ClusteringClient clusteringClient,
-	                                    ConfigurationContext configurationContext) {
-		this.clusteringClient = clusteringClient;
-		this.configurationContext = configurationContext;
-    }
-
-	public void memberAdded(Member arg0, boolean arg1) {
-	    log.info(" ********* Member is added to the group ... " + arg0);
-    }
-
-	public void memberDisappeared(Member member, boolean arg1) {
-		 log.info(" **********  Member is removed from group ... " + member);
-		 Registrant registrant = new Registrant();
-		 
-		 //HostName : cartridgeName + "." + cartridgeInfo.getHostName()
-		 // sajithphpautoscale.php.slive.com.php.domain
-		 //Domain : HostName.php.domain
-		 // TODO
-    		/* String hostName = getHostNameFromDomain(member.getDomain());
-    		 log.info("Host name is returned as: " + hostName);
-    		 try {
-    	        clusteringClient.removeClusterDomain(member.getDomain(), "__$default", hostName, configurationContext);
-            } catch (CartridgeAgentException e) {
-    	        e.printStackTrace();
-            }*/
-    }
-
-	private String getHostNameFromDomain(String domain) {
-	    return domain.substring(0, domain.length()-11);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/exception/CartridgeAgentException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/exception/CartridgeAgentException.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/exception/CartridgeAgentException.java
deleted file mode 100644
index 40e38e4..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/exception/CartridgeAgentException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent.exception;
-
-/**
- * CartridgeAgentException
- */
-public class CartridgeAgentException extends Exception {
-    public CartridgeAgentException() {
-        super();
-    }
-
-    public CartridgeAgentException(String s) {
-        super(s);
-    }
-
-    public CartridgeAgentException(String s, Throwable throwable) {
-        super(s, throwable);
-    }
-
-    public CartridgeAgentException(Throwable throwable) {
-        super(throwable);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentConstants.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentConstants.java
deleted file mode 100644
index 2bd4a99..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentConstants.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-
-package org.apache.stratos.cartridge.agent.internal;
-
-/**
- * Constants used in the Cartridge Agent
- */
-public final class CartridgeAgentConstants {
-    public static final String CLUSTERING_CLIENT = "clustering.client";
-}


[37/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/utils/Util.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/utils/Util.java b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/utils/Util.java
new file mode 100644
index 0000000..98bb716
--- /dev/null
+++ b/components/org.apache.stratos.activation/src/main/java/org/apache/stratos/activation/activation/utils/Util.java
@@ -0,0 +1,138 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.activation.activation.utils;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.service.RealmService;
+
+/**
+ * Utilities for the Service Activation Module for Tenants.
+ */
+public class Util {
+
+    private static RegistryService registryService = null;
+    private static RealmService realmService = null;
+    private static String serviceName = null;
+    private static final Log log = LogFactory.getLog(Util.class);
+
+    private static boolean cloudServiceInfoPathSanityChecked = false;
+
+    /**
+     * Stores an instance of the Registry Service that can be used to access the registry.
+     *
+     * @param service the Registry Service instance.
+     */
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    /**
+     * Method to retrieve the Registry Service instance.
+     *
+     * @return the Registry Service instance if it has been stored or null if not.
+     */
+    @SuppressWarnings("unused")
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    /**
+     * Stores an instance of the Realm Service that can be used to access the user realm.
+     *
+     * @param service the Realm Service instance.
+     */
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    /**
+     * Method to retrieve the Realm Service instance.
+     *
+     * @return the Realm Service instance if it has been stored or null if not.
+     */
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    private static UserRegistry getSuperTenantGovernanceSystemRegistry() throws RegistryException {
+        return registryService.getGovernanceSystemRegistry();
+    }
+
+//    /**
+//     * Method to determine whether the given cloud service is active.
+//     *
+//     * @param cloudServiceName the name of the cloud service.
+//     * @param tenantId         the tenant identifier.
+//     * @param systemRegistry   the super tenant's governance system registry
+//     *
+//     * @return true if the service is active or false if not.
+//     * @throws Exception if the operation failed.
+//     */
+//    public static boolean isCloudServiceActive(String cloudServiceName,
+//                                               int tenantId, UserRegistry systemRegistry)
+//            throws Exception {
+//        // The cloud manager is always active
+//        if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
+//            return true;
+//        }
+//
+//        if(!cloudServiceInfoPathSanityChecked) {
+//            if(!systemRegistry.resourceExists(StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH)) {
+//                throw new RuntimeException("Cloud services list resource " +
+//                                           StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH + " does not exist");
+//            }
+//            cloudServiceInfoPathSanityChecked = true;
+//        }
+//
+//        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
+//                RegistryConstants.PATH_SEPARATOR + tenantId +
+//                RegistryConstants.PATH_SEPARATOR + cloudServiceName;
+//        Resource cloudServiceInfoResource;
+//        if (systemRegistry.resourceExists(cloudServiceInfoPath)) {
+//            cloudServiceInfoResource = systemRegistry.get(cloudServiceInfoPath);
+//            String isActiveStr =
+//                cloudServiceInfoResource.getProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
+//            return Boolean.toString(true).equals(isActiveStr);
+//        }
+//        return false;
+//    }
+//
+
+    /**
+     * Method to obtain the name of the cloud service in which this module is running.
+     *
+     * @return the name of the service as defined in the server configuration.
+     */
+    public static String getServiceName() {
+        if (serviceName == null) {
+            serviceName = ServerConfiguration.getInstance().getFirstProperty("Name");
+        }
+        return serviceName;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/src/main/resources/META-INF/module.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/src/main/resources/META-INF/module.xml b/components/org.apache.stratos.activation/src/main/resources/META-INF/module.xml
new file mode 100644
index 0000000..220e0e5
--- /dev/null
+++ b/components/org.apache.stratos.activation/src/main/resources/META-INF/module.xml
@@ -0,0 +1,33 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<module name="activation" class="org.apache.stratos.activation.activation.module.ActivationModule">
+   <InFlow>
+        <handler name="InFlowActivationHandler"
+                 class="org.apache.stratos.activation.activation.module.ActivationHandler">
+        <order phase="Validation" phaseFirst="true"/>
+        </handler>
+   </InFlow>
+
+   <InFaultFlow>
+        <handler name="FaultInFlowActivationHandler"
+                 class="org.apache.stratos.activation.activation.module.ActivationHandler">
+        <order phase="Validation" phaseFirst="true"/>
+        </handler>
+   </InFaultFlow>
+  <parameter name="adminModule" locked="true">true</parameter>
+</module>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.activation/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.activation/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.activation/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..01c4d91
--- /dev/null
+++ b/components/org.apache.stratos.activation/src/main/resources/META-INF/services.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ !
+ ! Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ !
+ ! WSO2 Inc. licenses this file to you under the Apache License,
+ ! Version 2.0 (the "License"); you may not use this file except
+ ! in compliance with the License.
+ ! You may obtain a copy of the License at
+ !
+ ! http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing,
+ ! software distributed under the License is distributed on an
+ ! "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ! KIND, either express or implied.  See the License for the
+ ! specific language governing permissions and limitations
+ ! under the License.
+ !-->
+<serviceGroup>
+    <service name="ActivationService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.apache.stratos.activation.activation.service.ActivationService
+        </parameter>
+    </service>
+    <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/pom.xml b/components/org.apache.stratos.adc.mgt.cli/2.1.3/pom.xml
deleted file mode 100644
index e82ce78..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/pom.xml
+++ /dev/null
@@ -1,125 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights 
-	Reserved. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); 
-	~ you may not use this file except in compliance with the License. ~ You 
-	may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 
-	~ ~ Unless required by applicable law or agreed to in writing, software ~ 
-	distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT 
-	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the 
-	License for the specific language governing permissions and ~ limitations 
-	under the License. -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-	<parent>
-		<groupId>org.apache.stratos</groupId>
-		<artifactId>stratos-components-parent</artifactId>
-		<version>3.0.0-SNAPSHOT</version>
-                <relativePath>../../pom.xml</relativePath>
-	</parent>
-
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>org.apache.stratos.adc.mgt.cli</artifactId>
-        <version>2.1.3</version>
-	<packaging>jar</packaging>
-	<name>Apache Stratos - ADC Management CLI</name>
-	<description>ADC management CLI bundle</description>
-	<url>http://apache.org</url>
-	
-	<properties>
-		<slf4j.version>1.7.5</slf4j.version>
-	</properties>
-
-	<dependencies>
-		<!-- <dependency>
-			<groupId>org.wso2.carbon</groupId>
-			<artifactId>org.wso2.carbon.ui</artifactId>
-		</dependency> -->
-		<!-- Adding HttpClient dependencies. Those were resolved with above one -->
-		<dependency>
-			<groupId>commons-httpclient</groupId>
-			<artifactId>commons-httpclient</artifactId>
-			<version>${commons-httpclient.version}</version>
-		</dependency>
-		<dependency>
-			<groupId>org.wso2.securevault</groupId>
-			<artifactId>org.wso2.securevault</artifactId>
-			<version>1.0.0-wso2v2</version>
-		</dependency>
-		<dependency>
-			<groupId>org.apache.httpcomponents.wso2</groupId>
-			<artifactId>httpcore</artifactId>
-			<version>4.1.0-wso2v1</version>
-		</dependency>
-		<dependency>
-			<groupId>org.apache.stratos</groupId>
-			<artifactId>org.apache.stratos.adc.mgt.stub</artifactId>
-			<version>4.1.3</version>
-		</dependency>
-		<dependency>
-			<groupId>commons-cli</groupId>
-			<artifactId>commons-cli</artifactId>
-			<version>1.2</version>
-		</dependency>
-		<dependency>
-			<groupId>jline</groupId>
-			<artifactId>jline</artifactId>
-			<version>2.11</version>
-		</dependency>
-		<dependency>
-			<groupId>org.apache.commons</groupId>
-			<artifactId>commons-lang3</artifactId>
-			<version>3.1</version>
-		</dependency>
-		<dependency>
-			<groupId>commons-validator</groupId>
-			<artifactId>commons-validator</artifactId>
-			<version>1.4.0</version>
-		</dependency>
-		<!-- Logging -->
-		<dependency>
-			<groupId>org.slf4j</groupId>
-			<artifactId>slf4j-api</artifactId>
-			<version>${slf4j.version}</version>
-		</dependency>
-		<dependency>
-			<groupId>org.slf4j</groupId>
-			<artifactId>slf4j-log4j12</artifactId>
-			<version>${slf4j.version}</version>
-			<scope>runtime</scope>
-		</dependency>
-		<dependency>
-			<groupId>com.google.code.gson</groupId>
-			<artifactId>gson</artifactId>
-			<version>2.1</version>
-		</dependency>
-	</dependencies>
-	<build>
-		<plugins>
-			<plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-assembly-plugin</artifactId>
-				<configuration>
-					<archive>
-						<manifest>
-							<mainClass>org.apache.stratos.adc.mgt.cli.CliTool</mainClass>
-						</manifest>
-					</archive>
-					<descriptors>
-						<descriptor>src/main/assembly/src.xml</descriptor>
-					</descriptors>
-				</configuration>
-				<executions>
-					<execution>
-						<id>make-assembly</id> <!-- this is used for inheritance merges -->
-						<phase>package</phase> <!-- bind to the packaging phase -->
-						<goals>
-							<goal>single</goal>
-						</goals>
-					</execution>
-				</executions>
-			</plugin>
-		</plugins>
-	</build>
-
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/assembly/src.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/assembly/src.xml b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/assembly/src.xml
deleted file mode 100644
index ec41ef1..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/assembly/src.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<!--
-       Licensed to the Apache Software Foundation (ASF) under one
-       or more contributor license agreements.  See the NOTICE file
-       distributed with this work for additional information
-       regarding copyright ownership.  The ASF licenses this file
-       to you under the Apache License, Version 2.0 (the
-       "License"); you may not use this file except in compliance
-       with the License.  You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing,
-       software distributed under the License is distributed on an
-       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-       KIND, either express or implied.  See the License for the
-       specific language governing permissions and limitations
-       under the License.
- -->
-<assembly
-	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
-	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
-	<id>Tool</id>
-	<formats>
-		<format>jar</format>
-	</formats>
-	<includeBaseDirectory>false</includeBaseDirectory>
-	<dependencySets>
-		<dependencySet>
-			<outputDirectory>/</outputDirectory>
-			<useProjectArtifact>true</useProjectArtifact>
-			<unpack>true</unpack>
-			<scope>runtime</scope>
-		</dependencySet>
-	</dependencySets>
-</assembly>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/Main.iml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/Main.iml b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/Main.iml
deleted file mode 100644
index 9a9b340..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/Main.iml
+++ /dev/null
@@ -1,204 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<module type="JAVA_MODULE" version="4">
-  <component name="NewModuleRootManager" inherit-compiler-output="true">
-    <exclude-output />
-    <content url="file://$MODULE_DIR$">
-      <sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
-    </content>
-    <orderEntry type="inheritedJdk" />
-    <orderEntry type="sourceFolder" forTests="false" />
-  </component>
-  <component name="org.twodividedbyzero.idea.findbugs">
-    <option name="_basePreferences">
-      <map>
-        <entry key="property.analysisEffortLevel" value="default" />
-        <entry key="property.analyzeAfterCompile" value="false" />
-        <entry key="property.annotationGutterIconEnabled" value="true" />
-        <entry key="property.annotationSuppressWarningsClass" value="edu.umd.cs.findbugs.annotations.SuppressWarnings" />
-        <entry key="property.annotationTextRangeMarkupEnabled" value="true" />
-        <entry key="property.exportAsHtml" value="true" />
-        <entry key="property.exportAsXml" value="true" />
-        <entry key="property.exportBaseDir" value="" />
-        <entry key="property.exportCreateArchiveDir" value="false" />
-        <entry key="property.exportOpenBrowser" value="true" />
-        <entry key="property.minPriorityToReport" value="Medium" />
-        <entry key="property.runAnalysisInBackground" value="false" />
-        <entry key="property.showHiddenDetectors" value="false" />
-        <entry key="property.toolWindowToFront" value="true" />
-      </map>
-    </option>
-    <option name="_detectors">
-      <map>
-        <entry key="AppendingToAnObjectOutputStream" value="true" />
-        <entry key="AtomicityProblem" value="true" />
-        <entry key="BadAppletConstructor" value="false" />
-        <entry key="BadResultSetAccess" value="true" />
-        <entry key="BadSyntaxForRegularExpression" value="true" />
-        <entry key="BadUseOfReturnValue" value="true" />
-        <entry key="BadlyOverriddenAdapter" value="true" />
-        <entry key="BooleanReturnNull" value="true" />
-        <entry key="BuildInterproceduralCallGraph" value="false" />
-        <entry key="BuildObligationPolicyDatabase" value="true" />
-        <entry key="CallToUnsupportedMethod" value="false" />
-        <entry key="CalledMethods" value="true" />
-        <entry key="CheckCalls" value="false" />
-        <entry key="CheckExpectedWarnings" value="false" />
-        <entry key="CheckImmutableAnnotation" value="true" />
-        <entry key="CheckTypeQualifiers" value="true" />
-        <entry key="CloneIdiom" value="true" />
-        <entry key="ComparatorIdiom" value="true" />
-        <entry key="ConfusedInheritance" value="true" />
-        <entry key="ConfusionBetweenInheritedAndOuterMethod" value="true" />
-        <entry key="CrossSiteScripting" value="true" />
-        <entry key="DefaultEncodingDetector" value="true" />
-        <entry key="DoInsideDoPrivileged" value="true" />
-        <entry key="DontCatchIllegalMonitorStateException" value="true" />
-        <entry key="DontIgnoreResultOfPutIfAbsent" value="true" />
-        <entry key="DontUseEnum" value="true" />
-        <entry key="DroppedException" value="true" />
-        <entry key="DumbMethodInvocations" value="true" />
-        <entry key="DumbMethods" value="true" />
-        <entry key="DuplicateBranches" value="true" />
-        <entry key="EmptyZipFileEntry" value="true" />
-        <entry key="EqualsOperandShouldHaveClassCompatibleWithThis" value="true" />
-        <entry key="ExplicitSerialization" value="true" />
-        <entry key="FieldItemSummary" value="true" />
-        <entry key="FinalizerNullsFields" value="true" />
-        <entry key="FindBadCast2" value="true" />
-        <entry key="FindBadForLoop" value="true" />
-        <entry key="FindBugsSummaryStats" value="true" />
-        <entry key="FindCircularDependencies" value="false" />
-        <entry key="FindDeadLocalStores" value="true" />
-        <entry key="FindDoubleCheck" value="true" />
-        <entry key="FindEmptySynchronizedBlock" value="true" />
-        <entry key="FindFieldSelfAssignment" value="true" />
-        <entry key="FindFinalizeInvocations" value="true" />
-        <entry key="FindFloatEquality" value="true" />
-        <entry key="FindFloatMath" value="false" />
-        <entry key="FindHEmismatch" value="true" />
-        <entry key="FindInconsistentSync2" value="true" />
-        <entry key="FindJSR166LockMonitorenter" value="true" />
-        <entry key="FindLocalSelfAssignment2" value="true" />
-        <entry key="FindMaskedFields" value="true" />
-        <entry key="FindMismatchedWaitOrNotify" value="true" />
-        <entry key="FindNakedNotify" value="true" />
-        <entry key="FindNonSerializableStoreIntoSession" value="false" />
-        <entry key="FindNonSerializableValuePassedToWriteObject" value="false" />
-        <entry key="FindNonShortCircuit" value="true" />
-        <entry key="FindNullDeref" value="true" />
-        <entry key="FindNullDerefsInvolvingNonShortCircuitEvaluation" value="true" />
-        <entry key="FindOpenStream" value="true" />
-        <entry key="FindPuzzlers" value="true" />
-        <entry key="FindRefComparison" value="true" />
-        <entry key="FindReturnRef" value="true" />
-        <entry key="FindRunInvocations" value="true" />
-        <entry key="FindSelfComparison" value="true" />
-        <entry key="FindSelfComparison2" value="true" />
-        <entry key="FindSleepWithLockHeld" value="true" />
-        <entry key="FindSpinLoop" value="true" />
-        <entry key="FindSqlInjection" value="true" />
-        <entry key="FindTwoLockWait" value="true" />
-        <entry key="FindUncalledPrivateMethods" value="true" />
-        <entry key="FindUnconditionalWait" value="true" />
-        <entry key="FindUninitializedGet" value="true" />
-        <entry key="FindUnrelatedTypesInGenericContainer" value="true" />
-        <entry key="FindUnreleasedLock" value="true" />
-        <entry key="FindUnsatisfiedObligation" value="true" />
-        <entry key="FindUnsyncGet" value="true" />
-        <entry key="FindUseOfNonSerializableValue" value="true" />
-        <entry key="FindUselessControlFlow" value="true" />
-        <entry key="FormatStringChecker" value="true" />
-        <entry key="FunctionsThatMightBeMistakenForProcedures" value="true" />
-        <entry key="HugeSharedStringConstants" value="true" />
-        <entry key="IDivResultCastToDouble" value="true" />
-        <entry key="IncompatMask" value="true" />
-        <entry key="InconsistentAnnotations" value="true" />
-        <entry key="InefficientMemberAccess" value="false" />
-        <entry key="InefficientToArray" value="true" />
-        <entry key="InfiniteLoop" value="true" />
-        <entry key="InfiniteRecursiveLoop" value="true" />
-        <entry key="InheritanceUnsafeGetResource" value="true" />
-        <entry key="InitializationChain" value="true" />
-        <entry key="InitializeNonnullFieldsInConstructor" value="true" />
-        <entry key="InstantiateStaticClass" value="true" />
-        <entry key="IntCast2LongAsInstant" value="true" />
-        <entry key="InvalidJUnitTest" value="true" />
-        <entry key="IteratorIdioms" value="true" />
-        <entry key="LazyInit" value="true" />
-        <entry key="LoadOfKnownNullValue" value="true" />
-        <entry key="LostLoggerDueToWeakReference" value="true" />
-        <entry key="MethodReturnCheck" value="true" />
-        <entry key="Methods" value="true" />
-        <entry key="MultithreadedInstanceAccess" value="true" />
-        <entry key="MutableLock" value="true" />
-        <entry key="MutableStaticFields" value="true" />
-        <entry key="Naming" value="true" />
-        <entry key="Noise" value="false" />
-        <entry key="NoiseNullDeref" value="false" />
-        <entry key="NoteAnnotationRetention" value="true" />
-        <entry key="NoteCheckReturnValueAnnotations" value="true" />
-        <entry key="NoteDirectlyRelevantTypeQualifiers" value="true" />
-        <entry key="NoteJCIPAnnotation" value="true" />
-        <entry key="NoteNonNullAnnotations" value="true" />
-        <entry key="NoteNonnullReturnValues" value="true" />
-        <entry key="NoteSuppressedWarnings" value="true" />
-        <entry key="NoteUnconditionalParamDerefs" value="true" />
-        <entry key="NumberConstructor" value="true" />
-        <entry key="OverridingEqualsNotSymmetrical" value="true" />
-        <entry key="PreferZeroLengthArrays" value="true" />
-        <entry key="PublicSemaphores" value="false" />
-        <entry key="QuestionableBooleanAssignment" value="true" />
-        <entry key="ReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass" value="true" />
-        <entry key="ReadReturnShouldBeChecked" value="true" />
-        <entry key="RedundantInterfaces" value="true" />
-        <entry key="ReflectiveClasses" value="true" />
-        <entry key="RepeatedConditionals" value="true" />
-        <entry key="ResolveAllReferences" value="false" />
-        <entry key="RuntimeExceptionCapture" value="true" />
-        <entry key="SerializableIdiom" value="true" />
-        <entry key="StartInConstructor" value="true" />
-        <entry key="StaticCalendarDetector" value="true" />
-        <entry key="StringConcatenation" value="true" />
-        <entry key="SuperfluousInstanceOf" value="true" />
-        <entry key="SuspiciousThreadInterrupted" value="true" />
-        <entry key="SwitchFallthrough" value="true" />
-        <entry key="SynchronizationOnSharedBuiltinConstant" value="true" />
-        <entry key="SynchronizeAndNullCheckField" value="true" />
-        <entry key="SynchronizeOnClassLiteralNotGetClass" value="true" />
-        <entry key="SynchronizingOnContentsOfFieldToProtectField" value="true" />
-        <entry key="TestASM" value="false" />
-        <entry key="TestDataflowAnalysis" value="false" />
-        <entry key="TestingGround" value="false" />
-        <entry key="TestingGround2" value="false" />
-        <entry key="TrainFieldStoreTypes" value="true" />
-        <entry key="TrainLongInstantfParams" value="true" />
-        <entry key="TrainNonNullAnnotations" value="true" />
-        <entry key="TrainUnconditionalDerefParams" value="true" />
-        <entry key="URLProblems" value="true" />
-        <entry key="UncallableMethodOfAnonymousClass" value="true" />
-        <entry key="UnnecessaryMath" value="true" />
-        <entry key="UnreadFields" value="true" />
-        <entry key="UselessSubclassMethod" value="false" />
-        <entry key="VarArgsProblems" value="true" />
-        <entry key="VolatileUsage" value="true" />
-        <entry key="WaitInLoop" value="true" />
-        <entry key="WrongMapIterator" value="true" />
-        <entry key="XMLFactoryBypass" value="true" />
-      </map>
-    </option>
-    <option name="_reportCategories">
-      <map>
-        <entry key="BAD_PRACTICE" value="true" />
-        <entry key="CORRECTNESS" value="true" />
-        <entry key="EXPERIMENTAL" value="true" />
-        <entry key="I18N" value="true" />
-        <entry key="MALICIOUS_CODE" value="true" />
-        <entry key="MT_CORRECTNESS" value="true" />
-        <entry key="PERFORMANCE" value="true" />
-        <entry key="SECURITY" value="true" />
-        <entry key="STYLE" value="true" />
-      </map>
-    </option>
-  </component>
-</module>
-

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CliTool.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CliTool.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CliTool.java
deleted file mode 100644
index 4a824a4..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CliTool.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli;
-
-import static org.apache.stratos.adc.mgt.cli.utils.CliConstants.STRATOS_DIR;
-
-import java.io.File;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This class is used for input the commands through CLITool, command prompt.
- */
-public class CliTool {
-
-	private static final Logger logger = LoggerFactory.getLogger(CliTool.class);
-
-	/**
-	 * Main executable method used to call from CLI.
-	 * 
-	 */
-	public static void main(final String[] args) {
-		CliTool cliTool = new CliTool();
-		cliTool.createConfigDirectory();
-		cliTool.handleConsoleInputs(args);
-	}
-
-	/**
-	 * Here is the place all the command line inputs get processed
-	 * 
-	 * @param arguments
-	 *            passed to CLI tool.
-	 */
-	private void handleConsoleInputs(String[] arguments) {
-		if (logger.isInfoEnabled()) {
-			logger.info("Stratos CLI Started...");
-		}
-		StratosApplication application = new StratosApplication();
-		application.start(arguments);
-	}
-
-	private void createConfigDirectory() {
-		File stratosFile = new File(System.getProperty("user.home"), STRATOS_DIR);
-		if (stratosFile.exists()) {
-			if (logger.isInfoEnabled()) {
-				logger.info("Using directory: {}", stratosFile.getPath());
-			}
-		} else {
-			if (stratosFile.mkdir()) {
-				if (logger.isInfoEnabled()) {
-					logger.info("Created directory: {}", stratosFile.getPath());
-				}
-			} else if (logger.isWarnEnabled()) {
-				logger.warn("Failed to created directory: {}", stratosFile.getPath());
-			}
-		}
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/Command.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/Command.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/Command.java
deleted file mode 100644
index caebaa4..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/Command.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli;
-
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.commons.cli.Options;
-
-public interface Command<T extends CommandContext> {
-
-	/**
-	 * @return The name of the command
-	 */
-	String getName();
-
-	/**
-	 * Information about the command
-	 * 
-	 * @return The description of the command
-	 */
-	String getDescription();
-
-	/**
-	 * This should return the syntax required for the command.
-	 * 
-	 * Used to display help.
-	 * 
-	 * @return The syntax for this command
-	 */
-	String getArgumentSyntax();
-
-	/**
-	 * The options accepted by the command
-	 * 
-	 * @return The Options for the commands
-	 */
-	Options getOptions();
-
-	/**
-	 * Executing the commands. Returns a code
-	 * 
-	 * @param context
-	 *            The context assoicated with the Command Line Application
-	 * @param args
-	 *            The arguments for the command
-	 * @return The status code
-	 * @throws org.apache.stratos.adc.mgt.cli.exception.CommandException
-	 *             if any errors occur when executing the command
-	 */
-	int execute(T context, String[] args) throws CommandException;
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandContext.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandContext.java
deleted file mode 100644
index 745b2f4..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandContext.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Observable;
-
-public class CommandContext extends Observable {
-
-	/**
-	 * Properties for the context.
-	 */
-	private Map<String, Object> properties;
-
-	/**
-	 * The application
-	 */
-	private final CommandLineApplication<? extends CommandContext> application;
-
-	public CommandContext(CommandLineApplication<? extends CommandContext> application) {
-		properties = new HashMap<String, Object>();
-		this.application = application;
-	}
-
-	public final CommandLineApplication<? extends CommandContext> getApplication() {
-		return application;
-	}
-
-	/**
-	 * Set property in the context
-	 * 
-	 * @param key
-	 *            The key
-	 * @param o
-	 *            The value for the key
-	 * @return The previous value or null
-	 */
-	public Object put(String key, Object o) {
-		Object previous = properties.put(key, o);
-		setChanged();
-		notifyObservers();
-		return previous;
-	}
-
-	/**
-	 * Get property value from the context
-	 * 
-	 * @param key
-	 *            The key
-	 * @return The value
-	 */
-	public Object getObject(String key) {
-		return properties.get(key);
-	}
-
-	/**
-	 * Get the string value, or null
-	 * 
-	 * @param key
-	 *            The key
-	 * @return The string value, or null.
-	 */
-	public String getString(String key) {
-		Object o = getObject(key);
-		if (o instanceof String) {
-			return (String) o;
-		}
-		return null;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineApplication.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineApplication.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineApplication.java
deleted file mode 100644
index 010948f..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineApplication.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli;
-
-import java.io.File;
-import java.io.IOException;
-
-import jline.console.ConsoleReader;
-import jline.console.history.FileHistory;
-
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class CommandLineApplication<T extends CommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(CommandLineApplication.class);
-
-	protected final ConsoleReader reader;
-	protected FileHistory history;
-
-	public CommandLineApplication() {
-		reader = createConsoleReader();
-	}
-
-	/**
-	 * Creates new jline ConsoleReader.
-	 * 
-	 * @return a jline ConsoleReader instance
-	 */
-	protected ConsoleReader createConsoleReader() {
-		ConsoleReader consoleReader = null;
-		try {
-			consoleReader = new ConsoleReader();
-			consoleReader.setPrompt(getPrompt());
-			history = new FileHistory(getHistoryFile());
-			consoleReader.setHistory(history);
-		} catch (IOException e) {
-			throw new IllegalStateException("Cannot create jline console reader", e);
-		}
-		return consoleReader;
-	}
-
-	public ConsoleReader getConsoleReader() {
-		return reader;
-	}
-
-	protected abstract String getPrompt();
-
-	/**
-	 * Get the history file for the Console Reader.
-	 * 
-	 * @return File for storing history
-	 */
-	protected abstract File getHistoryFile();
-
-	public final void start(String[] args) {
-		Thread shutdownHookThread = new Thread("CLI Shutdown Hook") {
-			@Override
-			public void run() {
-				performDestroy();
-			}
-		};
-		Runtime.getRuntime().addShutdownHook(shutdownHookThread);
-		int returnCode = run(args);
-		if (logger.isDebugEnabled()) {
-			logger.debug("Exiting with error code {}", returnCode);
-		}
-		System.exit(returnCode);
-	}
-
-	protected abstract int run(String[] args);
-
-	protected void promptLoop() {
-		String line = null;
-		boolean exit = false;
-
-		try {
-			while (!exit && (reader != null && ((line = reader.readLine()) != null))) {
-				if ("".equals(line)) {
-					continue;
-				}
-				if (StringUtils.isNotBlank(line)) {
-					execute(line);
-					exit = CliConstants.EXIT_ACTION.equals(line.trim());
-				}
-			}
-		} catch (IOException e) {
-			throw new IllegalStateException("Error in reading line", e);
-		}
-	}
-
-	private int execute(String line) {
-		try {
-			if (logger.isDebugEnabled()) {
-				logger.debug("Executing command line: \"{}\"", line);
-			}
-			int returnCode = executeCommand(line);
-			if (logger.isDebugEnabled()) {
-				logger.debug("Command line executed \"{}\". Return code: {}", line, returnCode);
-			}
-			return returnCode;
-		} catch (RuntimeException e) {
-			if (logger.isErrorEnabled()) {
-				logger.error("Error executing command line: " + line, e);
-			}
-			return 1;
-		}
-	}
-
-	protected abstract int executeCommand(String line);
-
-	private void performDestroy() {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Shutting down application... Invoking destroy methods");
-		}
-		if (history != null) {
-			try {
-				history.flush();
-			} catch (IOException e) {
-				if (logger.isErrorEnabled()) {
-					logger.error("Error flushing history.", e);
-				}
-			}
-		}
-		destroy();
-	}
-
-	/**
-	 * May override to perform action before destroying
-	 */
-	protected void destroy() {
-	};
-
-	public String getInput(String prompt) {
-		return getInput(prompt, null);
-	}
-
-	public String getInput(String prompt, Character mask) {
-		String line = null;
-		try {
-			reader.setPrompt(prompt + ": ");
-			while ((line = reader.readLine(mask)) != null) {
-				if ("".equals(line)) {
-					continue;
-				}
-				return line;
-			}
-		} catch (IOException e) {
-			throw new IllegalStateException("Error in reading line", e);
-		} finally {
-			reader.setPrompt(CliConstants.STRATOS_SHELL_PROMPT);
-		}
-		return line;
-	}
-	
-	/**
-	 * @return {@code true if user confirmed}
-	 */
-	public boolean getConfirmation(String prompt) {
-		prompt = prompt + " [yes/no]";
-
-		String input = "";
-		int tries = 0;
-		do {
-			tries++;
-			input = getInput(prompt);
-		} while (!"y".equals(input) && !"yes".equals(input) && !"n".equals(input) && !"no".equals(input) && tries < 3);
-
-		return "y".equals(input) || "yes".equals(input);
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineService.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineService.java
deleted file mode 100644
index 2aa9f2b..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineService.java
+++ /dev/null
@@ -1,556 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli;
-
-import java.rmi.RemoteException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.client.Options;
-import org.apache.axis2.client.ServiceClient;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.context.ConfigurationContextFactory;
-import org.apache.axis2.description.TransportOutDescription;
-import org.apache.axis2.transport.http.HttpTransportProperties;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.stratos.adc.mgt.cli.utils.CommandLineUtils;
-import org.apache.stratos.adc.mgt.cli.utils.RowMapper;
-import org.apache.stratos.adc.mgt.dto.xsd.Cartridge;
-import org.apache.stratos.adc.mgt.dto.xsd.PolicyDefinition;
-import org.apache.stratos.adc.mgt.dto.xsd.SubscriptionInfo;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceADCExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceAlreadySubscribedExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceDomainMappingExistsExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceDuplicateCartridgeAliasExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceInvalidCartridgeAliasExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceInvalidRepositoryExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceNotSubscribedExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServicePolicyExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceRepositoryRequiredExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceRepositoryTransportExceptionException;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceStub;
-import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceUnregisteredCartridgeExceptionException;
-
-import com.google.gson.Gson;
-
-public class CommandLineService {
-
-	private static final Logger logger = LoggerFactory.getLogger(CommandLineService.class);
-
-	private ApplicationManagementServiceStub stub;
-
-	private CommandLineService() {
-	}
-
-	private static class SingletonHolder {
-		private final static CommandLineService INSTANCE = new CommandLineService();
-	}
-
-	public static CommandLineService getInstance() {
-		return SingletonHolder.INSTANCE;
-	}
-	
-	private void initializeApplicationManagementStub(String serverURL, String username, String password) throws AxisFault {
-		HttpTransportProperties.Authenticator authenticator = new HttpTransportProperties.Authenticator();
-        authenticator.setUsername(username);
-        authenticator.setPassword(password);
-        authenticator.setPreemptiveAuthentication(true);
-		
-        ApplicationManagementServiceStub stub;
-        ConfigurationContext configurationContext = null;
-        try {
-            configurationContext = ConfigurationContextFactory.createDefaultConfigurationContext();
-        } catch (Exception e) {
-            String msg = "Backend error occurred. Please contact the service admins!";
-            throw new AxisFault(msg, e);
-        }
-        HashMap<String, TransportOutDescription> transportsOut = configurationContext
-                .getAxisConfiguration().getTransportsOut();
-        for (TransportOutDescription transportOutDescription : transportsOut.values()) {
-            transportOutDescription.getSender().init(configurationContext, transportOutDescription);
-        }
-        stub = new ApplicationManagementServiceStub(configurationContext, serverURL + "/services/ApplicationManagementService");
-        ServiceClient client = stub._getServiceClient();
-        Options option = client.getOptions();
-        option.setManageSession(true);
-        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, authenticator);
-        option.setTimeOutInMilliSeconds(300000);
-        this.stub = stub;
-    }
-
-	public boolean login(String serverURL, String username, String password, boolean validateLogin) throws CommandException {
-		try {
-			// Following code will avoid validating certificate
-			SSLContext sc;
-			// Get SSL context
-			sc = SSLContext.getInstance("SSL");
-			// Create empty HostnameVerifier
-			HostnameVerifier hv = new HostnameVerifier() {
-				public boolean verify(String urlHostName, SSLSession session) {
-					return true;
-				}
-			};
-			// Create a trust manager that does not validate certificate
-			// chains
-			TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
-				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
-					return null;
-				}
-
-				public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
-				}
-
-				public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
-				}
-			} };
-			sc.init(null, trustAllCerts, new java.security.SecureRandom());
-			SSLContext.setDefault(sc);
-			HttpsURLConnection.setDefaultHostnameVerifier(hv);
-		} catch (Exception e) {
-			throw new RuntimeException("Error while authentication process!", e);
-		}
-
-		// Initialize Service Stub
-		try {
-			initializeApplicationManagementStub(serverURL, username, password);
-		} catch (AxisFault e) {
-			System.out.println("Error connecting to the back-end");
-			throw new CommandException(e);
-		}
-		
-		try {
-			if (validateLogin) {
-				String tenantDomain = stub.getTenantDomain();
-				if (logger.isDebugEnabled()) {
-					logger.debug("Tenant Domain {}", tenantDomain);
-				}
-				return (tenantDomain != null);
-			} else {
-				// Just return true as we don't need to validate
-				return true;
-			}
-		} catch (RemoteException e) {
-			System.out.println("Authentication failed!");
-			throw new CommandException(e);
-		}
-	}
-
-	public void listSubscribedCartridges(final boolean full) throws CommandException {
-		try {
-			Cartridge[] cartridges = stub.getSubscribedCartridges();
-
-			if (cartridges == null) {
-				if (logger.isDebugEnabled()) {
-					logger.debug("No subscribed cartridges found");
-				}
-				System.out.println("There are no subscribed cartridges");
-				return;
-			}
-
-			RowMapper<Cartridge> cartridgeMapper = new RowMapper<Cartridge>() {
-
-				@Override
-				public String[] getData(Cartridge cartridge) {
-					String[] data = full ? new String[9] : new String[7];
-					data[0] = cartridge.getCartridgeType();
-					data[1] = cartridge.getDisplayName();
-					data[2] = cartridge.getVersion();
-					data[3] = cartridge.getMultiTenant() ? "Multi-Tenant" : "Single-Tenant";
-					data[4] = cartridge.getCartridgeAlias();
-					data[5] = cartridge.getStatus();
-					data[6] = cartridge.getMultiTenant() ? "N/A" : String.valueOf(cartridge.getActiveInstances());
-					if (full) {
-						data[7] = getAccessURLs(cartridge);
-						data[8] = cartridge.getRepoURL() != null ? cartridge.getRepoURL() : "";
-					}
-					return data;
-				}
-			};
-			
-			List<String> headers = new ArrayList<String>();
-			headers.add("Type");
-			headers.add("Name");
-			headers.add("Version");
-			headers.add("Tenancy Model");
-			headers.add("Alias");
-			headers.add("Status");
-			headers.add("Running Instances");
-			if (full) {
-				headers.add("Access URL(s)");
-				headers.add("Repo URL");
-			}
-
-			System.out.println("Subscribed Cartridges:");
-			CommandLineUtils.printTable(cartridges, cartridgeMapper, headers.toArray(new String[headers.size()]));
-
-			System.out.println();
-
-		} catch (ApplicationManagementServiceADCExceptionException e) {
-			handleException("cannot.list.subscribed.cartridges", e);
-		} catch (RemoteException e) {
-			handleException(e);
-		}
-	}
-
-	public void listAvailableCartridges() throws CommandException {
-		try {
-			Cartridge[] multiTenantCatridges = stub.getAvailableCartridges(true);
-
-			if (multiTenantCatridges == null) {
-				if (logger.isDebugEnabled()) {
-					logger.debug("No multi-tenant cartridges available");
-				}
-				System.out.println("There are no multi-tenant cartridges available");
-			}
-
-			RowMapper<Cartridge> cartridgeMapper = new RowMapper<Cartridge>() {
-
-				@Override
-				public String[] getData(Cartridge cartridge) {
-					String[] data = new String[3];
-					data[0] = cartridge.getCartridgeType();
-					data[1] = cartridge.getDisplayName();
-					data[2] = cartridge.getVersion();
-					return data;
-				}
-			};
-
-			System.out.println("Available Multi-Tenant Cartridges:");
-			CommandLineUtils.printTable(multiTenantCatridges, cartridgeMapper, "Type", "Name", "Version");
-			System.out.println();
-			
-			Cartridge[] singleTenantCatridges = stub.getAvailableCartridges(false);
-
-			if (multiTenantCatridges == null) {
-				if (logger.isDebugEnabled()) {
-					logger.debug("No single-tenant cartridges available");
-				}
-				System.out.println("There are no single-tenant cartridges available");
-			}
-			
-			System.out.println("Available Single-Tenant Cartridges:");
-			CommandLineUtils.printTable(singleTenantCatridges, cartridgeMapper, "Type", "Name", "Version");
-			System.out.println();
-		} catch (ApplicationManagementServiceADCExceptionException e) {
-			handleException("cannot.list.available.cartridges", e);
-		} catch (RemoteException e) {
-			handleException(e);
-		}
-	}
-	
-	public void listAvailablePolicies() throws CommandException {
-		try {
-			PolicyDefinition[] policies = stub.getPolicyDefinitions();
-
-			if (policies == null) {
-				if (logger.isDebugEnabled()) {
-					logger.debug("No policies available");
-				}
-				System.out.println("There are no policies available");
-			}
-
-			RowMapper<PolicyDefinition> policyMapper = new RowMapper<PolicyDefinition>() {
-
-				@Override
-				public String[] getData(PolicyDefinition policyDefinition) {
-					String[] data = new String[3];
-					data[0] = policyDefinition.getName();
-					data[1] = policyDefinition.getDescription();
-					data[2] = policyDefinition.getDefaultPolicy() ? "Yes" : "No";
-					return data;
-				}
-			};
-
-			CommandLineUtils.printTable(policies, policyMapper, "Policy Name", "Description", "Default");
-			System.out.println();
-		} catch (RemoteException e) {
-			handleException(e);
-		}
-	}
-
-	public void info(String alias) throws CommandException {
-		try {
-            Cartridge cartridge = null;
-            try {
-                cartridge = stub.getCartridgeInfo(alias);
-            } catch (ApplicationManagementServiceADCExceptionException e) {
-            	handleException(e);
-                return;
-            } catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
-            	handleException("notsubscribed.error", e, alias);
-			}
-			if (logger.isDebugEnabled()) {
-				logger.debug("Cartridge Info: {}", new Gson().toJson(cartridge));
-			}
-			final String FORMAT = "%-20s: %s%n";
-			System.out.println();
-			System.out.println("Cartridge Information");
-			System.out.println("---------------------");
-			System.out.format(FORMAT, "Cartridge", cartridge.getCartridgeType());
-			System.out.format(FORMAT, "Name", cartridge.getDisplayName());
-			System.out.format(FORMAT, "Description", cartridge.getDescription());
-			System.out.format(FORMAT, "Version", cartridge.getVersion());
-			System.out.format(FORMAT, "Tenancy Model", cartridge.getMultiTenant() ? "Multi-Tenant" : "Single-Tenant");
-			System.out.format(FORMAT, "Alias", cartridge.getCartridgeAlias());
-			if (StringUtils.isNotBlank(cartridge.getPolicyDescription())) {
-				System.out.format(FORMAT, "Policy", cartridge.getPolicyDescription());
-			}
-			System.out.format(FORMAT, "Access URL(s)", getAccessURLs(cartridge));
-			if (StringUtils.isNotBlank(cartridge.getIp())) {
-				System.out.format(FORMAT, "Host", cartridge.getIp());
-			}
-			if (StringUtils.isNotBlank(cartridge.getDbUserName())) {
-				System.out.format(FORMAT, "Database Username", cartridge.getDbUserName());
-			}
-			if (StringUtils.isNotBlank(cartridge.getPassword())) {
-				System.out.format(FORMAT, "Password", cartridge.getPassword());
-			}
-			if (StringUtils.isNotBlank(cartridge.getRepoURL())) {
-				System.out.format(FORMAT, "Repository URL", cartridge.getRepoURL());
-			}
-			System.out.format(FORMAT, "Status", cartridge.getStatus());
-			System.out.format(FORMAT, "Running Instances",
-					cartridge.getMultiTenant() ? "N/A" : String.valueOf(cartridge.getActiveInstances()));
-			System.out.println();
-
-        } catch (RemoteException e) {
-        	handleException(e);
-        }
-	}
-
-	public void unsubscribe(String alias) throws CommandException {
-		try {
-			stub.unsubscribe(alias);
-			System.out.println("You have successfully unsubscribed " + alias);
-        } catch (ApplicationManagementServiceADCExceptionException e) {
-        	handleException("cannot.unsubscribe", e);
-        } catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
-			handleException("notsubscribed.error", e, alias);
-        } catch (RemoteException e) {
-        	handleException(e);
-        }
-	}
-
-	public void sync(String alias) throws CommandException {
-		try {
-			System.out.format("Synchronizing repository for alias: %s%n", alias);
-			stub.synchronizeRepository(alias);
-		} catch (ApplicationManagementServiceADCExceptionException e) {
-			handleException("cannot.syncrepo", e);
-		} catch (RemoteException e) {
-			handleException(e);
-		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
-			handleException("notsubscribed.error", e, alias);
-		}
-	}
-
-	public String addDomainMapping(String domain, String alias) throws CommandException {
-		try {
-			return stub.addDomainMapping(domain, alias);
-		} catch (ApplicationManagementServiceADCExceptionException e) {
-			handleException("cannot.mapdomain", e);
-		} catch (RemoteException e) {
-			handleException(e);
-		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
-			handleException("notsubscribed.error", e, alias);
-		} catch (ApplicationManagementServiceDomainMappingExistsExceptionException e) {
-			handleException("domainmapping.exists.error", e, domain, alias);
-		}
-		return null;
-	}
-
-	public void removeDomainMapping(String alias) throws CommandException {
-		try {
-			stub.removeDomainMapping(alias);
-			System.out.format("Domain mapping removed for alias: %s.%n", alias);
-		} catch (ApplicationManagementServiceADCExceptionException e) {
-			handleException("cannot.removedomain", e);
-		} catch (RemoteException e) {
-			handleException(e);
-		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
-			handleException("notsubscribed.error", e, alias);
-		}
-	}
-
-	public void subscribe(String cartridgeType, String alias, String policy, String externalRepoURL,
-			boolean privateRepo, String username, String password, String dataCartridgeType, String dataCartridgeAlias)
-			throws CommandException {
-		
-		SubscriptionInfo subcriptionConnectInfo = null;
-		if (StringUtils.isNotBlank(dataCartridgeType) && StringUtils.isNotBlank(dataCartridgeAlias)) {
-			System.out.format("Subscribing to data cartridge %s with alias %s.%n", dataCartridgeType,
-					dataCartridgeAlias);
-			try {
-				subcriptionConnectInfo = stub.subscribe(dataCartridgeType, dataCartridgeAlias, null, null, false, null,
-						null, null, null);
-				System.out.format("You have successfully subscribed to %s cartridge with alias %s.%n",
-						dataCartridgeType, dataCartridgeAlias);
-				System.out.format("%nSubscribing to %s cartridge and connecting with %s data cartridge.%n", alias,
-						dataCartridgeAlias);
-			} catch (RemoteException e) {
-				handleException(e);
-			} catch (ApplicationManagementServiceADCExceptionException e) {
-				handleException("cannot.subscribe", e);
-			} catch (ApplicationManagementServiceRepositoryRequiredExceptionException e) {
-				handleException("repository.required", e);
-			} catch (ApplicationManagementServiceUnregisteredCartridgeExceptionException e) {
-				handleException("cartridge.notregistered", e, dataCartridgeType);
-			} catch (ApplicationManagementServiceInvalidCartridgeAliasExceptionException e) {
-				handleException("cartridge.invalid.alias", e);
-			} catch (ApplicationManagementServiceAlreadySubscribedExceptionException e) {
-				handleException("cartridge.already.subscribed", e, e.getFaultMessage().getAlreadySubscribedException()
-						.getCartridgeType());
-			} catch (ApplicationManagementServiceDuplicateCartridgeAliasExceptionException e) {
-				handleException("cartridge.alias.duplicate", e, dataCartridgeAlias);
-			} catch (ApplicationManagementServicePolicyExceptionException e) {
-				handleException("policy.error", e);
-			} catch (ApplicationManagementServiceRepositoryTransportExceptionException e) {
-				handleException("repository.transport.error", e, externalRepoURL);
-			} catch (ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException e) {
-				handleException("repository.credentials.required", e, externalRepoURL);
-			} catch (ApplicationManagementServiceInvalidRepositoryExceptionException e) {
-				handleException("repository.invalid.error", e, externalRepoURL);
-			}
-		}
-		
-		
-		try {
-			SubscriptionInfo subcriptionInfo = stub.subscribe(cartridgeType, alias, policy, externalRepoURL,
-					privateRepo, username, password, dataCartridgeType, dataCartridgeAlias);
-
-			System.out
-					.format("You have successfully subscribed to %s cartridge with alias %s.%n", cartridgeType, alias);
-
-			String repoURL = null;
-			String hostnames = null;
-			String hostnamesLabel = null;
-			if (subcriptionInfo != null) {
-				repoURL = subcriptionInfo.getRepositoryURL();
-				hostnames = subcriptionInfo.getHostname();
-				hostnamesLabel = "host name";
-
-				if (repoURL != null) {
-					System.out.println("GIT Repository URL: " + repoURL);
-				}
-
-				Cartridge cart = stub.getCartridgeInfo(alias);
-				System.out.format("Your application is being published here. %s%n", getAccessURLs(cart));
-			}
-			if (subcriptionConnectInfo != null) {
-				hostnames += ", " + subcriptionConnectInfo.getHostname();
-				hostnamesLabel = "host names";
-
-				Cartridge cart = stub.getCartridgeInfo(alias);
-				System.out.format("Your data application is being published here. %s%n", getAccessURLs(cart));
-			}
-			if (externalRepoURL != null) {
-				String takeTimeMsg = "(this might take few minutes... depending on repo size)\n";
-				System.out.println(takeTimeMsg);
-			}
-
-			System.out.format("Please map the %s \"%s\" to ELB IP%n", hostnamesLabel, hostnames);
-		} catch (RemoteException e) {
-			handleException(e);
-		} catch (ApplicationManagementServiceADCExceptionException e) {
-			handleException("cannot.subscribe", e);
-		} catch (ApplicationManagementServiceRepositoryRequiredExceptionException e) {
-			handleException("repository.required", e);
-		} catch (ApplicationManagementServiceUnregisteredCartridgeExceptionException e) {
-			handleException("cartridge.notregistered", e, cartridgeType);
-		} catch (ApplicationManagementServiceInvalidCartridgeAliasExceptionException e) {
-			handleException("cartridge.invalid.alias", e);
-		} catch (ApplicationManagementServiceAlreadySubscribedExceptionException e) {
-			handleException("cartridge.already.subscribed", e, e.getFaultMessage().getAlreadySubscribedException()
-					.getCartridgeType());
-		} catch (ApplicationManagementServiceDuplicateCartridgeAliasExceptionException e) {
-			handleException("cartridge.alias.duplicate", e, alias);
-		} catch (ApplicationManagementServicePolicyExceptionException e) {
-			handleException("policy.error", e);
-		} catch (ApplicationManagementServiceRepositoryTransportExceptionException e) {
-			handleException("repository.transport.error", e, externalRepoURL);
-		} catch (ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException e) {
-			handleException("repository.credentials.required", e, externalRepoURL);
-		} catch (ApplicationManagementServiceInvalidRepositoryExceptionException e) {
-			handleException("repository.invalid.error", e, externalRepoURL);
-		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
-			handleException("notsubscribed.error", e, alias);
-		}
-	}
-
-	private String getAccessURLs(Cartridge cartridge) {
-		String[] accessURLs = cartridge.getAccessURLs();
-		StringBuilder urlBuilder = new StringBuilder();
-		if (accessURLs != null) {
-			for (int i = 0; i < accessURLs.length; i++) {
-				String url = accessURLs[i];
-				if (url != null) {
-					if (i > 0) {
-						urlBuilder.append(", ");
-					}
-					urlBuilder.append(url);
-				}
-			}
-		}
-		return urlBuilder.toString();
-	}
-
-	private void handleException(Exception e) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Displaying message from Exception {}\n{}", e.getClass(), e.getMessage());
-		}
-		// TODO: Fix handling error message.
-		// Sometimes the Axis2 stub throws only the RemoteException (an
-		// AxisFault)
-		// So, other exceptions won't come here.
-		String message = e.getMessage();
-		if (message == null || (message != null && message.contains("Exception"))) {
-			message = "Error executing command!";
-		}
-		if (logger.isErrorEnabled()) {
-			logger.error(message);
-		}
-		System.out.println(message);
-		throw new CommandException(message, e);
-	}
-    
-    private void handleException(String key, Exception e, Object... args) throws CommandException {
-    	if (logger.isDebugEnabled()) {
-    		logger.debug("Displaying message for {}. Exception thrown is {}", key, e.getClass());
-    	}
-    	String message = CommandLineUtils.getMessage(key, args);
-        if (logger.isErrorEnabled()) {
-        	logger.error(message);
-        }
-        System.out.println(message);
-        throw new CommandException(message, e);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/StratosApplication.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/StratosApplication.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/StratosApplication.java
deleted file mode 100644
index 74caf39..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/StratosApplication.java
+++ /dev/null
@@ -1,504 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli;
-
-import static org.apache.stratos.adc.mgt.cli.utils.CliConstants.STRATOS_DIR;
-import static org.apache.stratos.adc.mgt.cli.utils.CliConstants.STRATOS_HISTORY_DIR;
-
-import java.io.File;
-import java.io.PrintWriter;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.stratos.adc.mgt.cli.completer.CommandCompleter;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.GnuParser;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.text.StrTokenizer;
-import org.apache.commons.validator.routines.UrlValidator;
-import org.apache.log4j.Level;
-import org.apache.log4j.LogManager;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.commands.AddDomainMappingCommand;
-import org.apache.stratos.adc.mgt.cli.commands.CartridgesCommand;
-import org.apache.stratos.adc.mgt.cli.commands.ExitCommand;
-import org.apache.stratos.adc.mgt.cli.commands.HelpCommand;
-import org.apache.stratos.adc.mgt.cli.commands.InfoCommand;
-import org.apache.stratos.adc.mgt.cli.commands.ListCommand;
-import org.apache.stratos.adc.mgt.cli.commands.PoliciesCommand;
-import org.apache.stratos.adc.mgt.cli.commands.RemoveDomainMappingCommand;
-import org.apache.stratos.adc.mgt.cli.commands.SubscribeCommand;
-import org.apache.stratos.adc.mgt.cli.commands.SyncCommand;
-import org.apache.stratos.adc.mgt.cli.commands.UnsubscribeCommand;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class StratosApplication extends CommandLineApplication<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(StratosApplication.class);
-
-	private final Map<String, Command<StratosCommandContext>> commands;
-	private final StratosCommandContext context;
-
-	private final Options options;
-
-	public StratosApplication() {
-		commands = new HashMap<String, Command<StratosCommandContext>>();
-		context = new StratosCommandContext(this);
-
-		options = constructOptions();
-
-		createCommands();
-		createAutocomplete();
-	}
-
-	/**
-	 * Construct Options.
-	 * 
-	 * @return Options expected from command-line.
-	 */
-	private Options constructOptions() {
-		final Options options = new Options();
-		Option usernameOption = new Option(CliConstants.USERNAME_OPTION, CliConstants.USERNAME_LONG_OPTION, true,
-				"Username");
-		usernameOption.setArgName("username");
-		options.addOption(usernameOption);
-
-		Option passwordOption = new Option(CliConstants.PASSWORD_OPTION, CliConstants.PASSWORD_LONG_OPTION, true,
-				"Password");
-		passwordOption.setArgName("password");
-		passwordOption.setOptionalArg(true);
-		options.addOption(passwordOption);
-		options.addOption(CliConstants.HELP_OPTION, CliConstants.HELP_LONG_OPTION, false, "Display this help");
-		options.addOption(CliConstants.TRACE_OPTION, false, "Enable trace logging");
-		options.addOption(CliConstants.DEBUG_OPTION, false, "Enable debug logging");
-		return options;
-	}
-
-	private void createCommands() {
-		Command<StratosCommandContext> command = new HelpCommand();
-		commands.put(command.getName(), command);
-
-		command = new ExitCommand();
-		commands.put(command.getName(), command);
-
-		command = new SubscribeCommand();
-		commands.put(command.getName(), command);
-
-		command = new UnsubscribeCommand();
-		commands.put(command.getName(), command);
-		
-		command = new CartridgesCommand();
-		commands.put(command.getName(), command);
-		
-		command = new ListCommand();
-		commands.put(command.getName(), command);
-		
-		command = new InfoCommand();
-		commands.put(command.getName(), command);
-		
-		command = new AddDomainMappingCommand();
-		commands.put(command.getName(), command);
-		
-		command = new RemoveDomainMappingCommand();
-		commands.put(command.getName(), command);
-		
-		command = new SyncCommand();
-		commands.put(command.getName(), command);
-		
-		command = new PoliciesCommand();
-		commands.put(command.getName(), command);
-
-		if (logger.isDebugEnabled()) {
-			logger.debug("Created {} commands for the application. {}", commands.size(), commands.keySet());
-		}
-	}
-
-	private void createAutocomplete() {
-		reader.addCompleter(new CommandCompleter(commands));
-	}
-
-	@Override
-	protected String getPrompt() {
-		return CliConstants.STRATOS_SHELL_PROMPT;
-	}
-
-	@Override
-	protected File getHistoryFile() {
-		File stratosFile = new File(System.getProperty("user.home"), STRATOS_DIR);
-		File historyFile = new File(stratosFile, STRATOS_HISTORY_DIR);
-		return historyFile;
-	}
-
-	@Override
-	public int run(String[] args) {
-		boolean loaded = loadRequiredProperties();
-		if (!loaded) {
-			return CliConstants.ERROR_CODE;
-		}
-
-		// To get the command action from arguments
-		String[] remainingArgs = null;
-
-		// Command action
-		String action = null;
-
-		String usernameInput = null;
-		String passwordInput = null;
-
-		if (args != null && args.length > 0) {
-			// Arguments are passed.
-			if (logger.isDebugEnabled()) {
-				logger.debug("Arguments:");
-				for (String arg : args) {
-					logger.debug(arg);
-				}
-			}
-
-			final CommandLineParser parser = new GnuParser();
-			CommandLine commandLine;
-			try {
-				// Must add all options. Otherwise actions cannot be performed directly by command line.
-				Options allCommandOptions = new Options();
-				for (Command<StratosCommandContext> command : commands.values()) {
-					Options commandOptions = command.getOptions();
-					if (commandOptions != null) {
-						Collection<?> allOptions = commandOptions.getOptions();
-						for (Object o : allOptions) {
-							allCommandOptions.addOption((Option) o);
-						}
-					}
-				}
-				// Add options in this application
-				Collection<?> allOptions = options.getOptions();
-				for (Object o : allOptions) {
-					allCommandOptions.addOption((Option) o);
-				}
-				
-				commandLine = parser.parse(allCommandOptions, args);
-				remainingArgs = commandLine.getArgs();
-				if (remainingArgs != null && remainingArgs.length > 0) {
-					// Get command action
-					action = remainingArgs[0];
-				}
-
-				// Set logger levels from this point onwards
-				setLoggerLevel(commandLine.hasOption(CliConstants.TRACE_OPTION),
-						commandLine.hasOption(CliConstants.DEBUG_OPTION));
-
-				if (commandLine.hasOption(CliConstants.USERNAME_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("Username option is passed");
-					}
-					usernameInput = commandLine.getOptionValue(CliConstants.USERNAME_OPTION);
-				}
-				if (commandLine.hasOption(CliConstants.PASSWORD_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("Password option is passed");
-					}
-					passwordInput = commandLine.getOptionValue(CliConstants.PASSWORD_OPTION);
-				}
-				if (commandLine.hasOption(CliConstants.HELP_ACTION)) {
-					printHelp();
-					return CliConstants.SUCCESSFUL_CODE;
-				}
-			} catch (ParseException e) {
-				if (logger.isErrorEnabled()) {
-					logger.error("Error parsing arguments when trying to login", e);
-				}
-				System.out.println(e.getMessage());
-				return CliConstants.BAD_ARGS_CODE; 
-			}
-
-		}
-
-		if (StringUtils.isNotBlank(action)) {
-			// User is executing an action
-			if (logger.isDebugEnabled()) {
-				logger.debug("Action: {}", action);
-			}
-			Command<StratosCommandContext> command = commands.get(action);
-			if (command == null) {
-				printHelp();
-				return CliConstants.BAD_ARGS_CODE;
-			}
-
-			boolean loginRequired = !CliConstants.HELP_ACTION.equals(action);
-			
-			if (loginRequired && logger.isDebugEnabled()) {
-				logger.debug("Trying to login...");
-			}
-
-			if (loginRequired && !login(usernameInput, passwordInput, false)) {
-				if (logger.isDebugEnabled()) {
-					logger.debug("Exiting from CLI. Login required but login might have failed: {}", action);
-				}
-				// Exit
-				return CliConstants.ERROR_CODE;
-			}
-
-			try {
-				String[] actionArgs = Arrays.copyOfRange(remainingArgs, 1, remainingArgs.length);
-				if (logger.isDebugEnabled()) {
-					logger.debug("Executing Action: {} {}", action, Arrays.asList(actionArgs));
-				}
-				int returnCode = command.execute(context, actionArgs);
-				if (logger.isDebugEnabled()) {
-					logger.debug("Exiting with error code {} after executing action {}", returnCode, action);
-				}
-				System.exit(returnCode);
-			} catch (CommandException e) {
-				if (logger.isErrorEnabled()) {
-					logger.error("Error executing command: " + action, e);
-				}
-				return CliConstants.ERROR_CODE;
-			}
-		} else {
-			if (login(usernameInput, passwordInput, true)) {
-				System.out.println("Successfully Authenticated.");
-			} else {
-				// Exit
-				return CliConstants.ERROR_CODE;
-			}
-
-			promptLoop();
-		}
-		return CliConstants.SUCCESSFUL_CODE;
-	}
-
-	private boolean login(String usernameInput, String passwordInput, boolean validateLogin) {
-		// TODO Previous CLI version uses a keystore. Here we are not using it.
-		// Check whether user has passed username and password
-		if (StringUtils.isBlank(usernameInput) && StringUtils.isBlank(passwordInput)) {
-			// User has not passed any arguments.
-			// Try authenticating from the values found
-			usernameInput = context.getString(CliConstants.STRATOS_USERNAME_ENV_PROPERTY);
-			passwordInput = context.getString(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY);
-
-			if (logger.isDebugEnabled()) {
-				if (StringUtils.isNotBlank(usernameInput) && StringUtils.isNotBlank(passwordInput)) {
-					logger.debug("Found authentication details for {} from context", usernameInput);
-				}
-			}
-
-		}
-		// Get user input if not passed as args
-		if (StringUtils.isBlank(usernameInput)) {
-			usernameInput = getInput("Username");
-		} else {
-			System.out.format("Username: %s%n", usernameInput);
-		}
-		if (StringUtils.isBlank(passwordInput)) {
-			passwordInput = getInput("Password", '*');
-		}
-
-		boolean success = false;
-		String stratosURL = null;
-		stratosURL = context.getString(CliConstants.STRATOS_URL_ENV_PROPERTY);
-
-		try {
-			success = CommandLineService.getInstance().login(stratosURL, usernameInput, passwordInput, validateLogin);
-		} catch (Exception e) {
-			if (logger.isErrorEnabled()) {
-				logger.error("Error when trying to login", e);
-			}
-		}
-		if (success) {
-			if (logger.isDebugEnabled()) {
-				logger.debug("Successfully Authenticated.");
-			}
-		} else {
-			if (logger.isDebugEnabled()) {
-				logger.debug("Authentication failed.");
-			}
-		}
-		return success;
-	}
-
-	@Override
-	protected int executeCommand(String line) {
-		String[] tokens = new StrTokenizer(line).getTokenArray();
-		String action = tokens[0];
-		String[] actionArgs = Arrays.copyOfRange(tokens, 1, tokens.length);
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing command action: {}, Tokens: {}", action, tokens.length);
-		}
-		Command<StratosCommandContext> command = commands.get(action);
-		if (command == null) {
-			System.out.println(action + ": command not found.");
-			return CliConstants.BAD_ARGS_CODE;
-		}
-		try {
-			return command.execute(context, actionArgs);
-		} catch (CommandException e) {
-			if (logger.isErrorEnabled()) {
-				logger.error("Error executing command: " + action, e);
-			}
-			return CliConstants.ERROR_CODE;
-		}
-	}
-
-	/**
-	 * @return {@code true} if required properties are loaded
-	 */
-	private boolean loadRequiredProperties() {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Loading properties...");
-		}
-		// Load properties
-		String stratosURL = null;
-		String username = null;
-		String password = null;
-
-		stratosURL = System.getenv(CliConstants.STRATOS_URL_ENV_PROPERTY);
-		username = System.getenv(CliConstants.STRATOS_USERNAME_ENV_PROPERTY);
-		password = System.getenv(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY);
-
-		if (StringUtils.isBlank(stratosURL)) {
-			if (logger.isDebugEnabled()) {
-				logger.debug("Required configuration not found.");
-			}
-			// Stratos Controller details are not set.
-			System.out.format("Could not find required \"%s\" variable in your environment.%n",
-					CliConstants.STRATOS_URL_ENV_PROPERTY);
-			return false;
-		} else {
-			if (logger.isDebugEnabled()) {
-				logger.debug("Required configuration found. Validating {}", stratosURL);
-			}
-			UrlValidator urlValidator = new UrlValidator(new String[] { "https" });
-			if (!urlValidator.isValid(stratosURL)) {
-				if (logger.isDebugEnabled()) {
-					logger.debug("Stratos Controller URL {} is not valid", stratosURL);
-				}
-				System.out.format(
-						"The \"%s\" variable in your environment is not a valid URL. You have provided \"%s\".%n"
-								+ "Please provide the Stratos Controller URL as follows%nhttps://<host>:<port>%n",
-						CliConstants.STRATOS_URL_ENV_PROPERTY, stratosURL);
-				return false;
-			}
-			if (logger.isDebugEnabled()) {
-				logger.debug("Stratos Controller URL {} is valid.", stratosURL);
-				logger.debug("Adding the values to context.");
-			}
-			context.put(CliConstants.STRATOS_URL_ENV_PROPERTY, stratosURL);
-			context.put(CliConstants.STRATOS_USERNAME_ENV_PROPERTY, username);
-			context.put(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY, password);
-			return true;
-		}
-	}
-	
-	private void setLoggerLevel(boolean trace, boolean debug) {
-		// We are using Log4j. So, get the logger and set log levels.
-		org.apache.log4j.Logger logger = LogManager.getLogger(StratosApplication.class.getPackage().getName());
-		if (logger != null && trace) {
-			logger.setLevel(Level.TRACE);
-			LogManager.getRootLogger().setLevel(Level.TRACE);
-		} else if (logger != null && debug) {
-			logger.setLevel(Level.DEBUG);
-			LogManager.getRootLogger().setLevel(Level.DEBUG);
-		}
-	}
-
-	public void printHelp(final String action) {
-		Command<StratosCommandContext> command = commands.get(action);
-		if (command == null) {
-			System.out.println(action + ": command not found. Help not available.");
-			return;
-		}
-		System.out.println(command.getDescription());
-		Options options = command.getOptions();
-		if (options != null) {
-			if (StringUtils.isNotBlank(command.getArgumentSyntax())) {
-				printHelp(command.getName() + " " + command.getArgumentSyntax(), options);
-			} else {
-				printHelp(command.getName(), options);
-			}
-		} else {
-			// No options. Just print the usage.
-			printUsage(command);
-		}
-	}
-
-	public void printHelp() {
-		printHelp(CliConstants.STRATOS_APPLICATION_NAME, options);
-		System.out.println("\n\nAvailable Commands: ");
-		for (String action : commands.keySet()) {
-			Command<StratosCommandContext> command = commands.get(action);
-			if (command != null) {
-				System.out.format("%-25s %s%n", command.getName(), command.getDescription());
-			}
-		}
-
-		System.out.println("\nFor help on a specific command type:\nhelp [command]");
-	}
-
-	/**
-	 * Print "help" with usage
-	 */
-	private void printHelp(final String commandLineSyntax, final Options options) {
-		final HelpFormatter helpFormatter = new HelpFormatter();
-		helpFormatter.printHelp(commandLineSyntax, options, true);
-	}
-	
-	public void printUsage(final String action) {
-		Command<StratosCommandContext> command = commands.get(action);
-		if (command == null) {
-			return;
-		}
-		printUsage(command);
-	}
-	
-	private void printUsage(Command<StratosCommandContext> command) {
-		Options options = command.getOptions();
-		if (options != null) {
-			if (StringUtils.isNotBlank(command.getArgumentSyntax())) {
-				printUsage(command.getName() + " " + command.getArgumentSyntax(), options);
-			} else {
-				printUsage(command.getName(), options);
-			}
-		} else {
-			System.out.print("usage: ");
-			if (StringUtils.isNotBlank(command.getArgumentSyntax())) {
-				System.out.println(command.getName() + " " + command.getArgumentSyntax());
-			} else {
-				System.out.println(command.getName());
-			}
-		}
-	}
-	
-	/**
-	 * Print "usage"
-	 */
-	private void printUsage(final String commandLineSyntax, final Options options) {
-		final PrintWriter writer = new PrintWriter(System.out);
-		final HelpFormatter usageFormatter = new HelpFormatter();
-		usageFormatter.printUsage(writer, 80, commandLineSyntax, options);
-		writer.flush();
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/StratosCommandContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/StratosCommandContext.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/StratosCommandContext.java
deleted file mode 100644
index e4f7652..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/StratosCommandContext.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli;
-
-public class StratosCommandContext extends CommandContext {
-
-	public StratosCommandContext(StratosApplication application) {
-		super(application);
-	}
-
-	public StratosApplication getStratosApplication() {
-		return (StratosApplication) getApplication();
-	}
-
-}


[07/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/tenant-activity.jsp
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/tenant-activity.jsp b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/tenant-activity.jsp
new file mode 100644
index 0000000..e7db5a7
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity.ui/src/main/resources/web/tenant-activity/tenant-activity.jsp
@@ -0,0 +1,174 @@
+<!--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+-->
+<%@ page import="java.util.List" %>
+<%@ page import="org.wso2.carbon.tenant.activity.ui.clients.TenantActivityServiceClient" %>
+<%@ page import="org.wso2.carbon.tenant.activity.ui.utils.TenantMonitorUtil" %>
+<%@ page import="java.util.Map" %>
+<%@ page import="org.apache.stratos.common.config.CloudServiceConfig" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+
+
+<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@ page import="org.wso2.carbon.CarbonConstants" %>
+<%@ page import="org.wso2.carbon.registry.common.ui.UIException" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
+<%@ page import="java.text.SimpleDateFormat" %>
+<%@ page import="java.util.Calendar" %>
+<%@ page import="java.util.Date" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
+<script type="text/javascript" src="../registry_common/js/registry_validation.js"></script>
+<script type="text/javascript" src="../registry_common/js/registry_common.js"></script>
+<script type="text/javascript" src="../ajax/js/prototype.js"></script>
+<script type="text/javascript" src="js/tenant_config.js"></script>
+
+<carbon:jsi18n
+        resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.JSResources"
+        request="<%=request%>"/>
+
+<fmt:bundle basename="org.wso2.carbon.tenant.activity.ui.i18n.Resources">
+    <carbon:breadcrumb
+            label="govern.view_tenants.menu"
+            resourceBundle="org.wso2.carbon.tenant.activity.ui.i18n.Resources"
+            topPage="true"
+            request="<%=request%>"/>
+
+
+    <div id="middle">
+        <div id="top">
+            <h2><fmt:message key="active.tenants.services"/></h2>
+
+            <form id="findTenantForm" action="find-tenant.jsp" method="post">
+                <table class="normal-nopadding" cellspacing="0">
+                    <tbody>
+                    <tr style="border:0; !important">
+                        <td style="border:0; !important">
+                            <nobr>
+                                &nbsp;&nbsp;&nbsp;
+                                Enter Tenant Domain
+                                <input type="text" name="domain" id="domain" value="">&nbsp;
+                            </nobr>
+                        </td>
+                        <td style="border:0; !important">
+                            <a class="icon-link" href="#" style="background-image: url(images/search.gif);"
+                               onclick="domainSelected();" alt="Search"></a>
+                        </td>
+                    </tr>
+                    </tbody>
+                </table>
+            </form>
+        </div>
+
+        <div id="workArea">
+            <table id="serviceStatTable1" cellpadding="0" cellspacing="0" border="0" style="width:100%"
+                   class="styledLeft">
+                <thead>
+                <tr>
+                    <th style="padding-left:5px;text-align:left;width:40%"><fmt:message key="service.name"/></th>
+                    <th style="padding-left:5px;text-align:left;width:150px"><fmt:message
+                            key="active.tenant.count"/></th>
+                    <th style="padding-left:5px;text-align:left;"><fmt:message key="view.list"/></th>
+                </tr>
+                </thead>
+            </table>
+        </div>
+    </div>
+</fmt:bundle>
+
+<%
+    Map<String, CloudServiceConfig> cloudServicesConfigs = TenantMonitorUtil.getCloudServiceConfigMap();
+%>
+
+
+<script type="text/javascript">
+
+    function getStats() {
+        console.log("In the getStat() function");
+        var serviceArray = new Array();
+
+    <%
+    for(String serviceName : cloudServicesConfigs.keySet()){
+
+    %>
+
+        var serviceObj = new Object();
+        serviceObj.backEndUrl = '<%=cloudServicesConfigs.get(serviceName).getLink()%>';
+        serviceObj.serviceName = '<%=serviceName%>';
+        serviceArray.push(serviceObj);
+
+    <% }
+    %>
+
+        for (var i = 0; i < serviceArray.length; i++) {
+
+            jQuery.ajax({
+                type: 'GET',
+                url: 'get-data-ajaxprocessor.jsp',
+                data: 'backEndUrl=' + serviceArray[i].backEndUrl + '&serviceName=' + serviceArray[i].serviceName,
+                dataType: 'json',
+                async: true,
+                success: function(msg) {
+                    var resp = msg;
+                    var view = 'View';
+                    if (resp.count > 0) {
+                        document.getElementById('serviceStatTable1').innerHTML += '<tr><td><a href="javascript:showTenants(\'' + resp.service + '\');">' + resp.service + '</a></td><td>' + resp.count + '</td><td><a href="javascript:showTenants(\'' + resp.service + '\');">' + view + '</a></td></tr>';
+                    }
+                    else {
+                        document.getElementById('serviceStatTable1').innerHTML += '<tr><td>' + resp.service + '</td><td>' + resp.count + '</td><td>-</td></tr>';
+                    }
+                },
+                error:function () {
+                    CARBON.showErrorDialog('Could not connect to server');
+                    //document.getElementById('serviceStatTable').innerHTML += '<tr><td>' + eresp.servic + '</td><td>' + resp.count + '</td></tr>';
+                    document.getElementById('serviceStatTable').innerHTML += 'Not Available';
+                }
+            });
+
+        }
+    }
+    function showTenants(serviceNameKey) {
+        document.getElementById("serviceName").value = serviceNameKey;
+        document.myform.submit();
+    }
+
+    function domainSelected() {
+        var findDomainForm = document.getElementById('findTenantForm');
+        var domain = document.getElementById("domain").getValue();
+        if(domain.length > 3){
+            findDomainForm.submit();
+        }
+        else{
+          CARBON.showErrorDialog('Enter valid domain name');
+        }
+
+    }
+
+</script>
+
+<body onload="getStats();">
+<div>
+    <table id="serviceStatTable"></table>
+    <form name="myform" method="post" action="show-active-tenants.jsp">
+        <input type='hidden' name='serviceName' id="serviceName"/>
+    </form>
+</div>
+</body>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/pom.xml b/components/org.apache.stratos.tenant.activity/pom.xml
new file mode 100644
index 0000000..64f25b4
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/pom.xml
@@ -0,0 +1,144 @@
+<!--
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.tenant.activity</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - TenantActivity</name>
+
+    <build>
+
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>build-helper-maven-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>add-source</id>
+                        <phase>generate-sources</phase>
+                        <goals>
+                            <goal>add-source</goal>
+                        </goals>
+                        <configuration>
+                            <sources>
+                                <source>target/generated-code/src</source>
+                            </sources>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Private-Package>
+                            org.apache.stratos.tenant.activity.internal.*,
+                            org.apache.stratos.tenant.activity.services.*,
+                        </Private-Package>
+                        <Export-Package>
+                            org.apache.stratos.tenant.activity.api.*,
+                            org.apache.stratos.tenant.activity.util.*,
+                            org.apache.stratos.tenant.activity.beans.*,
+                            org.apache.stratos.tenant.activity.commands.*,
+                        </Export-Package>
+                        <Import-Package>
+                            !org.wso2.carbon.tenant.activity.stub.*,
+                            org.apache.stratos.common.*,
+                            org.wso2.carbon.cluster.mgt.core.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.wso2.version}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+            <version>${axis2.wso2.version}</version>
+        </dependency>
+        <!--dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2-kernel</artifactId>
+            <version>${orbit.version.axis2}</version>
+        </dependency-->
+
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.mgt</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+	    <version>${apache.stratos.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.cluster.mgt.core</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/PaginatedTenantDataBean.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/PaginatedTenantDataBean.java b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/PaginatedTenantDataBean.java
new file mode 100644
index 0000000..ce43b61
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/PaginatedTenantDataBean.java
@@ -0,0 +1,52 @@
+/*
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.tenant.activity.beans;
+
+import org.wso2.carbon.utils.Pageable;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * Bean for paginated tenant information
+ */
+public class PaginatedTenantDataBean implements Pageable, Serializable {
+    private TenantDataBean[] tenantInfoBeans;
+    private int numberOfPages;
+
+    public TenantDataBean[] getTenantInfoBeans() {
+        return tenantInfoBeans;
+    }
+
+    public void setTenantInfoBeans(TenantDataBean[] tenantInfoBeans) {
+        this.tenantInfoBeans = tenantInfoBeans;
+    }
+
+    public int getNumberOfPages() {
+        return numberOfPages;
+    }
+
+    public void setNumberOfPages(int numberOfPages) {
+        this.numberOfPages = numberOfPages;
+    }
+
+    public <T> void set(List<T> items) {
+        this.tenantInfoBeans = items.toArray(new TenantDataBean[items.size()]);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/TenantDataBean.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/TenantDataBean.java b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/TenantDataBean.java
new file mode 100644
index 0000000..e301231
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/beans/TenantDataBean.java
@@ -0,0 +1,97 @@
+package org.apache.stratos.tenant.activity.beans;
+/*
+ *  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+
+
+import java.io.Serializable;
+
+/**
+ * Represents a Tenant
+ */
+@SuppressWarnings("unused")
+public class TenantDataBean implements Serializable {
+
+    /**
+     * The tenant Id
+     */
+    private int id;
+
+    /**
+     * The domain name of the tenant
+     */
+    private String domain;
+
+    /**
+     * The admin user name of the tenant
+     */
+    private String adminName;
+
+    /**
+     * The email address of the tenant
+     */
+    private String email;
+
+    /**
+     * Indicates whether this tenant is active or not
+     */
+    private boolean active;
+
+
+    public String getEmail() {
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getAdminName() {
+        return adminName;
+    }
+
+    public void setAdminName(String adminName) {
+        this.adminName = adminName;
+    }
+
+    public String getDomain() {
+        return domain;
+    }
+
+    public void setDomain(String domain) {
+        this.domain = domain;
+    }
+
+    public boolean isActive() {
+        return active;
+    }
+
+    public void setActive(boolean active) {
+        this.active = active;
+    }
+
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberRequest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberRequest.java b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberRequest.java
new file mode 100644
index 0000000..3cd4cd3
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberRequest.java
@@ -0,0 +1,59 @@
+/*
+ *  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.tenant.activity.commands;
+
+import org.apache.axis2.clustering.ClusteringCommand;
+import org.apache.axis2.clustering.ClusteringMessage;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
+import org.apache.stratos.tenant.activity.beans.TenantDataBean;
+import org.wso2.carbon.user.api.Tenant;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This Cluster message is used to get active tenants in each node then
+ * send response as other cluster command which holds active tenants
+ */
+public class GetActiveTenantsInMemberRequest extends ClusteringMessage {
+    private static final Log log = LogFactory.getLog(GetActiveTenantsInMemberRequest.class);
+    private List<TenantDataBean> tenants = new ArrayList<TenantDataBean>();
+
+    public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
+        try {
+            for (Tenant tenant : TenantAxisUtils.getActiveTenants(configurationContext)) {
+                TenantDataBean tb = new TenantDataBean();
+                tb.setDomain(tenant.getDomain());
+                tenants.add(tb);
+            }
+        } catch (Exception e) {
+            String msg = "Cannot get Active tenants";
+            log.error(msg, e);
+            throw new ClusteringFault(msg, e);
+        }
+    }
+
+    public ClusteringCommand getResponse() {
+        return new GetActiveTenantsInMemberResponse(tenants);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberResponse.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberResponse.java b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberResponse.java
new file mode 100644
index 0000000..b3c19d0
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/commands/GetActiveTenantsInMemberResponse.java
@@ -0,0 +1,54 @@
+/*
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.tenant.activity.commands;
+
+import org.apache.axis2.clustering.ClusteringCommand;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.tenant.activity.beans.TenantDataBean;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * This clustering command is used send active tenants list if we send clustering message
+ * GetActiveTenantsInMemberRequest then as a response we can get GetActiveTenantsInMemberResponse
+ * which holds active tenants list
+ */
+public class GetActiveTenantsInMemberResponse extends ClusteringCommand {
+
+    private List<TenantDataBean> tenants = new ArrayList<TenantDataBean>();
+
+    public GetActiveTenantsInMemberResponse(List<TenantDataBean> tenantList) {
+        tenants = tenantList;
+    }
+
+    public void addTenant(TenantDataBean tenant) {
+        tenants.add(tenant);
+    }
+
+    public List<TenantDataBean> getTenants() {
+        return Collections.unmodifiableList(tenants);
+    }
+
+    @Override
+    public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/internal/TenantActivityServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/internal/TenantActivityServiceComponent.java b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/internal/TenantActivityServiceComponent.java
new file mode 100644
index 0000000..47042b9
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/internal/TenantActivityServiceComponent.java
@@ -0,0 +1,96 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.tenant.activity.internal;
+
+import org.apache.stratos.tenant.activity.util.Util;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.axis2.transport.local.LocalTransportReceiver;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import java.lang.Throwable;
+
+/**
+ * @scr.component name="org.wso2.stratos.tenant.activity" immediate="true"
+ * @scr.reference name="registry.service"
+ * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="1..1"
+ * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
+ * @scr.reference name="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService" cardinality="1..1"
+ * policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
+ * @scr.reference name="config.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
+ * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
+ */
+public class TenantActivityServiceComponent {
+    private static Log log = LogFactory.getLog(TenantActivityServiceComponent.class);
+
+
+    protected void activate(ComponentContext context) {
+        try {
+            Util.registerRetrieverServices(context.getBundleContext());
+            if(log.isDebugEnabled()){
+                log.debug("******* Tenant Activity bundle is activated ******* ");
+            }
+        } catch (Throwable e) {
+            log.error("******* Error in activating Tenant Activity bundle ******* ", e);
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        if (log.isDebugEnabled()) {
+            log.debug("******* Tenant Activity is deactivated ******* ");
+        }
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService ccService) {
+        ConfigurationContext serverCtx = ccService.getServerConfigContext();
+        AxisConfiguration serverConfig = serverCtx.getAxisConfiguration();
+        LocalTransportReceiver.CONFIG_CONTEXT = new ConfigurationContext(serverConfig);
+        LocalTransportReceiver.CONFIG_CONTEXT.setServicePath("services");
+        LocalTransportReceiver.CONFIG_CONTEXT.setContextRoot("local:/");
+
+        Util.setConfigurationContextService(ccService);
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService ccService) {
+        Util.setConfigurationContextService(null);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/services/TenantActivityService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/services/TenantActivityService.java b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/services/TenantActivityService.java
new file mode 100644
index 0000000..2d6e2a7
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/services/TenantActivityService.java
@@ -0,0 +1,83 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.stratos.tenant.activity.services;
+
+import org.apache.stratos.tenant.activity.util.Util;
+import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.apache.stratos.tenant.activity.beans.PaginatedTenantDataBean;
+import org.apache.stratos.tenant.activity.beans.TenantDataBean;
+import org.apache.stratos.tenant.activity.util.TenantActivityUtil;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.utils.DataPaginator;
+
+import java.util.*;
+
+/**
+ * This service use to get active tenants related data.If its single node
+ */
+public class TenantActivityService extends AbstractAdmin {
+    List<String> list = new ArrayList<String>();
+
+    public int getActiveTenantCount() throws Exception {
+        return getAllActiveTenantList().size();
+    }
+
+    /**
+     *
+     * @return Active tenants list on service cluster
+     * @throws Exception  when error in retrieving active tenants list
+     */
+    private List<TenantDataBean> getAllActiveTenantList() throws Exception {
+       // ClusterMgtUtil cm = new ClusterMgtUtil();
+        List<TenantDataBean> list = new ArrayList<TenantDataBean>();
+        //This will add current node active tenants list to tenant list
+        for (Tenant tenant : TenantAxisUtils.getActiveTenants(Util.getConfigurationContextService().getServerConfigContext())) {
+            TenantDataBean tb = new TenantDataBean();
+            tb.setDomain(tenant.getDomain());
+            list.add(tb);
+        }
+        //if there are multiple nodes in clusters get active tenants from there as well
+        for (TenantDataBean tenantDataBean : TenantActivityUtil.getActiveTenantsInCluster()) {
+            if (TenantActivityUtil.indexOfTenantInList(list, tenantDataBean) < 0) {
+                list.add(tenantDataBean);
+            }
+
+        }
+        return list;
+    }
+
+    public PaginatedTenantDataBean retrievePaginatedActiveTenants(int pageNumber) throws Exception {
+        List<TenantDataBean> tenantList = getAllActiveTenantList();
+        // Pagination
+        PaginatedTenantDataBean paginatedTenantInfoBean = new PaginatedTenantDataBean();
+        DataPaginator.doPaging(pageNumber, tenantList, paginatedTenantInfoBean);
+        return paginatedTenantInfoBean;
+    }
+
+    public boolean isActiveTenantOnService(String domainName) throws Exception {
+        boolean state = false;
+        for (TenantDataBean tenant : getAllActiveTenantList()) {
+            if (tenant.getDomain().equalsIgnoreCase(domainName)) {
+                return true;
+            }
+        }
+        return state;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/TenantActivityUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/TenantActivityUtil.java b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/TenantActivityUtil.java
new file mode 100644
index 0000000..195980b
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/TenantActivityUtil.java
@@ -0,0 +1,79 @@
+/*
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.tenant.activity.util;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.ClusteringCommand;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.stratos.tenant.activity.commands.GetActiveTenantsInMemberRequest;
+import org.apache.stratos.tenant.activity.commands.GetActiveTenantsInMemberResponse;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.tenant.activity.beans.TenantDataBean;
+
+import java.util.ArrayList;
+import java.util.List;
+
+
+public class TenantActivityUtil {
+    private static final Log log = LogFactory.getLog(TenantActivityUtil.class);
+
+    public static List<TenantDataBean> getActiveTenantsInCluster() throws AxisFault {
+        List<TenantDataBean> tenants = new ArrayList<TenantDataBean>();
+        try {
+            ClusteringAgent agent = getClusteringAgent();
+            List<ClusteringCommand> list = agent.sendMessage(new GetActiveTenantsInMemberRequest(), true);
+            if (log.isDebugEnabled()) {
+                log.debug("sent cluster command to to get Active tenants on cluster");
+            }
+            for (ClusteringCommand command : list) {
+                if (command instanceof GetActiveTenantsInMemberResponse) {
+                    GetActiveTenantsInMemberResponse response = (GetActiveTenantsInMemberResponse) command;
+                    for (TenantDataBean tenant : response.getTenants()) {
+                        tenants.add(tenant);
+                    }
+                }
+            }
+
+        } catch (AxisFault f) {
+            String msg = "Error in getting active tenant by cluster commands";
+            log.error(msg, f);
+            throw new AxisFault(msg);
+        }
+        return tenants;
+    }
+
+
+    private static ClusteringAgent getClusteringAgent() throws AxisFault {
+
+        AxisConfiguration axisConfig =
+                Util.getConfigurationContextService().getServerConfigContext().getAxisConfiguration();
+        return axisConfig.getClusteringAgent();
+    }
+
+    public static int indexOfTenantInList(List<TenantDataBean> list, TenantDataBean tenant) {
+        for (int i = 0; i < list.size(); i++) {
+            if (tenant.getDomain().equalsIgnoreCase(list.get(i).getDomain())) {
+                return i;
+            }
+        }
+        return -1;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/Util.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/Util.java b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/Util.java
new file mode 100644
index 0000000..18f1bf8
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/src/main/java/org/apache/stratos/tenant/activity/util/Util.java
@@ -0,0 +1,82 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.stratos.tenant.activity.util;
+
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.UserRealm;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * Util methods for usage.
+ */
+public class Util {
+
+    private static final Log log = LogFactory.getLog(Util.class);
+
+    private static RegistryService registryService;
+    private static RealmService realmService;
+    private static ConfigurationContextService configurationContextService;
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        registryService = service;
+    }
+
+    public static void setConfigurationContextService(
+            ConfigurationContextService configurationContextService) {
+        Util.configurationContextService = configurationContextService;
+    }
+
+    public static ConfigurationContextService getConfigurationContextService() {
+        return configurationContextService;
+    }
+
+    public static synchronized void setRealmService(RealmService service) {
+        realmService = service;
+    }
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static UserRealm getUserRealm(int tenantId) throws RegistryException {
+        return registryService.getUserRealm(tenantId);
+    }
+
+    public static UserRegistry getSuperTenantGovernanceSystemRegistry() throws RegistryException {
+        return registryService.getGovernanceSystemRegistry();
+    }
+
+    public static void registerRetrieverServices(BundleContext bundleContext) throws Exception {
+        ConfigurationContextService configCtxSvc = Util.getConfigurationContextService();
+
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/src/main/resources/META-INF/component.xml b/components/org.apache.stratos.tenant.activity/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..ebbd1cc
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/src/main/resources/META-INF/component.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+  ~
+  ~  Licensed under the Apache License, Version 2.0 (the "License");
+  ~  you may not use this file except in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~       http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing, software
+  ~  distributed under the License is distributed on an "AS IS" BASIS,
+  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~  See the License for the specific language governing permissions and
+  ~  limitations under the License.
+  -->
+
+<component xmlns="http://products.wso2.org/carbon">
+    <ManagementPermissions>
+        <ManagementPermission>
+            <DisplayName>Monitor</DisplayName>
+            <ResourceId>/permission/admin/monitor</ResourceId>
+        </ManagementPermission>
+        <ManagementPermission>
+            <DisplayName>Tenant-Activity</DisplayName>
+            <ResourceId>/permission/admin/monitor/tenantActivity</ResourceId>
+        </ManagementPermission>
+        <ManagementPermission>
+            <DisplayName>Protected</DisplayName>
+            <ResourceId>/permission/protected</ResourceId>
+        </ManagementPermission>
+        <ManagementPermission>
+            <DisplayName>Monitor</DisplayName>
+            <ResourceId>/permission/protected/monitor</ResourceId>
+        </ManagementPermission>
+    </ManagementPermissions>
+</component>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.activity/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.activity/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.tenant.activity/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..0288f27
--- /dev/null
+++ b/components/org.apache.stratos.tenant.activity/src/main/resources/META-INF/services.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ !
+ ! Copyright 2006 The Apache Software Foundation.
+ !
+ ! Licensed under the Apache License, Version 2.0 (the "License");
+ ! you may not use this file except in compliance with the License.
+ ! You may obtain a copy of the License at
+ !
+ !      http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing, software
+ ! distributed under the License is distributed on an "AS IS" BASIS,
+ ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ! See the License for the specific language governing permissions and
+ ! limitations under the License.
+ !-->
+<serviceGroup>
+
+    <service name="TenantActivityService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.apache.stratos.tenant.activity.services.TenantActivityService
+        </parameter>
+        <operation name="getActiveTenantCount">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/monitor/tenantActivity</parameter>
+        </operation>
+        <operation name="retrievePaginatedActiveTenants">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/monitor/tenantActivity</parameter>
+        </operation>
+        <operation name="isActiveTenantOnService">
+            <parameter name="superTenantService" locked="true">true</parameter>
+            <parameter name="AuthorizationAction" locked="true">/permission/protected/monitor/tenantActivity</parameter>
+        </operation>
+    </service>
+    <parameter name="adminService" locked="true">true</parameter>
+    <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.dispatcher/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.dispatcher/2.1.0/pom.xml b/components/org.apache.stratos.tenant.dispatcher/2.1.0/pom.xml
deleted file mode 100644
index 43cabb4..0000000
--- a/components/org.apache.stratos.tenant.dispatcher/2.1.0/pom.xml
+++ /dev/null
@@ -1,93 +0,0 @@
-<!--
-  ~ Licensed to the Apache Software Foundation (ASF) under one
-  ~ or more contributor license agreements. See the NOTICE file
-  ~ distributed with this work for additional information
-  ~ regarding copyright ownership. The ASF licenses this file
-  ~ to you under the Apache License, Version 2.0 (the
-  ~ "License"); you may not use this file except in compliance
-  ~ with the License. You may obtain a copy of the License at
-  ~
-  ~ http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing,
-  ~ software distributed under the License is distributed on an
-  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-  ~ KIND, either express or implied. See the License for the
-  ~ specific language governing permissions and limitations
-  ~ under the License.
-  -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.tenant.dispatcher</artifactId>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Tenant Dispatcher</name>
-
-    <build>
-
-        <plugins>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Private-Package>
-                            org.apache.stratos.tenant.dispatcher.*,
-                        </Private-Package>
-                        <Export-Package>
-                            !org.apache.stratos.tenant.dispatcher.internal.*,
-                            org.apache.stratos.tenant.dispatcher.*
-                        </Export-Package>
-                        <Import-Package>
-                            !javax.xml.namespace,
-                            javax.xml.namespace; version=0.0.0,
-                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
-                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
-                            *;resolution:=optional
-                        </Import-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-    <dependencies>
-
-        <dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.utils</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>log4j</groupId>
-            <artifactId>log4j</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>commons-logging</groupId>
-            <artifactId>commons-logging</artifactId>
-        </dependency>
-    </dependencies>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.dispatcher/2.1.0/src/main/java/org/apache/stratos/tenant/dispatcher/MultitenantDispatcher.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.dispatcher/2.1.0/src/main/java/org/apache/stratos/tenant/dispatcher/MultitenantDispatcher.java b/components/org.apache.stratos.tenant.dispatcher/2.1.0/src/main/java/org/apache/stratos/tenant/dispatcher/MultitenantDispatcher.java
deleted file mode 100644
index beed246..0000000
--- a/components/org.apache.stratos.tenant.dispatcher/2.1.0/src/main/java/org/apache/stratos/tenant/dispatcher/MultitenantDispatcher.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.tenant.dispatcher;
-
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.context.MessageContext;
-import org.apache.axis2.description.AxisOperation;
-import org.apache.axis2.description.AxisService;
-import org.apache.axis2.description.HandlerDescription;
-import org.apache.axis2.engine.AbstractDispatcher;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import javax.xml.namespace.QName;
-
-/**
- * If none of the dispatcher were able to find an Axis2 service or operation, this dispatcher will
- * be reached, and it will dispatch to the MultitenantService, which is associated with the
- * {@link org.wso2.carbon.core.multitenancy.MultitenantMessageReceiver}
- */
-public class MultitenantDispatcher extends AbstractDispatcher {
-
-    public static final String NAME = "MultitenantDispatcher";
-
-    public void initDispatcher() {
-        QName qn = new QName("http://wso2.org/projects/carbon", NAME);
-        HandlerDescription hd = new HandlerDescription(qn.getLocalPart());
-        super.init(hd);
-    }
-
-    public AxisService findService(MessageContext mc) throws AxisFault {
-        AxisService service = mc.getAxisService();
-        if (service == null) {
-            String to = mc.getTo().getAddress();
-
-            int tenantDelimiterIndex = to.indexOf("/t/");
-            if (tenantDelimiterIndex != -1) {
-                AxisConfiguration ac = mc.getConfigurationContext().getAxisConfiguration();
-                return ac.getService(MultitenantConstants.MULTITENANT_DISPATCHER_SERVICE);
-            }
-        }
-        return service;
-    }
-
-    public AxisOperation findOperation(AxisService svc, MessageContext mc) throws AxisFault {
-        AxisOperation operation = mc.getAxisOperation();
-        if (operation == null) {
-            return svc.getOperation(MultitenantConstants.MULTITENANT_DISPATCHER_OPERATION);
-        }
-        return operation;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.dispatcher/2.1.0/src/main/java/org/apache/stratos/tenant/dispatcher/internal/TenantDispatcherServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.dispatcher/2.1.0/src/main/java/org/apache/stratos/tenant/dispatcher/internal/TenantDispatcherServiceComponent.java b/components/org.apache.stratos.tenant.dispatcher/2.1.0/src/main/java/org/apache/stratos/tenant/dispatcher/internal/TenantDispatcherServiceComponent.java
deleted file mode 100644
index 4d4b9cb..0000000
--- a/components/org.apache.stratos.tenant.dispatcher/2.1.0/src/main/java/org/apache/stratos/tenant/dispatcher/internal/TenantDispatcherServiceComponent.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.tenant.dispatcher.internal;
-
-import org.apache.axis2.AxisFault;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.description.AxisOperation;
-import org.apache.axis2.description.AxisService;
-import org.apache.axis2.description.AxisServiceGroup;
-import org.apache.axis2.description.HandlerDescription;
-import org.apache.axis2.description.InOutAxisOperation;
-import org.apache.axis2.description.PhaseRule;
-import org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.axis2.engine.Handler;
-import org.apache.axis2.engine.Phase;
-import org.apache.axis2.phaseresolver.PhaseException;
-import org.apache.axis2.phaseresolver.PhaseMetadata;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.CarbonConstants;
-import org.wso2.carbon.core.multitenancy.MultitenantDispatcher;
-import org.wso2.carbon.core.multitenancy.MultitenantMessageReceiver;
-import org.wso2.carbon.utils.ConfigurationContextService;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import java.util.List;
-
-/**
- * @scr.component
- *                name="org.apache.stratos.tenant.dispatcher.internal.TenantDispatcherServiceComponent"
- *                immediate="true"
- * @scr.reference name="org.wso2.carbon.configurationContextService"
- *                interface="org.wso2.carbon.utils.ConfigurationContextService"
- *                cardinality="1..1" policy="dynamic"
- *                bind="setConfigurationContext"
- *                unbind="unsetConfigurationContext"
- */
-public class TenantDispatcherServiceComponent {
-    private Log log = LogFactory.getLog(TenantDispatcherServiceComponent.class);
-
-    private ConfigurationContext configCtx;
-
-    protected void activate(ComponentContext ctxt) {
-        try {
-            deployMultitenantService(configCtx.getAxisConfiguration());
-            addDispatchers(configCtx.getAxisConfiguration());
-        } catch (Throwable e) {
-            log.error("Failed to activate the TenantDispatcherServiceComponent", e);
-        }
-    }
-
-
-    private void deployMultitenantService(AxisConfiguration axisCfg) throws AxisFault {
-        AxisService service = new AxisService(MultitenantConstants.MULTITENANT_DISPATCHER_SERVICE);
-        AxisOperation operation =
-                new InOutAxisOperation(MultitenantConstants.MULTITENANT_DISPATCHER_OPERATION);
-        operation.setMessageReceiver(new MultitenantMessageReceiver());
-        service.addOperation(operation);
-        AxisServiceGroup multitenantSvcGroup = new AxisServiceGroup(axisCfg);
-        multitenantSvcGroup.setServiceGroupName(MultitenantConstants.MULTITENANT_DISPATCHER_SERVICE);
-        multitenantSvcGroup.addParameter(CarbonConstants.HIDDEN_SERVICE_PARAM_NAME, "true");
-        multitenantSvcGroup.addService(service);
-        axisCfg.addServiceGroup(multitenantSvcGroup);
-		if(log.isDebugEnabled()){
-			log.debug("Deployed " + MultitenantConstants.MULTITENANT_DISPATCHER_SERVICE);
-		}
-    }
-
-    /**
-     * Add the MultitenantDispatcher to the inFlow phase.
-     *
-     * @param mainAxisConfig super-tenant AxisConfiguration
-     * @throws org.apache.axis2.AxisFault if an error occurs while adding the dispatcher
-     */
-    private void addDispatchers(AxisConfiguration mainAxisConfig) throws AxisFault {
-        HandlerDescription handlerDescription = new HandlerDescription(MultitenantDispatcher.NAME);
-        PhaseRule rule = new PhaseRule(PhaseMetadata.PHASE_DISPATCH);
-        rule.setAfter(HTTPLocationBasedDispatcher.NAME);
-        rule.setBefore("SynapseDispatcher");
-        handlerDescription.setRules(rule);
-
-        MultitenantDispatcher multitenantDispatcher = new MultitenantDispatcher();
-        multitenantDispatcher.initDispatcher();
-        handlerDescription.setHandler(multitenantDispatcher);
-
-        List<Phase> inflowPhases
-                = mainAxisConfig.getInFlowPhases();
-        for (Phase inPhase : inflowPhases) {
-            // we are interested about the Dispatch phase in the inflow
-            if (PhaseMetadata.PHASE_DISPATCH.equals(inPhase.getPhaseName())) {
-                boolean handlerFound = false;
-                for (Handler handler : inPhase.getHandlers()) {
-                    if (handler.getHandlerDesc().getName() != null &&
-                            handler.getHandlerDesc().getName().equals(MultitenantDispatcher.NAME)) {
-                        handlerFound = true;
-                    }
-                }
-                if (!handlerFound) {
-                    try {
-                        inPhase.addHandler(handlerDescription);
-                    } catch (PhaseException e) {
-                        String msg = "Couldn't start Carbon, Cannot add " +
-                                "the required Carbon handlers";
-                        log.fatal(msg, e);
-                        throw new AxisFault(msg);
-                    }
-                }
-            }
-        }
-		if (log.isDebugEnabled()) {
-			log.info("Added multitenant dispatchers");
-		}
-    }
-
-    protected void deactivate(ComponentContext ctxt) {
-        if (log.isDebugEnabled()) {
-            log.debug("Deactivated TenantDispatcherServiceComponent");
-        }
-    }
-
-    protected void setConfigurationContext(ConfigurationContextService configCtx) {
-        this.configCtx = configCtx.getServerConfigContext();
-    }
-
-    protected void unsetConfigurationContext(ConfigurationContextService configCtx) {
-        this.configCtx = null;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.dispatcher/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.dispatcher/pom.xml b/components/org.apache.stratos.tenant.dispatcher/pom.xml
new file mode 100644
index 0000000..3a92ab4
--- /dev/null
+++ b/components/org.apache.stratos.tenant.dispatcher/pom.xml
@@ -0,0 +1,92 @@
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one
+  ~ or more contributor license agreements. See the NOTICE file
+  ~ distributed with this work for additional information
+  ~ regarding copyright ownership. The ASF licenses this file
+  ~ to you under the Apache License, Version 2.0 (the
+  ~ "License"); you may not use this file except in compliance
+  ~ with the License. You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing,
+  ~ software distributed under the License is distributed on an
+  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~ KIND, either express or implied. See the License for the
+  ~ specific language governing permissions and limitations
+  ~ under the License.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.tenant.dispatcher</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Tenant Dispatcher</name>
+
+    <build>
+
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Private-Package>
+                            org.apache.stratos.tenant.dispatcher.*,
+                        </Private-Package>
+                        <Export-Package>
+                            !org.apache.stratos.tenant.dispatcher.internal.*,
+                            org.apache.stratos.tenant.dispatcher.*
+                        </Export-Package>
+                        <Import-Package>
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.dispatcher/src/main/java/org/apache/stratos/tenant/dispatcher/MultitenantDispatcher.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.dispatcher/src/main/java/org/apache/stratos/tenant/dispatcher/MultitenantDispatcher.java b/components/org.apache.stratos.tenant.dispatcher/src/main/java/org/apache/stratos/tenant/dispatcher/MultitenantDispatcher.java
new file mode 100644
index 0000000..beed246
--- /dev/null
+++ b/components/org.apache.stratos.tenant.dispatcher/src/main/java/org/apache/stratos/tenant/dispatcher/MultitenantDispatcher.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.tenant.dispatcher;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.AxisOperation;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.HandlerDescription;
+import org.apache.axis2.engine.AbstractDispatcher;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import javax.xml.namespace.QName;
+
+/**
+ * If none of the dispatcher were able to find an Axis2 service or operation, this dispatcher will
+ * be reached, and it will dispatch to the MultitenantService, which is associated with the
+ * {@link org.wso2.carbon.core.multitenancy.MultitenantMessageReceiver}
+ */
+public class MultitenantDispatcher extends AbstractDispatcher {
+
+    public static final String NAME = "MultitenantDispatcher";
+
+    public void initDispatcher() {
+        QName qn = new QName("http://wso2.org/projects/carbon", NAME);
+        HandlerDescription hd = new HandlerDescription(qn.getLocalPart());
+        super.init(hd);
+    }
+
+    public AxisService findService(MessageContext mc) throws AxisFault {
+        AxisService service = mc.getAxisService();
+        if (service == null) {
+            String to = mc.getTo().getAddress();
+
+            int tenantDelimiterIndex = to.indexOf("/t/");
+            if (tenantDelimiterIndex != -1) {
+                AxisConfiguration ac = mc.getConfigurationContext().getAxisConfiguration();
+                return ac.getService(MultitenantConstants.MULTITENANT_DISPATCHER_SERVICE);
+            }
+        }
+        return service;
+    }
+
+    public AxisOperation findOperation(AxisService svc, MessageContext mc) throws AxisFault {
+        AxisOperation operation = mc.getAxisOperation();
+        if (operation == null) {
+            return svc.getOperation(MultitenantConstants.MULTITENANT_DISPATCHER_OPERATION);
+        }
+        return operation;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.dispatcher/src/main/java/org/apache/stratos/tenant/dispatcher/internal/TenantDispatcherServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.dispatcher/src/main/java/org/apache/stratos/tenant/dispatcher/internal/TenantDispatcherServiceComponent.java b/components/org.apache.stratos.tenant.dispatcher/src/main/java/org/apache/stratos/tenant/dispatcher/internal/TenantDispatcherServiceComponent.java
new file mode 100644
index 0000000..4d4b9cb
--- /dev/null
+++ b/components/org.apache.stratos.tenant.dispatcher/src/main/java/org/apache/stratos/tenant/dispatcher/internal/TenantDispatcherServiceComponent.java
@@ -0,0 +1,146 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.tenant.dispatcher.internal;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.AxisOperation;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.AxisServiceGroup;
+import org.apache.axis2.description.HandlerDescription;
+import org.apache.axis2.description.InOutAxisOperation;
+import org.apache.axis2.description.PhaseRule;
+import org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.axis2.engine.Handler;
+import org.apache.axis2.engine.Phase;
+import org.apache.axis2.phaseresolver.PhaseException;
+import org.apache.axis2.phaseresolver.PhaseMetadata;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.core.multitenancy.MultitenantDispatcher;
+import org.wso2.carbon.core.multitenancy.MultitenantMessageReceiver;
+import org.wso2.carbon.utils.ConfigurationContextService;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import java.util.List;
+
+/**
+ * @scr.component
+ *                name="org.apache.stratos.tenant.dispatcher.internal.TenantDispatcherServiceComponent"
+ *                immediate="true"
+ * @scr.reference name="org.wso2.carbon.configurationContextService"
+ *                interface="org.wso2.carbon.utils.ConfigurationContextService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setConfigurationContext"
+ *                unbind="unsetConfigurationContext"
+ */
+public class TenantDispatcherServiceComponent {
+    private Log log = LogFactory.getLog(TenantDispatcherServiceComponent.class);
+
+    private ConfigurationContext configCtx;
+
+    protected void activate(ComponentContext ctxt) {
+        try {
+            deployMultitenantService(configCtx.getAxisConfiguration());
+            addDispatchers(configCtx.getAxisConfiguration());
+        } catch (Throwable e) {
+            log.error("Failed to activate the TenantDispatcherServiceComponent", e);
+        }
+    }
+
+
+    private void deployMultitenantService(AxisConfiguration axisCfg) throws AxisFault {
+        AxisService service = new AxisService(MultitenantConstants.MULTITENANT_DISPATCHER_SERVICE);
+        AxisOperation operation =
+                new InOutAxisOperation(MultitenantConstants.MULTITENANT_DISPATCHER_OPERATION);
+        operation.setMessageReceiver(new MultitenantMessageReceiver());
+        service.addOperation(operation);
+        AxisServiceGroup multitenantSvcGroup = new AxisServiceGroup(axisCfg);
+        multitenantSvcGroup.setServiceGroupName(MultitenantConstants.MULTITENANT_DISPATCHER_SERVICE);
+        multitenantSvcGroup.addParameter(CarbonConstants.HIDDEN_SERVICE_PARAM_NAME, "true");
+        multitenantSvcGroup.addService(service);
+        axisCfg.addServiceGroup(multitenantSvcGroup);
+		if(log.isDebugEnabled()){
+			log.debug("Deployed " + MultitenantConstants.MULTITENANT_DISPATCHER_SERVICE);
+		}
+    }
+
+    /**
+     * Add the MultitenantDispatcher to the inFlow phase.
+     *
+     * @param mainAxisConfig super-tenant AxisConfiguration
+     * @throws org.apache.axis2.AxisFault if an error occurs while adding the dispatcher
+     */
+    private void addDispatchers(AxisConfiguration mainAxisConfig) throws AxisFault {
+        HandlerDescription handlerDescription = new HandlerDescription(MultitenantDispatcher.NAME);
+        PhaseRule rule = new PhaseRule(PhaseMetadata.PHASE_DISPATCH);
+        rule.setAfter(HTTPLocationBasedDispatcher.NAME);
+        rule.setBefore("SynapseDispatcher");
+        handlerDescription.setRules(rule);
+
+        MultitenantDispatcher multitenantDispatcher = new MultitenantDispatcher();
+        multitenantDispatcher.initDispatcher();
+        handlerDescription.setHandler(multitenantDispatcher);
+
+        List<Phase> inflowPhases
+                = mainAxisConfig.getInFlowPhases();
+        for (Phase inPhase : inflowPhases) {
+            // we are interested about the Dispatch phase in the inflow
+            if (PhaseMetadata.PHASE_DISPATCH.equals(inPhase.getPhaseName())) {
+                boolean handlerFound = false;
+                for (Handler handler : inPhase.getHandlers()) {
+                    if (handler.getHandlerDesc().getName() != null &&
+                            handler.getHandlerDesc().getName().equals(MultitenantDispatcher.NAME)) {
+                        handlerFound = true;
+                    }
+                }
+                if (!handlerFound) {
+                    try {
+                        inPhase.addHandler(handlerDescription);
+                    } catch (PhaseException e) {
+                        String msg = "Couldn't start Carbon, Cannot add " +
+                                "the required Carbon handlers";
+                        log.fatal(msg, e);
+                        throw new AxisFault(msg);
+                    }
+                }
+            }
+        }
+		if (log.isDebugEnabled()) {
+			log.info("Added multitenant dispatchers");
+		}
+    }
+
+    protected void deactivate(ComponentContext ctxt) {
+        if (log.isDebugEnabled()) {
+            log.debug("Deactivated TenantDispatcherServiceComponent");
+        }
+    }
+
+    protected void setConfigurationContext(ConfigurationContextService configCtx) {
+        this.configCtx = configCtx.getServerConfigContext();
+    }
+
+    protected void unsetConfigurationContext(ConfigurationContextService configCtx) {
+        this.configCtx = null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.core/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.core/2.1.0/pom.xml b/components/org.apache.stratos.tenant.mgt.core/2.1.0/pom.xml
deleted file mode 100644
index 4937403..0000000
--- a/components/org.apache.stratos.tenant.mgt.core/2.1.0/pom.xml
+++ /dev/null
@@ -1,82 +0,0 @@
-<!--
-# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-  -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-<relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.tenant.mgt.core</artifactId>
-    <version>2.1.0</version>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Tenant Managment Core</name>
-
-    <build>
-
-        <plugins>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Private-Package>
-                            org.apache.stratos.tenant.mgt.core.internal.*;-split-package:=merge-last,
-                        </Private-Package>
-                        <Import-Package>
-                            org.apache.stratos.common.*,
-                            org.wso2.carbon.registry.core.*,
-                            !javax.xml.namespace,
-                            javax.xml.namespace; version=0.0.0,
-                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
-                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
-                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
-                            *;resolution:=optional
-                        </Import-Package>
-                        <Export-Package>
-                            org.apache.stratos.tenant.mgt.core.*,
-                        </Export-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.registry.core</artifactId>
-	    <version>4.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.stratos.common</artifactId>
-	    <version>2.1.0</version>
-        </dependency>
-    </dependencies>
-</project>


[21/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentServiceComponent.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentServiceComponent.java
deleted file mode 100644
index b31cc7a..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentServiceComponent.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-
-package org.apache.stratos.cartridge.agent.internal;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cartridge.agent.ClusteringClient;
-import org.apache.stratos.cartridge.agent.ELBMembershipListener;
-import org.apache.stratos.cartridge.agent.registrant.RegistrantDatabase;
-import org.apache.stratos.cartridge.agent.registrant.RegistrantHealthChecker;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.utils.CarbonUtils;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.util.Properties;
-
-/**
- * @scr.component name="org.wso2.carbon.cartridge.agent" immediate="true"
- *
- * @scr.reference name="config.context.service"
- *                interface="org.wso2.carbon.utils.ConfigurationContextService"
- *                cardinality="1..1" policy="dynamic"
- *                bind="setConfigurationContextService"
- *                unbind="unsetConfigurationContextService"
- */
-public class CartridgeAgentServiceComponent {
-    private static final Log log = LogFactory.getLog(CartridgeAgentServiceComponent.class);
-
-    protected void activate(ComponentContext ctx) {
-        RegistrantHealthChecker healthChecker;
-        ConfigurationContext configurationContext = DataHolder.getServerConfigContext();
-
-        FileInputStream confFileIPStream = null;
-        try {
-            long start = System.currentTimeMillis();
-            log.info("Starting WSO2 Cartridge Agent...");
-            Properties conf = new Properties();
-            confFileIPStream = new FileInputStream(CarbonUtils.getCarbonConfigDirPath() +
-                    File.separator + "agent.properties");
-            conf.load(confFileIPStream);            
-            for (String name : conf.stringPropertyNames()) {
-    			String value = conf.getProperty(name);
-    			System.setProperty(name, value);
-    		}
-            
-            RegistrantDatabase registrantDatabase = new RegistrantDatabase();
-//            AxisServer axisServer = new AxisServer();
-//            ConfigurationContext configurationContext = axisServer.getConfigurationContext();
-            ClusteringClient clusteringClient = new ClusteringClient(registrantDatabase);
-            configurationContext.setProperty(CartridgeAgentConstants.CLUSTERING_CLIENT, clusteringClient);
-
-            String healthCheckInterval = conf.getProperty("registrant.heathCheckInterval");
-            String threadPoolSize = conf.getProperty("registrant.healthCheckThreadPoolSize");
-            int healthCheckIntervalInt =
-                    (healthCheckInterval == null) ? 2000 : Integer.parseInt(healthCheckInterval);
-            int threadPoolSizeInt =
-                    (threadPoolSize == null) ? 10 : Integer.parseInt(healthCheckInterval);
-            log.info("Registrant health check interval: " + healthCheckIntervalInt + "s");
-            healthChecker = new RegistrantHealthChecker(registrantDatabase,
-                    clusteringClient,
-                    configurationContext,
-                    healthCheckIntervalInt,
-                    threadPoolSizeInt
-            );
-            clusteringClient.init(conf,
-                    configurationContext,
-                    new ELBMembershipListener(clusteringClient,
-                            configurationContext,
-                            registrantDatabase,
-                            healthChecker));
-            healthChecker.startAll();
-            DataHolder.setHealthChecker(healthChecker);
-            /*configurationContext.deployService(AxisService.createService(CartridgeAgentService.class.getName().toString(),
-                     configurationContext.getAxisConfiguration()));*/
-//            axisServer.deployService(CartridgeAgentService.class.getName());
-
-
-            // Starting cliet..
-//            String trustStorePath = conf.getProperty("wso2.carbon.truststore");
-//            System.setProperty("javax.net.ssl.trustStore", trustStorePath);
-//            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
-//            // new InstanceStateNotificationClient().notify(null, null);
-//
-//            System.setProperty("adc.host",  conf.getProperty("adc.host"));
-//            System.setProperty("adc.port",  conf.getProperty("adc.port"));
-            // ----------------------
-
-            Runtime.getRuntime().addShutdownHook(new Thread(){
-
-                @Override
-                public void run() {
-                    log.info("Shutting down WSO2 Cartridge Agent...");
-                }
-            });
-            log.info("Started Cartridge Agent in " + (System.currentTimeMillis() - start) + "ms");
-        } catch (Exception e) {
-            log.fatal("Could not start Cartridge Agent", e);
-            //System.exit(1);
-        } finally {
-            if (confFileIPStream != null) {
-                try {
-                    confFileIPStream.close();
-                } catch (IOException e) {
-                    log.error("Cannot close agent.properties file", e);
-                }
-            }
-        }
-
-    }
-
-    protected void deactivate(ComponentContext ctx) {
-    }
-
-    protected void setConfigurationContextService(ConfigurationContextService contextService) {
-        DataHolder.setServerConfigContext(contextService.getServerConfigContext());
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/DataHolder.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/DataHolder.java
deleted file mode 100644
index 955c931..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/internal/DataHolder.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-
-package org.apache.stratos.cartridge.agent.internal;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.stratos.cartridge.agent.registrant.RegistrantHealthChecker;
-
-public class DataHolder {
-    private static ConfigurationContext serverConfigContext;
-    private static RegistrantHealthChecker healthChecker;
-
-    public static void setServerConfigContext(ConfigurationContext serverConfigContext) {
-        DataHolder.serverConfigContext = serverConfigContext;
-    }
-
-    public static void setHealthChecker(RegistrantHealthChecker healthChecker) {
-        DataHolder.healthChecker = healthChecker;
-    }
-
-    public static ConfigurationContext getServerConfigContext() {
-        return serverConfigContext;
-    }
-
-    public static RegistrantHealthChecker getHealthChecker() {
-        return healthChecker;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/PortMapping.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/PortMapping.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/PortMapping.java
deleted file mode 100644
index 3d1bc8b..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/PortMapping.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent.registrant;
-
-import java.io.Serializable;
-
-/**
- * This class provides the mapping between the actual port &amp; proxy port of a {@link org.apache.stratos.cartridge.agent.registrant.Registrant}
- *
- * e.g. if the Registrant is serving HTTP requests on port 9763, and the requests to that port have
- * to be proxied via port 80 on the ELB, the <code>primaryPort</code> has to be specified as 9763
- * &amp; <code>proxyPort</code> has to be specified as 80.
- *
- * @see org.apache.stratos.cartridge.agent.registrant.Registrant
- */
-@SuppressWarnings("unused")
-public class PortMapping implements Serializable {
-
-    private static final long serialVersionUID = 8020727939469156788L;
-    public static final String PORT_TYPE_HTTP = "http";
-    public static final String PORT_TYPE_HTTPS = "https";
-
-    private int primaryPort;
-    private int proxyPort;
-    private String type;
-
-    public PortMapping() {
-    }
-
-    public int getPrimaryPort() {
-        return primaryPort;
-    }
-
-    public int getProxyPort() {
-        return proxyPort;
-    }
-
-    public void setPrimaryPort(int primaryPort) {
-        this.primaryPort = primaryPort;
-    }
-
-    public void setProxyPort(int proxyPort) {
-        this.proxyPort = proxyPort;
-    }
-
-    public String getType() {
-        return type;
-    }
-
-    public void setType(String type) {
-        if (type.equalsIgnoreCase(PORT_TYPE_HTTP) && type.equalsIgnoreCase(PORT_TYPE_HTTPS)) {
-            throw new RuntimeException("Invalid port type " + type);
-        }
-        this.type = type;
-    }
-
-    public boolean equals (Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
-
-        PortMapping that = (PortMapping) o;
-        return (type.equalsIgnoreCase(that.type) &&
-               (primaryPort == that.primaryPort) &&
-               (proxyPort == that.proxyPort));
-    }
-
-    @Override
-    public int hashCode() {
-        return type.hashCode() +
-                Integer.toString(primaryPort).hashCode() +
-                Integer.toString(proxyPort).hashCode();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/Registrant.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/Registrant.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/Registrant.java
deleted file mode 100644
index a6ed860..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/Registrant.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent.registrant;
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.ClusteringFault;
-
-import java.io.Serializable;
-import java.util.Arrays;
-
-/**
- * This class represents a process which registers itself with this Cartridge Agent
- */
-@SuppressWarnings("unused")
-public class Registrant implements Serializable {
-
-    private static final long serialVersionUID = 1026289225178520964L;
-
-    private String key;
-    //private int tenantId;
-    private String tenantRange;
-    private String service;
-    private String hostName;
-    private PortMapping[] portMappings;
-    private String remoteHost;
-    private transient ClusteringAgent clusteringAgent;
-    private int minInstanceCount;
-    private int maxInstanceCount;
-    private int maxRequestsPerSecond;
-	private int roundsToAverage;
-	private double alarmingUpperRate;
-	private double alarmingLowerRate;
-	private double scaleDownFactor;
-   
-
-	public String getService() {
-        return service;
-    }
-
-    public String getTenantRange() {
-    	return tenantRange;
-    }
-
-	public void setTenantRange(String tenantRange) {
-    	this.tenantRange = tenantRange;
-    }
-
-	public void setService(String service) {
-        this.service = service;
-    }
-
-    public String getHostName() {
-        return hostName;
-    }
-
-    public void setHostName(String hostName) {
-        this.hostName = hostName;
-    }
-
-    public PortMapping[] getPortMappings() {
-        return Arrays.copyOf(portMappings, portMappings.length);
-    }
-
-    public void setPortMappings(PortMapping[] portMappings) {
-        this.portMappings = Arrays.copyOf(portMappings, portMappings.length);
-    }
-
-    public String getKey() {
-        return key;
-    }
-
-    public void setKey(String key) {
-        this.key = key;
-    }    
-    
-    public int getMinInstanceCount() {
-		return minInstanceCount;
-	}
-
-	public void setMinInstanceCount(int minInstanceCount) {
-		this.minInstanceCount = minInstanceCount;
-	}
-
-	public int getMaxInstanceCount() {
-		return maxInstanceCount;
-	}
-
-	public void setMaxInstanceCount(int maxInstanceCount) {
-		this.maxInstanceCount = maxInstanceCount;
-	}
-
-	public String retrieveClusterDomain() {
-		// alias.hostname.php.domain
-		return hostName+"."+service+".domain";
-    }
-
-    public void start(ClusteringAgent clusteringAgent) throws ClusteringFault {
-        this.clusteringAgent = clusteringAgent;
-        clusteringAgent.init();
-    }
-
-    public void stop() {
-        if (clusteringAgent != null) {
-            clusteringAgent.stop();
-        }
-        clusteringAgent = null;
-    }
-
-    public boolean running() {
-        return clusteringAgent != null;
-    }
-
-    public String getRemoteHost() {
-        return remoteHost;
-    }
-
-    public void setRemoteHost(String remoteHost) {
-        this.remoteHost = remoteHost;
-    }    
-    
-    public int getMaxRequestsPerSecond() {
-    	return maxRequestsPerSecond;
-    }
-
-	public void setMaxRequestsPerSecond(int maxRequestsPerSecond) {
-    	this.maxRequestsPerSecond = maxRequestsPerSecond;
-    }
-
-	public int getRoundsToAverage() {
-    	return roundsToAverage;
-    }
-
-	public void setRoundsToAverage(int roundsToAverage) {
-    	this.roundsToAverage = roundsToAverage;
-    }
-
-	public double getAlarmingUpperRate() {
-    	return alarmingUpperRate;
-    }
-
-	public void setAlarmingUpperRate(double alarmingUpperRate) {
-    	this.alarmingUpperRate = alarmingUpperRate;
-    }
-
-	public double getAlarmingLowerRate() {
-    	return alarmingLowerRate;
-    }
-
-	public void setAlarmingLowerRate(double alarmingLowerRate) {
-    	this.alarmingLowerRate = alarmingLowerRate;
-    }
-
-	public double getScaleDownFactor() {
-    	return scaleDownFactor;
-    }
-
-	public void setScaleDownFactor(double scaleDownFactor) {
-    	this.scaleDownFactor = scaleDownFactor;
-    }
-
-	@Override
-    public String toString() {
-        return "Registrant{" +
-               "key='" + key + '\'' +
-               ", remoteHost='" + remoteHost + '\'' +
-               '}';
-    }
-
-    @Override
-    public boolean equals(Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
-
-        Registrant that = (Registrant) o;
-        return key.equals(that.key);
-    }
-
-    @Override
-    public int hashCode() {
-        return key.hashCode();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantDatabase.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantDatabase.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantDatabase.java
deleted file mode 100644
index dc511dc..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantDatabase.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent.registrant;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cartridge.agent.InstanceStateNotificationClientThread;
-import org.apache.stratos.cartridge.agent.exception.CartridgeAgentException;
-
-import java.io.*;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-/**
- * This class represents a database for {@link Registrant}s. Registrants added to this database will be
- * persisted, so that when the Cartridge Agent is restarted, the Registrants can be restored.
- *
- * @see Registrant
- */
-public class RegistrantDatabase {
-    private static final Log log = LogFactory.getLog(RegistrantDatabase.class);
-
-    private List<Registrant> registrants = new CopyOnWriteArrayList<Registrant>();
-
-    public void add(Registrant registrant) throws CartridgeAgentException {
-        if (registrants.contains(registrant) && registrant.running()) {
-            throw new CartridgeAgentException("Active registrant with key " +
-                                              registrant.getKey() + " already exists");
-        }
-        synchronized (registrant) {
-            if (!isAlreadyAdded(registrant)) {
-                persist(registrant);
-                registrants.add(registrant);
-                log.info("Added registrant " + registrant);
-
-            } else {
-                log.info("Registrant " + registrant + "has been already added");
-            }
-        }
-    }
-
-    private void persist(Registrant registrant) throws CartridgeAgentException {
-        try {
-            ObjectOutput out = null;
-            try {
-                // Serialize to a file
-                if (!new File("registrants").exists() && !new File("registrants").mkdirs()) {
-                    throw new IOException("Cannot create registrants directory");
-                }
-                out = new ObjectOutputStream(new FileOutputStream("registrants" + File.separator +
-                                                                  registrant.getKey() + ".ser"));
-                out.writeObject(registrant);
-                out.close();
-            } finally {
-                if (out != null) {
-                    out.close();
-                }
-            }
-        } catch (IOException e) {
-            log.error("Could not serialize registrant " + registrant, e);
-        }
-    }
-
-    public void stopAll() {
-        for (Registrant registrant : registrants) {
-        	new Thread(new InstanceStateNotificationClientThread(registrant, "INACTIVE")).start();
-            registrant.stop();
-        }
-    }
-
-    public boolean containsActive(Registrant registrant) {
-        return registrants.contains(registrant) &&
-               registrants.get(registrants.indexOf(registrant)).running();
-    }
-
-    public List<Registrant> getRegistrants() {
-        return Collections.unmodifiableList(registrants);
-    }
-
-    public boolean isAlreadyAdded(Registrant registrant) {
-
-        boolean alreadyAdded = false;
-        for (Registrant registrantFromDb : registrants) {
-            if(registrantFromDb.getRemoteHost().equals(registrant.getRemoteHost())) {
-
-                PortMapping[] portMappingofRegistrantOfDB = registrantFromDb.getPortMappings();
-                PortMapping[] portMappingofRegistrant = registrant.getPortMappings();
-
-                if(portMappingofRegistrant.length != portMappingofRegistrantOfDB.length) {
-                    continue;
-
-                } else {
-                    alreadyAdded = checkPortMappings(registrant, registrantFromDb);
-                }
-
-            } else {
-                continue;
-            }
-        }
-        return alreadyAdded;
-    }
-
-    private boolean checkPortMappings (Registrant newRegistrant, Registrant existingRegistrant) {
-
-        PortMapping[] portMappingsOfNewRegistrant = newRegistrant.getPortMappings();
-        PortMapping[] portMappingsOfExistingRegistrant = existingRegistrant.getPortMappings();
-
-        for (PortMapping portMappingOfNewRegistrant : portMappingsOfNewRegistrant) {
-            boolean matchFound = false;
-            for (PortMapping portMappingOfExistingRegistrant : portMappingsOfExistingRegistrant) {
-                if(portMappingOfExistingRegistrant.equals(portMappingOfNewRegistrant)) {
-                    matchFound = true;
-                    break;
-                }
-            }
-            if(!matchFound) {
-                return false;
-            }
-        }
-        if(log.isDebugEnabled()) {
-            log.debug("***********************************Found matching registrant for " + newRegistrant + " in the Registrant database");
-        }
-        return true;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantHealthChecker.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantHealthChecker.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantHealthChecker.java
deleted file mode 100644
index 2f8a227..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantHealthChecker.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent.registrant;
-
-import java.util.List;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cartridge.agent.ClusteringClient;
-import org.apache.stratos.cartridge.agent.InstanceStateNotificationClientThread;
-
-/**
- * This health checker periodically checks the health of the {@link Registrant}s
- *
- * If a registrant is found to be unhealthy, then it is stopped. This task will also try to
- * connect to reactivate a registrant which was previously found to be unhealthy.
- *
- * If the Elastic Load Balancer (ELB) is not running, this health checker will not continue with
- * registrant health checks since it is futile to try to connect the registrants to the
- * unavailable ELB.
- */
-public class RegistrantHealthChecker {
-    private static final Log log = LogFactory.getLog(RegistrantHealthChecker.class);
-
-    private RegistrantDatabase database;
-    private ClusteringClient clusteringClient;
-    private ConfigurationContext configurationContext;
-    private ScheduledExecutorService scheduler;
-    private volatile boolean isELBRunning;
-    private int healthCheckInterval;
-
-    public RegistrantHealthChecker(RegistrantDatabase database,
-                                   ClusteringClient clusteringClient,
-                                   ConfigurationContext configurationContext,
-                                   int healthCheckInterval,
-                                   int threadPoolSize) {
-        this.database = database;
-        this.clusteringClient = clusteringClient;
-        this.configurationContext = configurationContext;
-        this.healthCheckInterval = healthCheckInterval;
-        scheduler = Executors.newScheduledThreadPool(threadPoolSize);
-    }
-
-    public void startAll() {
-        List<Registrant> registrants = database.getRegistrants();
-        for (Registrant registrant : registrants) {
-            scheduler.scheduleWithFixedDelay(new HealthCheckerTask(registrant), 45,
-                                 healthCheckInterval, TimeUnit.SECONDS);
-            if (log.isDebugEnabled()) {
-                log.debug("Started a health checker for " + registrant + " ...");
-            }
-        }
-    }
-
-    public void start(Registrant registrant){
-        scheduler.scheduleWithFixedDelay(new HealthCheckerTask(registrant), 45,
-                             healthCheckInterval, TimeUnit.SECONDS);
-        if (log.isDebugEnabled()) {
-            log.debug("Added a health checker for " + registrant + " ...");
-        }
-    }
-
-    public void setELBRunning(boolean ELBRunning) {
-        isELBRunning = ELBRunning;
-    }
-
-    private final class HealthCheckerTask implements Runnable {
-        Registrant registrant;
-        public HealthCheckerTask(Registrant registrant){
-            this.registrant = registrant;
-        }
-        public void run() {
-            if(!isELBRunning){
-                return;
-            }
-            try {
-                boolean healthyRegistrant = RegistrantUtil.isHealthy(registrant);
-                if (!healthyRegistrant && registrant.running()) {
-                    registrant.stop();
-                    new Thread(new InstanceStateNotificationClientThread(registrant, "INACTIVE")).start();
-                    log.warn("Stopped registrant " + registrant + " since it is unhealthy." );
-                } else if (healthyRegistrant && !registrant.running()) {
-                    registrant.stop();
-                    new Thread(new InstanceStateNotificationClientThread(registrant, "INACTIVE")).start();
-                    clusteringClient.joinGroup(registrant, configurationContext);
-                    log.info("Restarted registrant " + registrant + " after it became active");
-                }
-            } catch (Exception e) {
-                log.error("Error occurred while running registrant health check", e);
-            }
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantUtil.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantUtil.java
deleted file mode 100644
index 60208b4..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/registrant/RegistrantUtil.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.cartridge.agent.registrant;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cartridge.agent.ClusteringClient;
-import org.apache.stratos.cartridge.agent.exception.CartridgeAgentException;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.net.*;
-
-/**
- * Utility method collection for handling {@link Registrant}s
- *
- * @see Registrant
- */
-public class RegistrantUtil {
-    private static final Log log = LogFactory.getLog(RegistrantUtil.class);
-    private static boolean registrantsReloaded = false;
-    /**
-     * Before adding a member, we will try to verify whether we can connect to it
-     *
-     * @param registrant The member whose connectvity needs to be verified
-     * @return true, if the member can be contacted; false, otherwise.
-     */
-    public static boolean isHealthy(Registrant registrant) {
-        if (log.isDebugEnabled()) {
-            log.debug("Trying to connect to registrant " + registrant + "...");
-        }
-        if(log.isDebugEnabled()) {
-            log.debug("***********************************************isHealthy() method for registrant " + registrant);
-        }
-        String registrantRemoteHost = registrant.getRemoteHost();
-        log.debug("remote host : " + registrantRemoteHost);
-        if(registrantRemoteHost == null){
-            registrantRemoteHost = "localhost";
-        }
-        InetAddress addr;
-        try {
-            addr = InetAddress.getByName(registrantRemoteHost);
-            if(log.isDebugEnabled()) {
-                log.debug("***********************************************Host resolved for registrant " + registrant);
-            }
-        } catch (UnknownHostException e) {
-            log.error("Registrant " + registrant + " is unhealthy");
-            return false;
-        }
-        PortMapping[] portMappings = registrant.getPortMappings();
-
-        int maxRetries = Integer.parseInt(System.getProperty("clustering.maxRetries"));
-
-        for (int retries = maxRetries; retries > 0; retries--) {
-            try {
-                for (PortMapping portMapping : portMappings) {
-                    int port = portMapping.getPrimaryPort();
-                    if(log.isDebugEnabled()) {
-                        log.debug("***********************************************primary port" + port + " registrant " + registrant);
-                    }
-                    if (port != -1 && port != 0) {
-                        if(log.isDebugEnabled()) {
-                            log.debug("***********************************************connecting to " + registrant +
-                                    " re-try: " + retries);
-                        }
-                        SocketAddress httpSockaddr = new InetSocketAddress(addr, port);
-                        new Socket().connect(httpSockaddr, 10000);
-                        if(log.isDebugEnabled()) {
-                            log.debug("***********************************************connected successfully to port: " + port);
-                        }
-                    }
-                }
-                return true;
-            } catch (IOException e) {
-				if (log.isDebugEnabled()) {
-					log.debug("Error occurred.. " + e.getMessage());
-				}
-                String msg = e.getMessage();
-                if (!msg.contains("Connection refused") && !msg.contains("connect timed out")) {
-                    String msg2 = "Cannot connect to registrant " + registrant;
-                    log.error(msg2, e);
-                }
-                try {
-                    Thread.sleep(1000);
-                } catch (InterruptedException ignored) {
-                }
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Reload all the registrants persisted in the file system
-     * @param clusteringClient ClusteringClient
-     * @param configurationContext   ConfigurationContext
-     * @param registrantDatabase  RegistrantDatabase
-     * @throws CartridgeAgentException If reloading registrants fails
-     */
-    public static void reloadRegistrants(ClusteringClient clusteringClient,
-                                         ConfigurationContext configurationContext,
-                                         RegistrantDatabase registrantDatabase) throws CartridgeAgentException {
-
-        if(registrantsReloaded) {
-            log.info("Registrants already re-loaded, therefore not re-loading again");
-            return;
-        }
-
-        File registrants = new File("registrants");
-        if (!registrants.exists()) {
-            log.info("Registrant information doesn't exist in the file system");
-            return;
-        }
-        File[] files = registrants.listFiles();
-        if (files == null) {
-            log.error("Directory 'Registrants' is invalid");
-            return;
-
-        } else if (files.length == 0) {
-            log.info("No registrant information found in the Registrants directory");
-            return;
-        }
-
-        for (File file : files) {
-            try {
-                Registrant registrant =
-                        deserializeRegistrant("registrants" + File.separator + file.getName());
-                if (!registrantDatabase.containsActive(registrant)) {
-                    clusteringClient.joinGroup(registrant, configurationContext);
-                }
-            } catch (IOException e) {
-                log.error("Cannot deserialize registrant file " + file.getName(), e);
-            }
-        }
-        registrantsReloaded = true;
-    }
-
-    private static Registrant deserializeRegistrant(String fileName) throws IOException {
-        Registrant registrant = null;
-        ObjectInputStream in = null;
-
-        try {
-            // Deserialize from a file
-            File file = new File(fileName);
-            in = new ObjectInputStream(new FileInputStream(file));
-            // Deserialize the object
-            registrant = (Registrant) in.readObject();
-        } catch (ClassNotFoundException ignored) {
-        } finally {
-            if (in != null) {
-                in.close();
-            }
-        }
-        return registrant;
-    }
-    
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/service/CartridgeAgentService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/service/CartridgeAgentService.java b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/service/CartridgeAgentService.java
deleted file mode 100644
index 2136164..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/java/org/apache/stratos/cartridge/agent/service/CartridgeAgentService.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.cartridge.agent.service;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.context.MessageContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.cartridge.agent.ClusteringClient;
-import org.apache.stratos.cartridge.agent.exception.CartridgeAgentException;
-import org.apache.stratos.cartridge.agent.internal.CartridgeAgentConstants;
-import org.apache.stratos.cartridge.agent.internal.DataHolder;
-import org.apache.stratos.cartridge.agent.registrant.Registrant;
-
-/**
- * Web service used for allowing {@link Registrant}s to register themselves with the Cartridge Agent
- *
- * @see Registrant
- */
-@SuppressWarnings("unused")
-public class CartridgeAgentService {
-    private static final Log log = LogFactory.getLog(CartridgeAgentService.class);
-
-    public boolean register(Registrant registrant) throws CartridgeAgentException {
-
-        MessageContext messageContext = MessageContext.getCurrentMessageContext();
-        ConfigurationContext configurationContext = messageContext.getConfigurationContext();
-        ClusteringClient clusteringClient =
-                (ClusteringClient) configurationContext.getProperty(CartridgeAgentConstants.CLUSTERING_CLIENT);
-        if (registrant.getRemoteHost() == null || registrant.getRemoteHost().isEmpty()) {
-            String remoteAddr = (String) messageContext.getProperty("REMOTE_ADDR");
-            registrant.setRemoteHost(remoteAddr);
-        }
-        log.info("Trying to add new registrant " + registrant + "...");
-        clusteringClient.joinGroup(registrant, configurationContext);
-//        Main.getHealthChecker().start(registrant);
-        DataHolder.getHealthChecker().start(registrant);
-        return true;
-
-    }
-
-    public boolean unregister(String domain, String subDomain, String hostName) throws CartridgeAgentException {
-
-        MessageContext messageContext = MessageContext.getCurrentMessageContext();
-        ConfigurationContext configurationContext = messageContext.getConfigurationContext();
-        ClusteringClient clusteringClient =
-                (ClusteringClient) configurationContext.getProperty(CartridgeAgentConstants.CLUSTERING_CLIENT);
-        clusteringClient.removeClusterDomain(domain, subDomain, hostName, configurationContext);
-        return true;
-
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/resources/META-INF/services.xml
deleted file mode 100644
index 1eb8777..0000000
--- a/components/org.apache.stratos.cartridge.agent/2.1.3/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<!-- 
-     ~  Licensed to the Apache Software Foundation (ASF) under one
-     ~  or more contributor license agreements.  See the NOTICE file
-     ~  distributed with this work for additional information
-     ~  regarding copyright ownership.  The ASF licenses this file
-     ~  to you under the Apache License, Version 2.0 (the
-     ~  "License"); you may not use this file except in compliance
-     ~  with the License.  You may obtain a copy of the License at
-     ~
-     ~    http://www.apache.org/licenses/LICENSE-2.0
-     ~
-     ~  Unless required by applicable law or agreed to in writing,
-     ~  software distributed under the License is distributed on an
-     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-     ~  KIND, either express or implied.  See the License for the
-     ~  specific language governing permissions and limitations
-     ~  under the License.
-     ~
- -->
-<serviceGroup>
-    <service name="CartridgeAgentService" scope="transportsession">
-        <transports>
-            <transport>https</transport>
-        </transports>
-        <description>
-            Admin service for ADC activities
-        </description>
-        <parameter name="ServiceClass">org.wso2.carbon.cartridge.agent.service.CartridgeAgentService
-        </parameter>
-        <parameter name="enableMTOM">true</parameter>
-        <parameter name="adminService" locked="true">false</parameter>
-        <parameter name="hiddenService" locked="true">false</parameter>
-        <parameter name="AuthorizationAction" locked="true">
-            /permission/admin/manage/modify/webapp    </parameter>
-        <parameter name="DoAuthentication" locked="true">true</parameter>
-    </service>
-</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/pom.xml b/components/org.apache.stratos.cartridge.agent/pom.xml
new file mode 100644
index 0000000..28062ee
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/pom.xml
@@ -0,0 +1,128 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 
+     ~  Licensed to the Apache Software Foundation (ASF) under one
+     ~  or more contributor license agreements.  See the NOTICE file
+     ~  distributed with this work for additional information
+     ~  regarding copyright ownership.  The ASF licenses this file
+     ~  to you under the Apache License, Version 2.0 (the
+     ~  "License"); you may not use this file except in compliance
+     ~  with the License.  You may obtain a copy of the License at
+     ~
+     ~    http://www.apache.org/licenses/LICENSE-2.0
+     ~
+     ~  Unless required by applicable law or agreed to in writing,
+     ~  software distributed under the License is distributed on an
+     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+     ~  KIND, either express or implied.  See the License for the
+     ~  specific language governing permissions and limitations
+     ~  under the License.
+     ~
+ -->
+	
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+	<parent>
+		<groupId>org.apache.stratos</groupId>
+		<artifactId>stratos-components-parent</artifactId>
+		<version>3.0.0-SNAPSHOT</version>
+	</parent>
+
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>org.apache.stratos.cartridge.agent</artifactId>
+        <packaging>bundle</packaging>
+        <version>2.1.3</version>
+	<name>Apache Stratos Cartridge Agent - agent</name>
+
+	<dependencies>
+		<dependency>
+		<groupId>org.apache.stratos</groupId>
+		<artifactId>org.apache.stratos.cartridge.messages</artifactId>
+                <version>${apache.stratos.version}</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.axis2.wso2</groupId>
+			<artifactId>axis2</artifactId>
+			<version>${axis2.wso2.version}</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.ws.commons.axiom.wso2</groupId>
+			<artifactId>axiom</artifactId>
+		        <version>${orbit.version.axiom}</version>
+		</dependency>
+		<dependency>
+			<groupId>commons-logging</groupId>
+			<artifactId>commons-logging</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.adc.instanceinfo.mgt.stub</artifactId>
+			<version>4.1.1</version>
+		</dependency>
+        <dependency>
+            <groupId>org.eclipse.osgi</groupId>
+            <artifactId>org.eclipse.osgi</artifactId>
+            <version>3.5.0.v20090311-1300</version>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.osgi</groupId>
+            <artifactId>org.eclipse.osgi.services</artifactId>
+            <version>3.3.0.v20110513</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.adc.instanceinfo.mgt.stub</artifactId>
+            <version>4.1.1</version>
+        </dependency>
+
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Private-Package>
+                            org.apache.stratos.cartridge.agent.internal.*,
+                            !org.apache.stratos.cartridge.agent.service.*
+                        </Private-Package>
+                        <Export-Package>
+                            org.apache.stratos.cartridge.agent.service.*,
+                            org.apache.stratos.cartridge.agent.client.*,
+                            org.apache.stratos.cartridge.agent.registrant.*,
+                            org.apache.stratos.cartridge.agent.exception.*,
+                            org.apache.stratos.cartridge.agent.*
+                        </Export-Package>
+                        <Import-Package>
+                            org.apache.axis2.*; version="${axis2.wso2.version}",
+                            org.apache.axiom.*;
+                            version="${axiom.wso2.version}",
+                            org.apache.neethi.*;
+                            version="${neethi.wso2.version}",
+                            javax.xml.stream.*; version="1.0.1",
+                            javax.wsdl.*; version="1.6.2",
+                            org.osgi.framework.*,
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/ClusteringClient.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/ClusteringClient.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/ClusteringClient.java
new file mode 100644
index 0000000..b81b542
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/ClusteringClient.java
@@ -0,0 +1,270 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent;
+
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.clustering.*;
+import org.apache.axis2.clustering.tribes.TribesClusteringAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.Parameter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cartridge.agent.exception.CartridgeAgentException;
+import org.apache.stratos.cartridge.agent.registrant.PortMapping;
+import org.apache.stratos.cartridge.agent.registrant.Registrant;
+import org.apache.stratos.cartridge.agent.registrant.RegistrantDatabase;
+import org.apache.stratos.cartridge.agent.registrant.RegistrantUtil;
+import org.apache.stratos.cartridge.messages.CreateClusterDomainMessage;
+import org.apache.stratos.cartridge.messages.CreateRemoveClusterDomainMessage;
+
+import javax.xml.stream.XMLStreamException;
+import java.io.ByteArrayInputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.Random;
+
+/**
+ * This class is used for all Axis2 clustering related activities such as joining the load balancer
+ * & joining registrants to clustering groups.
+ */
+public class ClusteringClient {
+    private static final Log log = LogFactory.getLog(ClusteringClient.class);
+    public static final Random RANDOM = new Random();
+    private Properties conf;
+    private RegistrantDatabase registrantDatabase;
+    private ClusteringAgent loadBalancerAgent;
+
+    public ClusteringClient(RegistrantDatabase registrantDatabase) {
+        this.registrantDatabase = registrantDatabase;
+    }
+
+    public void init(Properties conf,
+                     ConfigurationContext configurationContext,
+                     MembershipListener membershipListener) throws CartridgeAgentException {
+        try {
+            this.conf = conf;
+            joinLoadBalancer(configurationContext, membershipListener);
+        } catch (Exception e) {
+            String msg = "Cannot initialize ClusteringClient";
+            log.error(msg, e);
+            throw new CartridgeAgentException(msg, e);
+        }
+    }
+
+    private void joinLoadBalancer(ConfigurationContext configurationContext,
+                                  MembershipListener membershipListener)
+            throws CartridgeAgentException {
+
+        try {
+            loadBalancerAgent = createClusteringAgent(configurationContext,
+                                                      conf.getProperty("loadBalancerDomain"));
+            List<MembershipListener> membershipListeners = new ArrayList<MembershipListener>();
+            membershipListeners.add(membershipListener);
+            ((TribesClusteringAgent) loadBalancerAgent).setMembershipListeners(membershipListeners);
+            loadBalancerAgent.init();
+        } catch (Exception e) {
+            String msg = "Cannot join LB group";
+            log.error(msg, e);
+            throw new CartridgeAgentException(msg, e);
+        }
+    }
+
+    /**
+     * Join a cluster group of the Elastic Load Balancer
+     *
+     * @param registrant           Registrant
+     * @param configurationContext ConfigurationContext
+     * @throws CartridgeAgentException If an error occurs while joining a cluster group
+     */
+    public void joinGroup(Registrant registrant,
+                          ConfigurationContext configurationContext) throws CartridgeAgentException {
+        if (registrantDatabase.containsActive(registrant)) {
+            throw new CartridgeAgentException("Active registrant with key " +
+                                              registrant.getKey() + " already exists");
+        }
+        registrantDatabase.add(registrant);
+
+        if (!RegistrantUtil.isHealthy(registrant)) {
+            String msg = "Couldn't add registrant " + registrant + " due to a health check failure";
+            log.error(msg);
+            return;
+            //throw new CartridgeAgentException(msg);
+        }
+        try {
+            List<ClusteringCommand> clusteringCommands =
+                    loadBalancerAgent.sendMessage(new CreateClusterDomainMessage(registrant.getService(),
+                                                                                 registrant.retrieveClusterDomain(),
+                                                                                 registrant.getHostName(),
+                                                                                 registrant.getTenantRange(),
+                                                                                 registrant.getMinInstanceCount(),
+                                                                                 registrant.getMaxInstanceCount(),
+                                                                                 registrant.getMaxRequestsPerSecond(),
+                                                                                 registrant.getRoundsToAverage(),
+                                                                                 registrant.getAlarmingUpperRate(),
+                                                                                 registrant.getAlarmingLowerRate(),
+                                                                                 registrant.getScaleDownFactor()),
+                                                  true);
+            if (clusteringCommands != null && !clusteringCommands.isEmpty()) {
+                for (ClusteringCommand clusteringCommand : clusteringCommands) {
+                    clusteringCommand.execute(configurationContext);
+                }
+            } else {
+                return;
+            }
+
+        } catch (ClusteringFault e) {
+            handleException("Cannot send CreateClusterDomainMessage to ELB", e);
+        }
+        ClusteringAgent agent;
+        try {
+            agent = createClusteringAgent(configurationContext,
+                                          registrant.retrieveClusterDomain());
+            
+        } catch (ClusteringFault e) {
+            handleException("Cannot create ClusteringAgent for registrant", e);
+            return;
+        }
+
+        //Add port.mapping.<port> entries to member
+        /*
+       <parameter name="properties">
+           <property name="port.mapping.8281" value="9768"/>
+           <property name="port.mapping.8244" value="9448"/>
+       </parameter>
+        */
+        Parameter propsParam = new Parameter();
+        propsParam.setName("properties");
+
+        StringBuilder propertiesPayload = new StringBuilder("<parameter name=\"properties\">");
+        int httpPort = -1;
+        int httpsPort = -1;
+        for (PortMapping portMapping : registrant.getPortMappings()) {
+            propertiesPayload.append("<property name=\"portMapping.mapping.").append(portMapping.getProxyPort()).
+                    append("\" value=\"").append(portMapping.getPrimaryPort()).append("\" />");
+            if (portMapping.getType().equals(PortMapping.PORT_TYPE_HTTP)) {
+                httpPort = portMapping.getPrimaryPort();
+            } else if (portMapping.getType().equals(PortMapping.PORT_TYPE_HTTPS)) {
+                httpsPort = portMapping.getPrimaryPort();
+            }
+        }
+
+        String remoteHost = registrant.getRemoteHost();
+        propertiesPayload.append("<property name=\"httpPort\" value=\"").append(httpPort).append("\" />");
+        propertiesPayload.append("<property name=\"httpsPort\" value=\"").append(httpsPort).append("\" />");
+        propertiesPayload.append("<property name=\"remoteHost\" value=\"").append(remoteHost).append("\" />");
+        propertiesPayload.append("<property name=\"subDomain\" value=\"__$default\" />");
+        propertiesPayload.append("</parameter>");
+
+        try {
+            StAXOMBuilder builder = new StAXOMBuilder(new ByteArrayInputStream(propertiesPayload.toString().getBytes()));
+            propsParam.setParameterElement(builder.getDocumentElement());
+            agent.addParameter(propsParam);
+        } catch (XMLStreamException e) {
+            handleException("Cannot create properties ClusteringAgent parameter", e);
+        } catch (AxisFault ignored) { // will not occur
+        }
+
+        int newMemberPort = Integer.parseInt(conf.getProperty("clustering.localMemberPort")) +
+                            RANDOM.nextInt(5000) + 27;
+        addParameter(agent, "localMemberPort", newMemberPort + "");
+        try {
+            synchronized (registrant) {
+                if(!registrant.running()) {
+                    registrant.start(agent);
+                }
+            }
+        } catch (ClusteringFault e) {
+            handleException("Cannot start registrant", e);
+        }
+        
+        // Update instance state in stratos database, with active
+        new Thread(new InstanceStateNotificationClientThread(registrant, "ACTIVE")).start();
+    }
+    
+    
+    public void removeClusterDomain(String domain,
+                                    String subDomain,
+                                    String hostName,
+                                    ConfigurationContext configurationContext) throws CartridgeAgentException {
+    	try {
+            List<ClusteringCommand> clusteringCommands =
+                    loadBalancerAgent.sendMessage(new CreateRemoveClusterDomainMessage(domain, subDomain, hostName),
+                                                  true);
+            if (clusteringCommands != null && !clusteringCommands.isEmpty()) {
+                for (ClusteringCommand clusteringCommand : clusteringCommands) {
+                    clusteringCommand.execute(configurationContext);
+                }
+            } else {
+                return;
+            }
+        } catch (ClusteringFault e) {
+            handleException("Cannot send CreateClusterDomainMessage to ELB", e);
+        }
+    }
+
+    private void handleException(String msg, Exception e) throws CartridgeAgentException {
+        log.error(msg, e);
+        throw new CartridgeAgentException(msg, e);
+    }
+
+    private ClusteringAgent createClusteringAgent(ConfigurationContext configurationContext,
+                                                  String clusterDomain) throws ClusteringFault {
+        TribesClusteringAgent agent = new TribesClusteringAgent();
+        addParameter(agent, "AvoidInitiation", "true");
+        for (String key : conf.stringPropertyNames()) {
+            if (key.startsWith("clustering.")) {
+                addParameter(agent,
+                             key.substring(key.indexOf(".") + 1),
+                             conf.getProperty(key));
+            }
+        }
+
+        List<Member> members = new ArrayList<Member>();
+        for (int i = 1; i < Integer.MAX_VALUE; i++) {
+            String host = conf.getProperty("members." + i + ".host");
+            String port = conf.getProperty("members." + i + ".port");
+            if (host == null || port == null) {
+                break;
+            }
+            members.add(new Member(host, Integer.parseInt(port)));
+        }
+        agent.setMembers(members);
+
+        addParameter(agent, "domain", clusterDomain);
+        agent.setConfigurationContext(configurationContext);
+
+        List<MembershipListener> membershipListeners = new ArrayList<MembershipListener>();
+        membershipListeners.add(new RegistrantMembershipListener(this, configurationContext));
+        agent.setMembershipListeners(membershipListeners);
+        return agent;
+    }
+
+    private static void addParameter(ClusteringAgent agent,
+                                     String paramName, String paramValue) {
+        Parameter parameter = new Parameter(paramName, paramValue);
+        try {
+            agent.removeParameter(parameter);
+            agent.addParameter(parameter);
+        } catch (AxisFault ignored) {
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/ELBMembershipListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/ELBMembershipListener.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/ELBMembershipListener.java
new file mode 100644
index 0000000..ca2cd96
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/ELBMembershipListener.java
@@ -0,0 +1,83 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent;
+
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.MembershipListener;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cartridge.agent.exception.CartridgeAgentException;
+import org.apache.stratos.cartridge.agent.registrant.RegistrantDatabase;
+import org.apache.stratos.cartridge.agent.registrant.RegistrantHealthChecker;
+import org.apache.stratos.cartridge.agent.registrant.RegistrantUtil;
+
+/**
+ * This membership listener will get notified when the Elastic Load Balancer (ELB) joins or
+ * leaves the cluster
+ *
+ * When the ELB leaves the cluster, we have to disconnect all Registrants, and when the ELB rejoins,
+ * we have to reconnect all the Registrants to the ELB
+ */
+public class ELBMembershipListener implements MembershipListener {
+    private static final Log log = LogFactory.getLog(ELBMembershipListener.class);
+
+    private ClusteringClient clusteringClient;
+    private ConfigurationContext configurationContext;
+    private RegistrantDatabase registrantDatabase;
+    private RegistrantHealthChecker healthChecker;
+
+    public ELBMembershipListener(ClusteringClient clusteringClient,
+                                 ConfigurationContext configurationContext,
+                                 RegistrantDatabase registrantDatabase,
+                                 RegistrantHealthChecker healthChecker) {
+        this.clusteringClient = clusteringClient;
+        this.configurationContext = configurationContext;
+        this.registrantDatabase = registrantDatabase;
+        this.healthChecker = healthChecker;
+    }
+
+    public void memberAdded(Member member, boolean b) {
+        log.info("ELB Member [" + member + "] joined cluster");
+        Runnable runnable = new Runnable() {
+            public void run() {
+                try {
+                    try {
+                        Thread.sleep(5000);
+                    } catch (InterruptedException ignored) {
+                    }
+                    RegistrantUtil.reloadRegistrants(clusteringClient,
+                                                     configurationContext,
+                                                     registrantDatabase);
+                    healthChecker.setELBRunning(true);
+                } catch (CartridgeAgentException e) {
+                    log.error("Could not reload registrants", e);
+                }
+            }
+        };
+        new Thread(runnable).start();
+    }
+
+    public void memberDisappeared(Member member, boolean b) {
+        log.info("ELB Member [" + member + "] left cluster");
+        healthChecker.setELBRunning(false);
+        registrantDatabase.stopAll();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/InstanceStateNotificationClientThread.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/InstanceStateNotificationClientThread.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/InstanceStateNotificationClientThread.java
new file mode 100644
index 0000000..8d3839d
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/InstanceStateNotificationClientThread.java
@@ -0,0 +1,63 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent;
+
+import org.apache.axis2.AxisFault;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cartridge.agent.registrant.Registrant;
+import org.wso2.carbon.adc.instanceinfo.mgt.stub.InstanceInformationManagementServiceStub;
+
+import java.rmi.RemoteException;
+
+public class InstanceStateNotificationClientThread implements Runnable {
+
+	private Registrant registrant;
+	private String state;
+
+	private static final Log log = LogFactory
+			.getLog(InstanceStateNotificationClientThread.class);
+
+	public InstanceStateNotificationClientThread(Registrant registrant,
+			String state) {
+		this.registrant = registrant;
+		this.state = state;
+	}
+
+	public void run() {
+		try {
+			log.info("Instance State is updated to " + state + " "
+					+ registrant.getRemoteHost());
+			String serviceURL = "https://" + System.getProperty("adc.host")
+					+ ":" + System.getProperty("adc.port")
+					+ "/services/InstanceInformationManagementService";
+			InstanceInformationManagementServiceStub stub = new InstanceInformationManagementServiceStub(
+					serviceURL);
+			stub.updateInstanceState(registrant.getRemoteHost(), 123,
+					registrant.retrieveClusterDomain(), "__$default",
+					registrant.getService(), state);
+		} catch (AxisFault e) {
+            log.warn("Error notifying state " + state + " of registrant " + registrant + " to ADC", e);
+		} catch (RemoteException e) {
+            log.warn("Error notifying state " + state + " of registrant " + registrant + " to ADC", e);
+		}
+
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/Main.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/Main.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/Main.java
new file mode 100644
index 0000000..f091e0b
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/Main.java
@@ -0,0 +1,158 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.engine.AxisServer;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cartridge.agent.internal.CartridgeAgentConstants;
+import org.apache.stratos.cartridge.agent.registrant.RegistrantDatabase;
+import org.apache.stratos.cartridge.agent.registrant.RegistrantHealthChecker;
+import org.apache.stratos.cartridge.agent.service.CartridgeAgentService;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Properties;
+
+/**
+ * The main class which starts up the Cartridge agent
+ */
+//public class Main {
+//    private static final Log log = LogFactory.getLog(Main.class);
+//    private static RegistrantHealthChecker healthChecker;
+//    public static void main(String[] args) {
+//        FileInputStream confFileIPStream = null;
+//        try {
+//            long start = System.currentTimeMillis();
+//            log.info("Starting WSO2 Cartridge Agent...");
+//            Properties conf = new Properties();
+//            confFileIPStream = new FileInputStream("conf" + File.separator + "agent.properties");
+//            conf.load(confFileIPStream);
+//            RegistrantDatabase registrantDatabase = new RegistrantDatabase();
+//            AxisServer axisServer = new AxisServer();
+//            ConfigurationContext configurationContext = axisServer.getConfigurationContext();
+//            ClusteringClient clusteringClient = new ClusteringClient(registrantDatabase);
+//            configurationContext.setProperty(CartridgeAgentConstants.CLUSTERING_CLIENT, clusteringClient);
+//            String healthCheckInterval = conf.getProperty("registrant.heathCheckInterval");
+//            String threadPoolSize = conf.getProperty("registrant.healthCheckThreadPoolSize");
+//            int healthCheckIntervalInt =
+//                    (healthCheckInterval == null) ? 2000 : Integer.parseInt(healthCheckInterval);
+//            int threadPoolSizeInt =
+//                    (threadPoolSize == null) ? 10 : Integer.parseInt(healthCheckInterval);
+//            log.info("Registrant health check interval: " + healthCheckIntervalInt + "s");
+//            healthChecker = new RegistrantHealthChecker(registrantDatabase,
+//                                                        clusteringClient,
+//                                                        configurationContext,
+//                                                        healthCheckIntervalInt,
+//                                                        threadPoolSizeInt
+//                                                        );
+//            clusteringClient.init(conf,
+//                                  configurationContext,
+//                                  new ELBMembershipListener(clusteringClient,
+//                                                            configurationContext,
+//                                                            registrantDatabase,
+//                                                            healthChecker));
+//            healthChecker.startAll();
+//            axisServer.deployService(CartridgeAgentService.class.getName());
+//
+//
+//            // Starting cliet..
+//            String trustStorePath = conf.getProperty("wso2.carbon.truststore");
+//            System.setProperty("javax.net.ssl.trustStore", trustStorePath);
+//            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
+//            // new InstanceStateNotificationClient().notify(null, null);
+//
+//            System.setProperty("adc.host",  conf.getProperty("adc.host"));
+//            System.setProperty("adc.port",  conf.getProperty("adc.port"));
+//            // ----------------------
+//
+//            writePID(".");
+//            Runtime.getRuntime().addShutdownHook(new Thread(){
+//
+//                @Override
+//                public void run() {
+//                    log.info("Shutting down WSO2 Cartridge Agent...");
+//                }
+//            });
+//            log.info("Started Cartridge Agent in " + (System.currentTimeMillis() - start) + "ms");
+//        } catch (Exception e) {
+//            log.fatal("Could not start Cartridge Agent", e);
+//            System.exit(1);
+//        } finally {
+//            if (confFileIPStream != null) {
+//                try {
+//                    confFileIPStream.close();
+//                } catch (IOException e) {
+//                    log.error("Cannot close agent.properties file", e);
+//                }
+//            }
+//        }
+//    }
+//
+//    public static RegistrantHealthChecker getHealthChecker(){
+//        return healthChecker;
+//    }
+//    /**
+//     * Write the process ID of this process to the file
+//     *
+//     * @param carbonHome carbon.home sys property value.
+//     */
+//    private static void writePID(String carbonHome) {
+//        byte[] bo = new byte[100];
+//        String[] cmd = {"bash", "-c", "echo $PPID"};
+//        Process p;
+//        try {
+//            p = Runtime.getRuntime().exec(cmd);
+//        } catch (IOException e) {
+//            //ignored. We might be invoking this on a Window platform. Therefore if an error occurs
+//            //we simply ignore the error.
+//            return;
+//        }
+//
+//        try {
+//            int bytes = p.getInputStream().read(bo);
+//        } catch (IOException e) {
+//            log.error(e.getMessage(), e);
+//        }
+//
+//        String pid = new String(bo);
+//        if (pid.length() != 0) {
+//            BufferedWriter out = null;
+//            try {
+//                FileWriter writer = new FileWriter(carbonHome + File.separator + "wso2carbon.pid");
+//                out = new BufferedWriter(writer);
+//                out.write(pid);
+//            } catch (IOException e) {
+//                log.warn("Cannot write wso2carbon.pid file");
+//            } finally {
+//                if (out != null) {
+//                    try {
+//                        out.close();
+//                    } catch (IOException ignored) {
+//                    }
+//                }
+//            }
+//        }
+//    }
+//}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/RegistrantMembershipListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/RegistrantMembershipListener.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/RegistrantMembershipListener.java
new file mode 100644
index 0000000..05ff859
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/RegistrantMembershipListener.java
@@ -0,0 +1,71 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent;
+
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.MembershipListener;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.cartridge.agent.registrant.Registrant;
+
+/**
+ * @author wso2
+ *
+ */
+public class RegistrantMembershipListener implements MembershipListener{
+	
+	private ClusteringClient clusteringClient;
+	private ConfigurationContext configurationContext;
+
+	private static final Log log = LogFactory.getLog(RegistrantMembershipListener.class);
+	
+	public RegistrantMembershipListener(ClusteringClient clusteringClient,
+	                                    ConfigurationContext configurationContext) {
+		this.clusteringClient = clusteringClient;
+		this.configurationContext = configurationContext;
+    }
+
+	public void memberAdded(Member arg0, boolean arg1) {
+	    log.info(" ********* Member is added to the group ... " + arg0);
+    }
+
+	public void memberDisappeared(Member member, boolean arg1) {
+		 log.info(" **********  Member is removed from group ... " + member);
+		 Registrant registrant = new Registrant();
+		 
+		 //HostName : cartridgeName + "." + cartridgeInfo.getHostName()
+		 // sajithphpautoscale.php.slive.com.php.domain
+		 //Domain : HostName.php.domain
+		 // TODO
+    		/* String hostName = getHostNameFromDomain(member.getDomain());
+    		 log.info("Host name is returned as: " + hostName);
+    		 try {
+    	        clusteringClient.removeClusterDomain(member.getDomain(), "__$default", hostName, configurationContext);
+            } catch (CartridgeAgentException e) {
+    	        e.printStackTrace();
+            }*/
+    }
+
+	private String getHostNameFromDomain(String domain) {
+	    return domain.substring(0, domain.length()-11);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/exception/CartridgeAgentException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/exception/CartridgeAgentException.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/exception/CartridgeAgentException.java
new file mode 100644
index 0000000..40e38e4
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/exception/CartridgeAgentException.java
@@ -0,0 +1,41 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.cartridge.agent.exception;
+
+/**
+ * CartridgeAgentException
+ */
+public class CartridgeAgentException extends Exception {
+    public CartridgeAgentException() {
+        super();
+    }
+
+    public CartridgeAgentException(String s) {
+        super(s);
+    }
+
+    public CartridgeAgentException(String s, Throwable throwable) {
+        super(s, throwable);
+    }
+
+    public CartridgeAgentException(Throwable throwable) {
+        super(throwable);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentConstants.java b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentConstants.java
new file mode 100644
index 0000000..2bd4a99
--- /dev/null
+++ b/components/org.apache.stratos.cartridge.agent/src/main/java/org/apache/stratos/cartridge/agent/internal/CartridgeAgentConstants.java
@@ -0,0 +1,28 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+
+package org.apache.stratos.cartridge.agent.internal;
+
+/**
+ * Constants used in the Cartridge Agent
+ */
+public final class CartridgeAgentConstants {
+    public static final String CLUSTERING_CLIENT = "clustering.client";
+}


[11/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
new file mode 100644
index 0000000..2945265
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
@@ -0,0 +1,531 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint.endpoint;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.util.AXIOMUtil;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.lb.endpoint.TenantAwareLoadBalanceEndpointException;
+import org.apache.stratos.lb.endpoint.internal.RegistryManager;
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.protocol.HTTP;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.SynapseConstants;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.config.xml.endpoints.utils.LoadbalanceAlgorithmFactory;
+import org.apache.synapse.core.LoadBalanceMembershipHandler;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
+import org.apache.synapse.endpoints.DynamicLoadbalanceFaultHandler;
+import org.apache.synapse.endpoints.Endpoint;
+import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
+import org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher;
+import org.apache.synapse.endpoints.dispatch.SALSessions;
+import org.apache.synapse.endpoints.dispatch.SessionInformation;
+import org.apache.synapse.transport.nhttp.NhttpConstants;
+import org.wso2.carbon.base.MultitenantConstants;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
+import org.apache.stratos.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
+import org.apache.stratos.lb.common.util.DomainMapping;
+import org.apache.stratos.lb.common.cache.URLMappingCache;
+import org.apache.stratos.lb.endpoint.TenantLoadBalanceMembershipHandler;
+
+public class TenantAwareLoadBalanceEndpoint extends org.apache.synapse.endpoints.DynamicLoadbalanceEndpoint implements Serializable {
+
+    private static final long serialVersionUID = 1577351815951789938L;
+    private static final Log log = LogFactory.getLog(TenantAwareLoadBalanceEndpoint.class);
+    /**
+     * Axis2 based membership handler which handles members in multiple clustering domains
+     */
+    private TenantLoadBalanceMembershipHandler tlbMembershipHandler;
+
+    /**
+     * Key - host name
+     * Value - {@link HostContext}
+     */
+    private Map<String, HostContext> hostContexts = new HashMap<String, HostContext>();
+
+    private LoadBalancerConfiguration lbConfig;
+
+    /**
+     * keep the size of cache which used to keep hostNames of url mapping.
+     */
+    private URLMappingCache mappingCache;
+    private RegistryManager registryManager;
+    private int sizeOfCache;
+
+    private boolean initialized;
+
+    private String algorithm;
+        private String configuration;
+        private String failOver;
+
+    @Override
+    public void init(SynapseEnvironment synapseEnvironment) {
+        try {
+
+            lbConfig = ConfigHolder.getInstance().getLbConfig();
+            hostContexts = lbConfig.getHostContextMap();
+            sizeOfCache = lbConfig.getLoadBalancerConfig().getSizeOfCache();
+            mappingCache = URLMappingCache.getInstance(sizeOfCache);
+            setSessionTimeout(lbConfig.getLoadBalancerConfig().getSessionTimeOut());
+            setFailover(lbConfig.getLoadBalancerConfig().getFailOver());
+
+        } catch (Exception e) {
+            String msg = "Failed while reading Load Balancer configuration";
+            log.error(msg, e);
+            throw new TenantAwareLoadBalanceEndpointException(msg, e);
+        }
+
+
+        LoadbalanceAlgorithm algorithm = null;
+        try {
+            OMElement payload = AXIOMUtil.stringToOM(generatePayLoad());
+            algorithm =
+                    LoadbalanceAlgorithmFactory.
+                            createLoadbalanceAlgorithm(payload, null);
+
+        } catch (Exception e) {
+            String msg = "Error While creating Load balance algorithm";
+            log.error(msg, e);
+            throw new SynapseException(msg, e);
+        }
+
+        if (!initialized) {
+            super.init(synapseEnvironment);
+            ConfigurationContext cfgCtx =
+                                          ((Axis2SynapseEnvironment) synapseEnvironment).getAxis2ConfigurationContext();
+            ClusteringAgent clusteringAgent = cfgCtx.getAxisConfiguration().getClusteringAgent();
+            if (clusteringAgent == null) {
+                throw new SynapseException("Axis2 ClusteringAgent not defined in axis2.xml");
+            }
+
+            // Add the Axis2 GroupManagement agents
+            if (hostContexts != null) {
+                // iterate through each host context
+                for (HostContext hostCtxt : hostContexts.values()) {
+                    // each host can has multiple Tenant Contexts, iterate through them
+                    for (TenantDomainContext tenantCtxt : hostCtxt.getTenantDomainContexts()) {
+
+                        String domain = tenantCtxt.getDomain();
+                        String subDomain = tenantCtxt.getSubDomain();
+
+                        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+                            String gmAgentClass = lbConfig.getLoadBalancerConfig().getGroupManagementAgentClass();
+                            GroupManagementAgent groupManagementAgent;
+                            if (gmAgentClass != null) {
+                                try {
+                                    groupManagementAgent = (GroupManagementAgent) Class.forName(gmAgentClass).newInstance();
+                                } catch (Exception e) {
+                                    String msg = "Cannot instantiate GroupManagementAgent. Class: " + gmAgentClass;
+                                    log.error(msg, e);
+                                    throw new TenantAwareLoadBalanceEndpointException(msg, e);
+                                }
+                            } else {
+                                groupManagementAgent = new SubDomainAwareGroupManagementAgent(subDomain);
+                            }
+                            clusteringAgent.addGroupManagementAgent(groupManagementAgent,
+                                                                    domain, subDomain,-1);
+                            if (log.isDebugEnabled()) {
+                                log.debug("Group management agent added to cluster domain: " +
+                                          domain + " and sub domain: " + subDomain);
+                            }
+                        }
+                    }
+                }
+
+                tlbMembershipHandler =
+                                       new TenantLoadBalanceMembershipHandler(hostContexts,
+                                                                              algorithm, cfgCtx,
+                                                                              isClusteringEnabled,
+                                                                              getName());
+
+                // set TenantLoadBalanceMembershipHandler for future reference
+                ConfigHolder.getInstance().setTenantLoadBalanceMembershipHandler(tlbMembershipHandler);
+            }
+
+            // Initialize the SAL Sessions if already has not been initialized.
+            SALSessions salSessions = SALSessions.getInstance();
+            if (!salSessions.isInitialized()) {
+                salSessions.initialize(isClusteringEnabled, cfgCtx);
+            }
+            setSessionAffinity(true);
+            setDispatcher(new HttpSessionDispatcher());
+            initialized = true;
+            log.info("Tenant Aware Load Balance Endpoint is initialized.");
+        }
+
+    }
+
+    	public void setConfiguration(String paramEle) {
+    	        configuration = paramEle;
+    	}
+
+    	    public void setAlgorithm(String paramEle) {
+    	        this.algorithm = paramEle;
+    	    }
+
+    	    public void setFailOver(String paramEle) {
+    	        this.failOver = paramEle;
+    	    }
+
+
+    public String getName() {
+		return "tlbEndpoint";
+	}
+
+    //TODO remove following hard coded element
+    private String generatePayLoad() {
+        return " <serviceDynamicLoadbalance failover=\"true\"\n" +
+                "                                           algorithm=\"org.apache.synapse.endpoints.algorithms.RoundRobin\"" +
+                //"                                           configuration=\"$system:loadbalancer.xml\"" +
+                "/>";
+    }
+
+    public LoadBalanceMembershipHandler getLbMembershipHandler() {
+        return tlbMembershipHandler;
+    }
+
+
+    public void send(MessageContext synCtx) {
+        /*   setCookieHeader(synCtx);     */
+        Member currentMember = null;
+        SessionInformation sessionInformation = null;
+        String actualHost = null;
+
+        //Gathering required information for domain mapping
+        org.apache.axis2.context.MessageContext axis2MessageContext =
+                                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+        Map<String, String> transportHeaders = (Map<String, String>) axis2MessageContext.
+                getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+        String targetHost = transportHeaders.get(HTTP.TARGET_HOST);
+
+        String port = "";
+        boolean containsPort = false;
+        if (targetHost.contains(":")) {
+            containsPort = true;
+            port = targetHost.substring(targetHost.indexOf(':') + 1, targetHost.length());
+            targetHost = targetHost.substring(0, targetHost.indexOf(':'));
+        }
+        //Gathering required information for domain mapping done
+
+        boolean isValidHost = tlbMembershipHandler.isAValidHostName(targetHost);
+        DomainMapping domainMapping = null;
+        if(!isValidHost){
+            //check if the host is valid, if not valid, execute following code to check whether it is a mapped domain
+            domainMapping = mappingCache.getMapping(targetHost);
+            if(domainMapping == null){
+                registryManager = new RegistryManager();
+                domainMapping = registryManager.getMapping(targetHost);
+                mappingCache.addValidMapping(targetHost, domainMapping);
+            }
+            if (domainMapping != null) {
+                actualHost = domainMapping.getActualHost();
+
+                if(containsPort){
+                    transportHeaders.put(HTTP.TARGET_HOST, actualHost + ":" + port);
+                } else {
+                    transportHeaders.put(HTTP.TARGET_HOST, actualHost);
+                }
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty("TRANSPORT_HEADERS" , transportHeaders);
+
+            } else {
+                String msg = "Invalid host name : " + targetHost;
+                log.error(msg);
+                throw new SynapseException(msg);
+            }
+        }
+
+        if (isSessionAffinityBasedLB()) {
+            // first check if this session is associated with a session. if so, get the endpoint
+            // associated for that session.
+            sessionInformation =
+                    (SessionInformation) synCtx.getProperty(
+                            SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
+
+            currentMember = (Member) synCtx.getProperty(
+                    SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER);
+
+            if (sessionInformation == null && currentMember == null) {
+                sessionInformation = dispatcher.getSession(synCtx);
+                if (sessionInformation != null) {
+
+                    if (log.isDebugEnabled()) {
+                        log.debug("Current session id : " + sessionInformation.getId());
+                    }
+
+                    currentMember = sessionInformation.getMember();
+                    synCtx.setProperty(
+                            SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
+                    // This is for reliably recovery any session information if while response is getting ,
+                    // session information has been removed by cleaner.
+                    // This will not be a cost as  session information a not heavy data structure
+                    synCtx.setProperty(
+                            SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION, sessionInformation);
+                }
+            }
+
+        }
+
+        // Dispatch request the relevant member
+//        String targetHost = getTargetHost(synCtx);
+        ConfigurationContext configCtx =
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext().getConfigurationContext();
+
+        if (tlbMembershipHandler.getConfigurationContext() == null) {
+            tlbMembershipHandler.setConfigurationContext(configCtx);
+        }
+
+        if(tlbMembershipHandler.getClusteringAgent() == null) {
+            tlbMembershipHandler.setConfigurationContext(configCtx);
+        }
+
+        TenantDynamicLoadBalanceFaultHandlerImpl faultHandler = new TenantDynamicLoadBalanceFaultHandlerImpl();
+        log.debug("************* Actual Host: "+actualHost +" ****** Target Host: "+targetHost);
+        faultHandler.setHost(actualHost != null ? actualHost : targetHost);
+
+        if (sessionInformation != null && currentMember != null) {
+            //send message on current session
+            sessionInformation.updateExpiryTime();
+            sendToApplicationMember(synCtx, currentMember, faultHandler, false);
+        } else {
+//            prepare for a new session
+            int tenantId = getTenantId(synCtx);
+            //check if this is a valid host name registered in ELB
+            if(tlbMembershipHandler.isAValidHostName(targetHost)){
+                currentMember = tlbMembershipHandler.getNextApplicationMember(targetHost, tenantId);
+                if (currentMember == null) {
+                    String msg = "No application members available";
+                    log.error(msg);
+                    throw new SynapseException(msg);
+                }
+                sendToApplicationMember(synCtx, currentMember, faultHandler, true);
+            } else {
+                if(domainMapping == null){
+                    registryManager = new RegistryManager();
+                    domainMapping = registryManager.getMapping(targetHost);
+                    mappingCache.addValidMapping(targetHost, domainMapping);
+                }
+                if(domainMapping != null) {
+
+                    actualHost = domainMapping.getActualHost();
+                    
+                    log.debug("************* Actual Host: "+actualHost +" ****** Target Host: "+targetHost);
+                    faultHandler.setHost(actualHost != null ? actualHost : targetHost);
+
+                    if(containsPort){
+                        transportHeaders.put(HTTP.TARGET_HOST, actualHost + ":" + port);
+                    } else {
+                        transportHeaders.put(HTTP.TARGET_HOST, actualHost);
+                    }
+                    ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty("TRANSPORT_HEADERS" , transportHeaders);
+
+                    currentMember = tlbMembershipHandler.getNextApplicationMember(actualHost,tenantId);
+                    sendToApplicationMember(synCtx,currentMember,faultHandler,true);
+                }else {
+                    String msg = "Invalid host name : " + targetHost;
+                    log.error(msg);
+                    throw new SynapseException(msg);
+                }
+            }
+        }
+    }
+
+
+//    public List<HostContext> getHostContexts() {
+//        return Collections.unmodifiableList(hostContexts);
+//    }
+
+    /**
+     * This FaultHandler will try to resend the message to another member if an error occurs
+     * while sending to some member. This is a failover mechanism
+     */
+
+    /**
+     * @param url to url for target
+     * @return tenantID if tenant id available else 0
+     */
+    private int getTenantId(String url) {
+        String servicesPrefix = "/t/";
+        if (url != null && url.contains(servicesPrefix)) {
+            int domainNameStartIndex =
+                    url.indexOf(servicesPrefix) + servicesPrefix.length();
+            int domainNameEndIndex = url.indexOf('/', domainNameStartIndex);
+            String domainName = url.substring(domainNameStartIndex,
+                    domainNameEndIndex == -1 ? url.length() : domainNameEndIndex);
+
+            // return tenant id if domain name is not null
+            if (domainName != null) {
+                try {
+                    return ConfigHolder.getInstance().getRealmService().getTenantManager().getTenantId(domainName);
+                } catch (org.wso2.carbon.user.api.UserStoreException e) {
+                    log.error("An error occurred while obtaining the tenant id.", e);
+                }
+            }
+        }
+        // return 0 if the domain name is null
+        return 0;
+    }
+
+    private int getTenantId(MessageContext synCtx){
+    	String url = synCtx.getTo().toString();
+    	int tenantId = getTenantId(url);
+    	// tenantId = 0 because domain name was null. May be this is the SSO response
+    	if(tenantId == 0 && url.contains(MultitenantConstants.TENANT_DOMAIN+"=")){
+    		// OK,this is the SAML SSO response from the IS
+    		// e.g url = https://localhost:9444/acs?teantDomain=domain
+    		String domainName = url.split("=").clone()[1];
+    		// return tenant id if domain name is not null
+            if (domainName != null) {
+                try {
+                    return ConfigHolder.getInstance().getRealmService().getTenantManager().getTenantId(domainName);
+                } catch (org.wso2.carbon.user.api.UserStoreException e) {
+                    log.error("An error occurred while obtaining the tenant id.", e);
+                }
+            }
+    	}
+    	return tenantId;
+    }
+
+
+    /**
+     * This FaultHandler will try to resend the message to another member if an error occurs
+     * while sending to some member. This is a failover mechanism
+     */
+    private class TenantDynamicLoadBalanceFaultHandlerImpl extends DynamicLoadbalanceFaultHandler {
+
+        private EndpointReference to;
+        private Member currentMember;
+        private Endpoint currentEp;
+        private String host;
+
+        private static final int MAX_RETRY_COUNT = 5;
+
+        // ThreadLocal variable to keep track of how many times this fault handler has been
+        // called
+        private ThreadLocal<Integer> callCount = new ThreadLocal<Integer>() {
+            protected Integer initialValue() {
+                return 0;
+            }
+        };
+
+        public void setHost(String host) {
+            log.debug("Setting host name: "+host);
+            this.host = host;
+        }
+
+        public void setCurrentMember(Member currentMember) {
+            this.currentMember = currentMember;
+        }
+
+        public void setTo(EndpointReference to) {
+            this.to = to;
+        }
+
+        private TenantDynamicLoadBalanceFaultHandlerImpl() {
+        }
+
+        public void onFault(MessageContext synCtx) {
+            if (currentMember == null || to == null) {
+                return;
+            }
+
+            // Prevent infinite retrying to failed members
+            callCount.set(callCount.get() + 1);
+            if (callCount.get() >= MAX_RETRY_COUNT) {
+                log.debug("Retrying to a failed member has stopped.");
+                return;
+            }
+
+            //cleanup endpoint if exists
+            if (currentEp != null) {
+                currentEp.destroy();
+            }
+            Integer errorCode = (Integer) synCtx.getProperty(SynapseConstants.ERROR_CODE);
+            if (errorCode != null) {
+                if (errorCode.equals(NhttpConstants.CONNECTION_FAILED)) {
+                    currentMember.suspend(10000);     // TODO: Make this configurable.
+                    log.info("Suspended member " + currentMember + " for 10s due to connection failure to that member");
+                }
+                if (errorCode.equals(NhttpConstants.CONNECTION_FAILED) ||
+                        errorCode.equals(NhttpConstants.CONNECT_CANCEL) ||
+                        errorCode.equals(NhttpConstants.CONNECT_TIMEOUT)) {
+                    
+                    if (!synCtx.getFaultStack().isEmpty()) {
+                        synCtx.getFaultStack().pop();
+                    }
+                    // Try to resend to another member
+                    Member newMember = tlbMembershipHandler.getNextApplicationMember(host, getTenantId(synCtx.toString()));
+                    if (newMember == null || newMember.isSuspended()) {
+                        String msg = "No application members available having host name : "+host+
+                                " and tenant id : "+getTenantId(synCtx.toString()+" and which is not suspended.");
+                        log.error(msg);
+                        throw new SynapseException(msg);
+                    }
+                    synCtx.setTo(to);
+                    if (isSessionAffinityBasedLB()) {
+                        // We are sending this message on a new session,
+                        // hence we need to remove previous session information
+                        Set pros = synCtx.getPropertyKeySet();
+                        if (pros != null) {
+                            pros.remove(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
+                        }
+                    }
+                    try {
+                        Thread.sleep(1000);  // Sleep for sometime before retrying
+                    } catch (InterruptedException ignored) {
+                    }
+                    
+                    if(synCtx == null || to == null) {
+                        return;
+                    }
+                    log.info("Failed over to " + newMember);
+                    sendToApplicationMember(synCtx, newMember, this, true);
+                } else if (errorCode.equals(NhttpConstants.SND_IO_ERROR_SENDING) ||
+                        errorCode.equals(NhttpConstants.CONNECTION_CLOSED)) {
+                    // TODO: Envelope is consumed
+                    String msg = "Error sending request! Connection to host "+host+
+                            " might be closed. Error code: "+errorCode;
+                    log.error(msg);
+                    throw new SynapseException(msg);
+                }
+            }
+            // We cannot failover since we are using binary relay
+        }
+
+        public void setCurrentEp(Endpoint currentEp) {
+            this.currentEp = currentEp;
+        }
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
new file mode 100644
index 0000000..cfd2bf8
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
@@ -0,0 +1,80 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint.group.mgt;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.stratos.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
+
+/**
+ * Responsible for building {@link GroupManagementAgent}s.
+ */
+public class GroupMgtAgentBuilder {
+    
+    private static final Log log = LogFactory.getLog(GroupMgtAgentBuilder.class);
+	
+    /**
+     * Creates a {@link SubDomainAwareGroupManagementAgent} corresponds to the given 
+     * parameters, if and only if there's no existing agent.
+     * @param domain clustering domain.
+     * @param subDomain clustering sub domain.
+     */
+    public static void createGroupMgtAgent(String domain, String subDomain) {
+
+        ClusteringAgent clusteringAgent =
+            ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
+        
+        if (clusteringAgent == null) {
+            throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
+        }
+
+        // checks the existence. 
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+            
+            clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(subDomain),
+                domain, subDomain,-1);
+            
+            log.info("Group management agent added to cluster domain: " +
+                domain + " and sub domain: " + subDomain);
+        }
+    }
+    
+    public static void resetGroupMgtAgent(String domain, String subDomain) {
+
+        ClusteringAgent clusteringAgent =
+            ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
+        
+        if (clusteringAgent == null) {
+            throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
+        }
+
+        // checks the existence. 
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) != null) {
+            
+            clusteringAgent.resetGroupManagementAgent(domain, subDomain);
+            
+            log.info("Group management agent of cluster domain: " +
+                domain + " and sub domain: " + subDomain+" is removed.");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
new file mode 100644
index 0000000..87bd8e8
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
@@ -0,0 +1,397 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.lb.endpoint.internal;
+
+import org.apache.axis2.deployment.DeploymentEngine;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.stratos.lb.endpoint.TenantAwareLoadBalanceEndpointException;
+import org.apache.stratos.lb.endpoint.builder.TopologySyncher;
+import org.apache.stratos.lb.endpoint.cluster.manager.ClusterDomainManagerImpl;
+import org.apache.stratos.lb.endpoint.endpoint.TenantAwareLoadBalanceEndpoint;
+import org.apache.stratos.lb.endpoint.subscriber.TopologySubscriber;
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.Mediator;
+import org.apache.synapse.config.SynapseConfiguration;
+import org.apache.synapse.config.xml.MultiXMLConfigurationBuilder;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.deployers.SynapseArtifactDeploymentStore;
+import org.apache.synapse.endpoints.Endpoint;
+import org.apache.synapse.mediators.base.SequenceMediator;
+import org.apache.synapse.mediators.builtin.SendMediator;
+import org.apache.synapse.mediators.filters.InMediator;
+import org.osgi.service.component.ComponentContext;
+import org.apache.stratos.cartridge.messages.CreateClusterDomainMessage;
+import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
+import org.wso2.carbon.mediation.initializer.ServiceBusConstants;
+import org.wso2.carbon.mediation.initializer.ServiceBusUtils;
+import org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService;
+import org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService;
+import org.wso2.carbon.mediation.initializer.services.SynapseRegistrationsService;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.apache.stratos.lb.endpoint.EndpointDeployer;
+import org.apache.stratos.lb.endpoint.util.TopologyConstants;
+
+import java.io.File;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @scr.component name="org.apache.stratos.load.balancer.endpoint" immediate="true"
+ * @scr.reference name="configuration.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
+ * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
+ * @scr.reference name="synapse.config.service"
+ * interface="org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService"
+ * cardinality="1..1" policy="dynamic" bind="setSynapseConfigurationService"
+ * unbind="unsetSynapseConfigurationService"
+ * @scr.reference name="synapse.env.service"
+ * interface="org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService"
+ * cardinality="1..n" policy="dynamic" bind="setSynapseEnvironmentService"
+ * unbind="unsetSynapseEnvironmentService"
+ * @scr.reference name="registry.service"
+ * interface="org.wso2.carbon.registry.core.service.RegistryService"
+ * cardinality="1..1" policy="dynamic"
+ * bind="setRegistryService" unbind="unsetRegistryService"
+ * @scr.reference name="dependency.mgt.service"
+ * interface="org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService"
+ * cardinality="0..1" policy="dynamic"
+ * bind="setDependencyManager" unbind="unsetDependencyManager"
+ * @scr.reference name="synapse.registrations.service"
+ * interface="org.wso2.carbon.mediation.initializer.services.SynapseRegistrationsService"
+ * cardinality="1..n" policy="dynamic" bind="setSynapseRegistrationsService"
+ * unbind="unsetSynapseRegistrationsService"
+ * @scr.reference name="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService"
+ * unbind="unsetRealmService"
+ * @scr.reference name="org.apache.stratos.lb.common"
+ * interface="org.apache.stratos.lb.common.service.LoadBalancerConfigurationService"
+ * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
+ * unbind="unsetLoadBalancerConfigurationService"
+ */
+@SuppressWarnings({"UnusedDeclaration", "JavaDoc"})
+public class LoadBalanceEndpointServiceComponent {
+
+    private static final Log log = LogFactory.getLog(LoadBalanceEndpointServiceComponent.class);
+
+    private boolean activated = false;
+
+    protected void activate(ComponentContext ctxt) {
+        try {
+            SynapseEnvironmentService synEnvService =
+                                                      ConfigHolder.getInstance()
+                                                                  .getSynapseEnvironmentService(MultitenantConstants.SUPER_TENANT_ID);
+
+            registerDeployer(ConfigHolder.getInstance().getAxisConfiguration(),
+                             synEnvService.getSynapseEnvironment());
+
+			      if (ConfigHolder.getInstance().getConfigCtxt() != null) {
+				      ConfigHolder
+						    .getInstance()
+						    .getConfigCtxt()
+						    .setNonReplicableProperty(
+								CreateClusterDomainMessage.CLUSTER_DOMAIN_MANAGER,
+								new ClusterDomainManagerImpl());
+				        log.debug("Setting property Cluster Domain MANAGER ... ");
+
+		  	    }
+			
+            SynapseEnvironment synapseEnv = synEnvService.getSynapseEnvironment();
+
+            /* Registering Tenant Aware Load Balance Endpoint */
+
+            // get the main sequence mediator
+            SequenceMediator mainSequence =
+                                            (SequenceMediator) synapseEnv.getSynapseConfiguration()
+                                                                         .getSequence("main");
+
+            boolean successfullyRegistered = false;
+            
+            // iterate through its child mediators
+            for (Mediator child : mainSequence.getList()) {
+
+                // find the InMediator
+                if (child instanceof InMediator) {
+                    
+                    for(Mediator inChild : ((InMediator)child).getList()){
+                        
+                        // find the SendMediator
+                        if (inChild instanceof SendMediator) {
+                            
+                            SendMediator sendMediator = (SendMediator) inChild;
+                            
+                            /* add Tenant Aware LB endpoint */
+                            
+                            TenantAwareLoadBalanceEndpoint tenantAwareEp = new TenantAwareLoadBalanceEndpoint();
+
+                            tenantAwareEp.init(synapseEnv);
+                            
+                            sendMediator.setEndpoint(tenantAwareEp);
+                            
+                            successfullyRegistered = true;
+
+                            if (log.isDebugEnabled()) {
+                                log.debug("Added Tenant Aware Endpoint: " +
+                                          sendMediator.getEndpoint().getName() + "" +
+                                          " to Send Mediator.");
+                            }
+                        }
+                    }
+                }
+            }
+            
+            if(!successfullyRegistered){
+                String msg = "Failed to register Tenant Aware Load Balance Endpoint in Send Mediator.";
+                log.fatal(msg);
+                throw new TenantAwareLoadBalanceEndpointException(msg);
+            }
+
+            if (log.isDebugEnabled()) {
+                log.debug("Endpoint Admin bundle is activated ");
+            }
+            
+            if (ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl() != null) {
+
+                // start consumer
+                // initialize TopologyBuilder Consumer
+                Thread topologyConsumer =
+                    new Thread(new TopologySyncher(ConfigHolder.getInstance().getSharedTopologyDiffQueue()));
+                // start consumer
+                topologyConsumer.start();
+
+                TopologySubscriber.subscribe(TopologyConstants.TOPIC_NAME);
+
+            }
+            activated = true;
+        } catch (Throwable e) {
+            log.error("Failed to activate Endpoint Admin bundle ", e);
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        try {
+            Set<Map.Entry<Integer, SynapseEnvironmentService>> entrySet =
+                    ConfigHolder.getInstance().getSynapseEnvironmentServices().entrySet();
+            for (Map.Entry<Integer, SynapseEnvironmentService> entry : entrySet) {
+                unregisterDeployer(
+                        entry.getValue().getConfigurationContext().getAxisConfiguration(),
+                        entry.getValue().getSynapseEnvironment());
+            }
+        } catch (Exception e) {
+            log.warn("Couldn't remove the EndpointDeployer");
+        }
+    }
+
+    /**
+     * Un-registers the Endpoint deployer.
+     *
+     * @param axisConfig         AxisConfiguration to which this deployer belongs
+     * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
+     */
+    private void unregisterDeployer(AxisConfiguration axisConfig, SynapseEnvironment synapseEnvironment)
+            throws TenantAwareLoadBalanceEndpointException {
+        if (axisConfig != null) {
+            DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig.getConfigurator();
+            String synapseConfigPath = ServiceBusUtils.getSynapseConfigAbsPath(
+                    synapseEnvironment.getServerContextInformation());
+            String endpointDirPath = synapseConfigPath
+                    + File.separator + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
+            deploymentEngine.removeDeployer(
+                    endpointDirPath, ServiceBusConstants.ARTIFACT_EXTENSION);
+        }
+    }
+
+    /**
+     * Registers the Endpoint deployer.
+     *
+     * @param axisConfig         AxisConfiguration to which this deployer belongs
+     * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
+     */
+    private void registerDeployer(AxisConfiguration axisConfig, SynapseEnvironment synapseEnvironment)
+            throws TenantAwareLoadBalanceEndpointException {
+        SynapseConfiguration synCfg = synapseEnvironment.getSynapseConfiguration();
+        DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig.getConfigurator();
+        SynapseArtifactDeploymentStore deploymentStore = synCfg.getArtifactDeploymentStore();
+
+        String synapseConfigPath = ServiceBusUtils.getSynapseConfigAbsPath(
+                synapseEnvironment.getServerContextInformation());
+        String endpointDirPath = synapseConfigPath
+                + File.separator + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
+
+        for (Endpoint ep : synCfg.getDefinedEndpoints().values()) {
+            if (ep.getFileName() != null) {
+                deploymentStore.addRestoredArtifact(
+                        endpointDirPath + File.separator + ep.getFileName());
+            }
+        }
+        deploymentEngine.addDeployer(
+                new EndpointDeployer(), endpointDirPath, ServiceBusConstants.ARTIFACT_EXTENSION);
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService cfgCtxService) {
+        ConfigHolder.getInstance().setAxisConfiguration(
+                cfgCtxService.getServerConfigContext().getAxisConfiguration());
+        ConfigHolder.getInstance().setConfigCtxt(cfgCtxService.getServerConfigContext());
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService cfgCtxService) {
+        ConfigHolder.getInstance().setAxisConfiguration(null);
+        ConfigHolder.getInstance().setConfigCtxt(null);
+    }
+
+    protected void setSynapseConfigurationService(
+            SynapseConfigurationService synapseConfigurationService) {
+
+        ConfigHolder.getInstance().setSynapseConfiguration(
+                synapseConfigurationService.getSynapseConfiguration());
+    }
+
+    protected void unsetSynapseConfigurationService(
+            SynapseConfigurationService synapseConfigurationService) {
+
+        ConfigHolder.getInstance().setSynapseConfiguration(null);
+    }
+
+    /**
+     * Here we receive an event about the creation of a SynapseEnvironment. If this is
+     * SuperTenant we have to wait until all the other constraints are met and actual
+     * initialization is done in the activate method. Otherwise we have to do the activation here.
+     *
+     * @param synapseEnvironmentService SynapseEnvironmentService which contains information
+     *                                  about the new Synapse Instance
+     */
+    protected void setSynapseEnvironmentService(
+            SynapseEnvironmentService synapseEnvironmentService) {
+        boolean alreadyCreated = ConfigHolder.getInstance().getSynapseEnvironmentServices().
+                containsKey(synapseEnvironmentService.getTenantId());
+
+        ConfigHolder.getInstance().addSynapseEnvironmentService(
+                synapseEnvironmentService.getTenantId(),
+                synapseEnvironmentService);
+        if (activated) {
+            if (!alreadyCreated) {
+                try {
+                    registerDeployer(synapseEnvironmentService.getConfigurationContext().getAxisConfiguration(),
+                            synapseEnvironmentService.getSynapseEnvironment());
+                    if (log.isDebugEnabled()) {
+                        log.debug("Endpoint Admin bundle is activated ");
+                    }
+                } catch (Throwable e) {
+                    log.error("Failed to activate Endpoint Admin bundle ", e);
+                }
+            }
+        }
+    }
+
+    /**
+     * Here we receive an event about Destroying a SynapseEnvironment. This can be the super tenant
+     * destruction or a tenant destruction.
+     *
+     * @param synapseEnvironmentService synapseEnvironment
+     */
+    protected void unsetSynapseEnvironmentService(
+            SynapseEnvironmentService synapseEnvironmentService) {
+        ConfigHolder.getInstance().removeSynapseEnvironmentService(
+                synapseEnvironmentService.getTenantId());
+    }
+
+    protected void setRegistryService(RegistryService regService) {
+        if (log.isDebugEnabled()) {
+            log.debug("RegistryService bound to the endpoint component");
+        }
+        try {
+            ConfigHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
+            ConfigHolder.getInstance().setGovernanceRegistry(regService.getGovernanceSystemRegistry());
+        } catch (RegistryException e) {
+            log.error("Couldn't retrieve the registry from the registry service");
+        }
+    }
+
+    protected void unsetRegistryService(RegistryService regService) {
+        if (log.isDebugEnabled()) {
+            log.debug("RegistryService unbound from the endpoint component");
+        }
+        ConfigHolder.getInstance().setConfigRegistry(null);
+    }
+
+    protected void setDependencyManager(DependencyManagementService dependencyMgr) {
+        if (log.isDebugEnabled()) {
+            log.debug("Dependency management service bound to the endpoint component");
+        }
+        ConfigHolder.getInstance().setDependencyManager(dependencyMgr);
+    }
+
+    protected void unsetDependencyManager(DependencyManagementService dependencyMgr) {
+        if (log.isDebugEnabled()) {
+            log.debug("Dependency management service unbound from the endpoint component");
+        }
+        ConfigHolder.getInstance().setDependencyManager(null);
+    }
+
+    protected void setSynapseRegistrationsService(
+            SynapseRegistrationsService synapseRegistrationsService) {
+
+    }
+
+    protected void unsetSynapseRegistrationsService(
+            SynapseRegistrationsService synapseRegistrationsService) {
+        int tenantId = synapseRegistrationsService.getTenantId();
+        if (ConfigHolder.getInstance().getSynapseEnvironmentServices().containsKey(tenantId)) {
+            SynapseEnvironment env = ConfigHolder.getInstance().
+                    getSynapseEnvironmentService(tenantId).getSynapseEnvironment();
+
+            ConfigHolder.getInstance().removeSynapseEnvironmentService(
+                    synapseRegistrationsService.getTenantId());
+
+            AxisConfiguration axisConfig = synapseRegistrationsService.getConfigurationContext().
+                    getAxisConfiguration();
+            if (axisConfig != null) {
+                try {
+                    unregisterDeployer(axisConfig, env);
+                } catch (Exception e) {
+                    log.warn("Couldn't remove the EndpointDeployer");
+                }
+            }
+        }
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        ConfigHolder.getInstance().setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        ConfigHolder.getInstance().setRealmService(null);
+    }
+    
+    protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        ConfigHolder.getInstance().setLbConfigService(lbConfigSer);
+    }
+    
+    protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        ConfigHolder.getInstance().setLbConfigService(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/RegistryManager.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/RegistryManager.java
new file mode 100644
index 0000000..2f91002
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/RegistryManager.java
@@ -0,0 +1,54 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.stratos.lb.common.util.DomainMapping;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+
+public class RegistryManager {
+    UserRegistry governanceRegistry = ConfigHolder.getInstance().getGovernanceRegistry();
+    private static final Log log = LogFactory.getLog(RegistryManager.class);
+    /**
+     *
+     */
+    private Resource resource = null;
+    public static final String HOST_INFO = "hostinfo/";
+    public static final String ACTUAL_HOST = "actual.host";
+
+    public DomainMapping getMapping(String hostName) {
+        DomainMapping domainMapping;
+        try {
+            if (governanceRegistry.resourceExists(HOST_INFO + hostName)) {
+                resource = governanceRegistry.get(HOST_INFO + hostName);
+                domainMapping = new DomainMapping(hostName);
+                domainMapping.setActualHost(resource.getProperty(ACTUAL_HOST));
+                return domainMapping;
+            }
+        } catch (RegistryException e) {
+            log.info("Error while getting registry resource");
+            throw new RuntimeException(e);
+        }
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopicHealthChecker.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopicHealthChecker.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopicHealthChecker.java
new file mode 100644
index 0000000..e9da865
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopicHealthChecker.java
@@ -0,0 +1,68 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint.subscriber;
+
+import javax.jms.TopicSubscriber;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * This health checker runs forever, and is responsible for re-establishing a connection
+ * between ELB and CC.
+ */
+public class TopicHealthChecker implements Runnable{
+    
+    private static final Log log = LogFactory.getLog(TopicHealthChecker.class);
+    private String topicName;
+    private TopicSubscriber subscriber;
+
+    public TopicHealthChecker(String topicName, TopicSubscriber subscriber) {
+        this.topicName = topicName;
+        this.subscriber = subscriber;
+    }
+    
+    @Override
+    public void run() {
+        log.info("Topic Health Checker is running... ");
+
+        while (true) {
+            try {
+                subscriber.getTopic();
+                
+                // health checker runs in every 30s
+                Thread.sleep(30000);
+
+            } catch (Exception e) {
+                // implies connection is not established
+                // sleep for 5s and retry
+                try {
+                    log.info("Health checker failed and will retry to establish a connection after a 5s.");
+                    Thread.sleep(5000);
+                    break;
+                } catch (InterruptedException ignore) {
+                }
+            }
+
+        }
+
+        TopologySubscriber.subscribe(topicName);
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologyListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologyListener.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologyListener.java
new file mode 100644
index 0000000..ee7a3ca
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologyListener.java
@@ -0,0 +1,47 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint.subscriber;
+
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageListener;
+import javax.jms.TextMessage;
+
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class TopologyListener implements MessageListener {
+
+	private static final Log log = LogFactory.getLog(TopologyListener.class);
+
+	@Override
+    public void onMessage(Message message) {
+		TextMessage receivedMessage = (TextMessage) message;
+        try {
+            
+            ConfigHolder.getInstance().getSharedTopologyDiffQueue().add(receivedMessage.getText());
+
+        } catch (JMSException e) {
+        	log.error(e.getMessage(), e);
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologySubscriber.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologySubscriber.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologySubscriber.java
new file mode 100644
index 0000000..0c127a1
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/subscriber/TopologySubscriber.java
@@ -0,0 +1,95 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint.subscriber;
+
+import java.util.Properties;
+
+import javax.jms.*;
+import javax.naming.InitialContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.stratos.lb.endpoint.util.TopologyConstants;
+
+public class TopologySubscriber {
+
+	private static final Log log = LogFactory.getLog(TopologySubscriber.class);
+	
+    public static void subscribe(String topicName) {
+        Properties initialContextProperties = new Properties();
+        TopicSubscriber topicSubscriber = null;
+        TopicSession topicSession = null;
+        TopicConnection topicConnection = null;
+        InitialContext initialContext = null;
+
+        initialContextProperties.put("java.naming.factory.initial",
+            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");
+
+        String mbServerUrl = null;
+        if (ConfigHolder.getInstance().getLbConfig() != null) {
+            mbServerUrl = ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl();
+        }
+        String connectionString =
+            "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" +
+                (mbServerUrl == null ? TopologyConstants.DEFAULT_MB_SERVER_URL : mbServerUrl) + "'&reconnect='true'";
+        initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);
+
+        try {
+            initialContext = new InitialContext(initialContextProperties);
+            TopicConnectionFactory topicConnectionFactory =
+                (TopicConnectionFactory) initialContext.lookup("qpidConnectionfactory");
+            topicConnection = topicConnectionFactory.createTopicConnection();
+            topicConnection.start();
+            topicSession =
+                topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Topic topic = topicSession.createTopic(topicName);
+            topicSubscriber =
+                topicSession.createSubscriber(topic);
+
+            topicSubscriber.setMessageListener(new TopologyListener());
+
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+
+            try {
+                if (topicSubscriber != null) {
+                    topicSubscriber.close();
+                }
+
+                if (topicSession != null) {
+                    topicSession.close();
+                }
+
+                if (topicConnection != null) {
+                    topicConnection.close();
+                }
+            } catch (JMSException e1) {
+                // ignore
+            }
+
+        } 
+        finally {
+            // start the health checker
+            Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
+            healthChecker.start();
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/util/ConfigHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/util/ConfigHolder.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/util/ConfigHolder.java
new file mode 100644
index 0000000..3817579
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/util/ConfigHolder.java
@@ -0,0 +1,192 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.lb.endpoint.util;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.config.SynapseConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+import org.apache.stratos.lb.endpoint.TenantAwareLoadBalanceEndpointException;
+import org.apache.stratos.lb.endpoint.TenantLoadBalanceMembershipHandler;
+import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
+import org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.service.RealmService;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+
+/**
+ *
+ */
+public class ConfigHolder {
+
+    private static ConfigHolder instance;
+    private static final Log log = LogFactory.getLog(ConfigHolder.class);
+
+    private SynapseConfiguration synapseConfiguration;
+    private ConfigurationContext configCtxt;
+    private AxisConfiguration axisConfiguration;
+    private UserRegistry configRegistry;
+    private UserRegistry governanceRegistry;
+    private DependencyManagementService dependencyManager;
+    private TenantLoadBalanceMembershipHandler tenantMembershipHandler;
+    private LoadBalancerConfigurationService lbConfigService;
+    private BlockingQueue<String> sharedTopologyQueue = new LinkedBlockingQueue<String>();
+    private String previousMsg;
+    
+
+    private Map<Integer, SynapseEnvironmentService> synapseEnvironmentServices =
+            new HashMap<Integer, SynapseEnvironmentService>();
+
+    public RealmService getRealmService() {
+        return realmService;
+    }
+
+    public void setRealmService(RealmService realmService) {
+        this.realmService = realmService;
+    }
+
+    private RealmService realmService;
+
+    private ConfigHolder() {
+    }
+
+    public static ConfigHolder getInstance() {
+        if (instance == null) {
+            instance = new ConfigHolder();
+        }
+        return instance;
+    }
+
+    public SynapseConfiguration getSynapseConfiguration() throws TenantAwareLoadBalanceEndpointException{
+        assertNull("SynapseConfiguration", synapseConfiguration);
+        return synapseConfiguration;
+    }
+
+    public void setSynapseConfiguration(SynapseConfiguration synapseConfiguration) {
+        this.synapseConfiguration = synapseConfiguration;
+    }
+
+    public AxisConfiguration getAxisConfiguration() throws TenantAwareLoadBalanceEndpointException {
+        assertNull("AxisConfiguration", axisConfiguration);
+        return axisConfiguration;
+    }
+
+    public void setAxisConfiguration(AxisConfiguration axisConfiguration) {
+        this.axisConfiguration = axisConfiguration;
+    }
+
+    public UserRegistry getConfigRegistry() throws TenantAwareLoadBalanceEndpointException {
+        assertNull("Registry", configRegistry);
+        return configRegistry;
+    }
+
+    public void setConfigRegistry(UserRegistry configRegistry) {
+        this.configRegistry = configRegistry;
+    }
+
+    public DependencyManagementService getDependencyManager() {
+        return dependencyManager;
+    }
+
+    public void setDependencyManager(DependencyManagementService dependencyManager) {
+        this.dependencyManager = dependencyManager;
+    }
+
+    private void assertNull(String name, Object object) throws TenantAwareLoadBalanceEndpointException {
+        if (object == null) {
+            String message = name + " reference in the proxy admin config holder is null";
+            log.error(message);
+            throw new TenantAwareLoadBalanceEndpointException(message);
+        }
+    }
+
+    public UserRegistry getGovernanceRegistry() {
+        return governanceRegistry;
+    }
+
+    public void setGovernanceRegistry(UserRegistry governanceRegistry) {
+        this.governanceRegistry = governanceRegistry;
+    }
+
+    public SynapseEnvironmentService getSynapseEnvironmentService(int id) {
+        return synapseEnvironmentServices.get(id);
+    }
+
+    public void addSynapseEnvironmentService(int id,
+                                             SynapseEnvironmentService synapseEnvironmentService) {
+        synapseEnvironmentServices.put(id, synapseEnvironmentService);
+    }
+
+    public void removeSynapseEnvironmentService(int id) {
+        synapseEnvironmentServices.remove(id);
+    }
+
+    public Map<Integer, SynapseEnvironmentService> getSynapseEnvironmentServices() {
+        return synapseEnvironmentServices;
+    }
+    
+    public void setTenantLoadBalanceMembershipHandler(TenantLoadBalanceMembershipHandler handler) {
+        tenantMembershipHandler = handler;
+    }
+    
+    public TenantLoadBalanceMembershipHandler getTenantLoadBalanceMembershipHandler() {
+        return tenantMembershipHandler;
+    }
+
+    public ConfigurationContext getConfigCtxt() {
+        return configCtxt;
+    }
+
+    public void setConfigCtxt(ConfigurationContext configCtxt) {
+        this.configCtxt = configCtxt;
+    }
+    
+    public void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
+        this.lbConfigService = lbConfigSer;
+    }
+
+    public LoadBalancerConfiguration getLbConfig() {
+        return (LoadBalancerConfiguration) lbConfigService.getLoadBalancerConfig();
+    }
+
+	public BlockingQueue<String> getSharedTopologyDiffQueue() {
+	    return sharedTopologyQueue;
+    }
+
+	public void setSharedTopologyDiffQueue(BlockingQueue<String> sharedTopologyDiffQueue) {
+	    this.sharedTopologyQueue = sharedTopologyDiffQueue;
+    }
+
+	public String getPreviousMsg() {
+	    return previousMsg;
+    }
+
+	public void setPreviousMsg(String previousMsg) {
+	    this.previousMsg = previousMsg;
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/util/TopologyConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/util/TopologyConstants.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/util/TopologyConstants.java
new file mode 100644
index 0000000..970e4b9
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/util/TopologyConstants.java
@@ -0,0 +1,31 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint.util;
+
+public class TopologyConstants {
+    
+    public static final String TOPIC_NAME = "cloud-controller-topology";
+    public static final String MB_SERVER_URL = "mb.server.ip";
+    public static final String DEFAULT_MB_SERVER_URL = "localhost:5672";
+    
+    public static final String TOPOLOGY_SYNC_CRON = "1 * * * * ? *";
+	public static final String TOPOLOGY_SYNC_TASK_NAME = "TopologySubscriberTaskOfADC";
+	public static final String TOPOLOGY_SYNC_TASK_TYPE = "TOPOLOGY_SUBSCRIBER_TASK";
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.load.balance.agent/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balance.agent/2.1.0/pom.xml b/components/org.apache.stratos.load.balance.agent/2.1.0/pom.xml
deleted file mode 100644
index f29ff76..0000000
--- a/components/org.apache.stratos.load.balance.agent/2.1.0/pom.xml
+++ /dev/null
@@ -1,76 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Licensed to the Apache Software Foundation (ASF) under one
-  ~ or more contributor license agreements. See the NOTICE file
-  ~ distributed with this work for additional information
-  ~ regarding copyright ownership. The ASF licenses this file
-  ~ to you under the Apache License, Version 2.0 (the
-  ~ "License"); you may not use this file except in compliance
-  ~ with the License. You may obtain a copy of the License at
-  ~
-  ~ http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~ Unless required by applicable law or agreed to in writing,
-  ~ software distributed under the License is distributed on an
-  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-  ~ KIND, either express or implied. See the License for the
-  ~ specific language governing permissions and limitations
-  ~ under the License.
-  -->
-        
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-   <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../../pom.xml</relativePath>
-    </parent>   
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.load.balance.agent</artifactId>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Load Balance Agent</name>
-    <description>
-        Load Balance Agent - Facilitates Getting the System Properties for Load Balancing and Auto Scaling
-    </description>
-    <url>http://wso2.org</url>
-
-    <build>
-        <plugins>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-surefire-plugin</artifactId>
-                <version>2.2</version>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-Vendor>WSO2 Inc</Bundle-Vendor>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Export-Package>
-                            org.apache.stratos.load.balance.agent.*,
-                        </Export-Package>
-                        <Import-Package>
-                             *;resolution:=optional
-                        </Import-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-   <dependencies>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.stratos.common</artifactId>
-            <version>2.1.0</version>
-        </dependency>
-    </dependencies>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.load.balance.agent/2.1.0/src/main/java/org/apache/stratos/load/balance/agent/LoadBalanceAgentService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balance.agent/2.1.0/src/main/java/org/apache/stratos/load/balance/agent/LoadBalanceAgentService.java b/components/org.apache.stratos.load.balance.agent/2.1.0/src/main/java/org/apache/stratos/load/balance/agent/LoadBalanceAgentService.java
deleted file mode 100644
index 441eeb9..0000000
--- a/components/org.apache.stratos.load.balance.agent/2.1.0/src/main/java/org/apache/stratos/load/balance/agent/LoadBalanceAgentService.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.load.balance.agent;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.lang.management.ManagementFactory;
-
-/**
- * Agent to get the system properties of the instances. Hence will be used in auto scaling, and
- * also potentially in load balancing. Instances will be scaling up and down based on these params.
- */
-public class LoadBalanceAgentService {
-
-    private static final Log log = LogFactory.getLog(LoadBalanceAgentService.class);
-
-
-    /**
-     * gets the load average of the system
-     *
-     * @return load average. Returns zero if the load average couldn't be read.
-     * Zero is treated as load-average not read, in the relevant places and ignored in the
-     * load balancer and autoscalar algorithms appropriately.
-     */
-    public double getLoadAverage() {
-        double systemLoadAverage = 0;
-        try {
-            systemLoadAverage =
-                    ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
-        } catch (Exception e) {
-            if (log.isDebugEnabled()) {
-                log.debug("Error in retrieving the load average of the instance");
-            }
-        }
-        return systemLoadAverage;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.load.balance.agent/2.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balance.agent/2.1.0/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.load.balance.agent/2.1.0/src/main/resources/META-INF/services.xml
deleted file mode 100644
index 02d6052..0000000
--- a/components/org.apache.stratos.load.balance.agent/2.1.0/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- !
- ! Copyright 2006 The Apache Software Foundation.
- !
- ! Licensed under the Apache License, Version 2.0 (the "License");
- ! you may not use this file except in compliance with the License.
- ! You may obtain a copy of the License at
- !
- !      http://www.apache.org/licenses/LICENSE-2.0
- !
- ! Unless required by applicable law or agreed to in writing, software
- ! distributed under the License is distributed on an "AS IS" BASIS,
- ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ! See the License for the specific language governing permissions and
- ! limitations under the License.
- !-->
-<serviceGroup>
-    <service name="LoadBalanceAgentService" scope="transportsession">
-        <transports>
-            <transport>https</transport>
-        </transports>
-        <parameter name="ServiceClass" locked="false">
-            org.apache.stratos.load.balance.agent.LoadBalanceAgentService
-        </parameter>
-        <operation name="getLoadAverage"/>
-    </service>
-    <parameter name="hiddenService" locked="true">true</parameter>
-</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.load.balance.agent/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balance.agent/pom.xml b/components/org.apache.stratos.load.balance.agent/pom.xml
new file mode 100644
index 0000000..ec5a408
--- /dev/null
+++ b/components/org.apache.stratos.load.balance.agent/pom.xml
@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.  
+-->
+        
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+   <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>   
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.load.balance.agent</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Load Balance Agent</name>
+    <description>
+        Load Balance Agent - Facilitates Getting the System Properties for Load Balancing and Auto Scaling
+    </description>
+    <url>http://apache.org</url>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <version>2.2</version>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Export-Package>
+                            org.apache.stratos.load.balance.agent.*,
+                        </Export-Package>
+                        <Import-Package>
+                             *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+   <dependencies>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+            <version>${apache.stratos.version}</version>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.load.balance.agent/src/main/java/org/apache/stratos/load/balance/agent/LoadBalanceAgentService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balance.agent/src/main/java/org/apache/stratos/load/balance/agent/LoadBalanceAgentService.java b/components/org.apache.stratos.load.balance.agent/src/main/java/org/apache/stratos/load/balance/agent/LoadBalanceAgentService.java
new file mode 100644
index 0000000..441eeb9
--- /dev/null
+++ b/components/org.apache.stratos.load.balance.agent/src/main/java/org/apache/stratos/load/balance/agent/LoadBalanceAgentService.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balance.agent;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.lang.management.ManagementFactory;
+
+/**
+ * Agent to get the system properties of the instances. Hence will be used in auto scaling, and
+ * also potentially in load balancing. Instances will be scaling up and down based on these params.
+ */
+public class LoadBalanceAgentService {
+
+    private static final Log log = LogFactory.getLog(LoadBalanceAgentService.class);
+
+
+    /**
+     * gets the load average of the system
+     *
+     * @return load average. Returns zero if the load average couldn't be read.
+     * Zero is treated as load-average not read, in the relevant places and ignored in the
+     * load balancer and autoscalar algorithms appropriately.
+     */
+    public double getLoadAverage() {
+        double systemLoadAverage = 0;
+        try {
+            systemLoadAverage =
+                    ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
+        } catch (Exception e) {
+            if (log.isDebugEnabled()) {
+                log.debug("Error in retrieving the load average of the instance");
+            }
+        }
+        return systemLoadAverage;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.load.balance.agent/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balance.agent/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.load.balance.agent/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..02d6052
--- /dev/null
+++ b/components/org.apache.stratos.load.balance.agent/src/main/resources/META-INF/services.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ !
+ ! Copyright 2006 The Apache Software Foundation.
+ !
+ ! Licensed under the Apache License, Version 2.0 (the "License");
+ ! you may not use this file except in compliance with the License.
+ ! You may obtain a copy of the License at
+ !
+ !      http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing, software
+ ! distributed under the License is distributed on an "AS IS" BASIS,
+ ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ! See the License for the specific language governing permissions and
+ ! limitations under the License.
+ !-->
+<serviceGroup>
+    <service name="LoadBalanceAgentService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.apache.stratos.load.balance.agent.LoadBalanceAgentService
+        </parameter>
+        <operation name="getLoadAverage"/>
+    </service>
+    <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>


[32/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/ApplicationManagementService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/ApplicationManagementService.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/ApplicationManagementService.java
deleted file mode 100644
index c977bc4..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/ApplicationManagementService.java
+++ /dev/null
@@ -1,620 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.service;
-
-import org.apache.axis2.AxisFault;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.custom.domain.RegistryManager;
-import org.apache.stratos.adc.mgt.dao.CartridgeSubscription;
-import org.apache.stratos.adc.mgt.dns.DNSManager;
-import org.apache.stratos.adc.mgt.dto.Cartridge;
-import org.apache.stratos.adc.mgt.dto.CartridgeWrapper;
-import org.apache.stratos.adc.mgt.dto.PolicyDefinition;
-import org.apache.stratos.adc.mgt.dto.RepositoryInformation;
-import org.apache.stratos.adc.mgt.dto.SubscriptionInfo;
-import org.apache.stratos.adc.mgt.exception.*;
-import org.apache.stratos.adc.mgt.internal.DataHolder;
-import org.apache.stratos.adc.mgt.utils.*;
-import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
-import org.wso2.carbon.context.PrivilegedCarbonContext;
-import org.wso2.carbon.core.AbstractAdmin;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.apache.stratos.cloud.controller.util.xsd.CartridgeInfo;
-import org.wso2.carbon.utils.DataPaginator;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.regex.Pattern;
-
-/**
- *
- *
- *
- */
-public class ApplicationManagementService extends AbstractAdmin {
-
-
-    private static final Log log = LogFactory.getLog(ApplicationManagementService.class);
-    RegistryManager registryManager = new RegistryManager();
-
-    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
-    String tenantDomain = carbonContext.getTenantDomain();
-    
-    /*
-     * Instantiate RepoNotificationService. Since this service is in the same 
-     * component (org.apache.stratos.adc.mgt), a new object is created.
-     * TODO: Is there a better way to get this service?
-     */
-    private RepoNotificationService repoNotificationService = new RepoNotificationService();
-
-	/**
-	 * Get Available Cartridges
-	 * 
-	 * @return Available Cartridges
-	 */
-	public Cartridge[] getAvailableCartridges(boolean multiTenant) throws ADCException {
-		List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant);
-		// Following is very important when working with axis2
-		return cartridges.isEmpty() ? new Cartridge[0] : cartridges.toArray(new Cartridge[cartridges.size()]);
-	}
-
-	/**
-	 * Get Subscribed Cartridges
-	 * 
-	 * @return Subscribed Cartridges
-	 */
-	public Cartridge[] getSubscribedCartridges() throws ADCException {
-		checkSuperTenant();
-		List<Cartridge> cartridgeList = getSubscribedCartridges(null);
-		// Following is very important when working with axis2
-		return cartridgeList.isEmpty() ? new Cartridge[0] : cartridgeList.toArray(new Cartridge[cartridgeList.size()]);
-	}
-
-	/**
-	 * Get available cartridges
-	 */
-	public CartridgeWrapper getPagedAvailableCartridges(String cartridgeSearchString, int pageNumber, boolean multiTenant)
-			throws ADCException {
-		checkSuperTenant();
-		CartridgeWrapper cartridgeWrapper = new CartridgeWrapper();
-		List<Cartridge> cartridges = getAvailableCartridges(cartridgeSearchString, multiTenant);
-    	
-		// TODO Improve pagination
-		if (!cartridges.isEmpty()) {
-			// Paginate only if cartridges are there.
-			DataPaginator.doPaging(pageNumber, cartridges, cartridgeWrapper);
-		} else {
-			// Must set this value as axis2 stub client will return an array
-			// with length = 1 and null element if cartridges[] is null
-			cartridgeWrapper.set(cartridges);
-		}
-		return cartridgeWrapper;
-	}
-
-	private List<Cartridge> getAvailableCartridges(String cartridgeSearchString, Boolean multiTenant) throws ADCException {
-		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 = ApplicationManagementUtil.getServiceClient().getRegisteredCartridges();
-
-			if (availableCartridges != null) {
-				for (String cartridgeType : availableCartridges) {
-					CartridgeInfo cartridgeInfo = null;
-					try {
-						cartridgeInfo = ApplicationManagementUtil.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 (!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.setStatus(CartridgeConstants.NOT_SUBSCRIBED);
-					cartridge.setCartridgeAlias("-");
-					cartridge.setActiveInstances(0);
-					cartridges.add(cartridge);
-					
-					if (cartridgeInfo.getMultiTenant() && !allowMultipleSubscription) {
-						// If the cartridge is multi-tenant. We should not let users
-						// subscribe twice.
-						if (PersistenceManager.isAlreadySubscribed(cartridgeType,
-								ApplicationManagementUtil.getTenantId(getConfigContext()))) {
-							if (log.isDebugEnabled()) {
-								log.debug("Already subscribed to " + cartridgeType
-										+ ". This multi-tenant cartridge will not be available to subscribe");
-							}
-							cartridge.setStatus(CartridgeConstants.SUBSCRIBED);
-						}
-					}
-				}
-			} else {
-				if (log.isDebugEnabled()) {
-					log.debug("There are no available cartridges");
-				}
-			}
-		} catch (Exception e) {
-			String msg = "Error when getting available cartridges. " + e.getMessage();
-			log.error(msg, e);
-			throw new ADCException("An error occurred getting available cartridges ", e);
-		}
-
-		Collections.sort(cartridges);
-
-		if (log.isDebugEnabled()) {
-			log.debug("Returning available cartridges " + cartridges.size());
-		}
-
-		return cartridges;
-	}
-
-	/**
-	 * Get subscribed cartridges
-	 */
-	public CartridgeWrapper getPagedSubscribedCartridges(String cartridgeSearchString, int pageNumber)
-			throws ADCException {
-		checkSuperTenant();
-		CartridgeWrapper cartridgeWrapper = new CartridgeWrapper();
-		List<Cartridge> cartridges = getSubscribedCartridges(cartridgeSearchString);
-
-		// TODO Improve pagination
-		if (!cartridges.isEmpty()) {
-			// Paginate only if cartridges are there.
-			DataPaginator.doPaging(pageNumber, cartridges, cartridgeWrapper);
-		} else {
-			cartridgeWrapper.set(cartridges);
-		}
-		return cartridgeWrapper;
-	}
-
-	private List<Cartridge> getSubscribedCartridges(String cartridgeSearchString) throws ADCException {
-		List<Cartridge> cartridges = new ArrayList<Cartridge>();
-		
-		if (log.isDebugEnabled()) {
-			log.debug("Getting subscribed cartridges. Search String: " + cartridgeSearchString);
-		}
-
-		try {
-			Pattern searchPattern = getSearchStringPattern(cartridgeSearchString);
-
-			List<CartridgeSubscription> subscriptionList = PersistenceManager
-					.retrieveSubscribedCartridges(ApplicationManagementUtil.getTenantId(getConfigContext()));
-
-			if (subscriptionList != null && !subscriptionList.isEmpty()) {
-				for (CartridgeSubscription subscription : subscriptionList) {
-					CartridgeInfo cartridgeInfo = null;
-					try {
-						cartridgeInfo = ApplicationManagementUtil.getServiceClient().getCartridgeInfo(
-								subscription.getCartridge());
-					} catch (Exception e) {
-						if (log.isWarnEnabled()) {
-							log.warn("Error when calling getCartridgeInfo for " + subscription.getCartridge()
-									+ ", Error: " + e.getMessage());
-						}
-					}
-					if (cartridgeInfo == null) {
-						// This cannot happen. But continue
-						if (log.isDebugEnabled()) {
-							log.debug("Cartridge Info not found: " + subscription.getCartridge());
-						}
-						continue;
-					}
-					if (!cartridgeMatches(cartridgeInfo, subscription, searchPattern)) {
-						continue;
-					}
-					TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
-					String[] ips = topologyMgtService.getActiveIPs(subscription.getCartridge(),
-							subscription.getClusterDomain(), subscription.getClusterSubdomain());
-					Cartridge cartridge = ApplicationManagementUtil.populateCartridgeInfo(cartridgeInfo, subscription, ips, tenantDomain);
-					cartridges.add(cartridge);
-				}
-			} else {
-				if (log.isDebugEnabled()) {
-					log.debug("There are no subscribed cartridges");
-				}
-			}
-		} catch (Exception e) {
-			String msg = "Error when getting subscribed cartridges. " + e.getMessage();
-			log.error(msg, e);
-			throw new ADCException("An Error occurred when getting subscribed cartridges.", e);
-		}
-
-		Collections.sort(cartridges);
-
-		if (log.isDebugEnabled()) {
-			log.debug("Returning subscribed cartridges " + cartridges.size());
-		}
-
-		return cartridges;
-	}
-
-    private 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;
-    }
-
-    // TODO: Improve search method
-    private 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 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.getCartridge() != null) {
-                matches = pattern.matcher(cartridgeSubscription.getCartridge().toLowerCase()).find();
-            }
-            if (!matches && cartridgeSubscription.getAlias() != null) {
-                matches = pattern.matcher(cartridgeSubscription.getAlias().toLowerCase()).find();
-            }
-            return matches;
-        }
-        return true;
-    }
-    
-    public Cartridge getCartridgeInfo(String alias) throws ADCException, NotSubscribedException {
-    	checkSuperTenant();
-    	return ApplicationManagementUtil.getCartridgeInfo(alias, getTenantDomain());
-    }
-
-    public String[] getSubscribedCartridgeAliases() throws AxisFault {
-        try {
-            List<CartridgeSubscription> subscriptionList = PersistenceManager
-                    .retrieveSubscribedCartridges(ApplicationManagementUtil.getTenantId(getConfigContext()));
-            List<String> subscribedAliases = new ArrayList<String>();
-            for (CartridgeSubscription cartridgeSubscription : subscriptionList) {
-
-                if(cartridgeSubscription.getProvider().equalsIgnoreCase(CartridgeConstants.PROVIDER_NAME_WSO2) &&
-                        getCartridgeInfo(cartridgeSubscription.getAlias()).isMultiTenant()) {
-
-                    subscribedAliases.add(cartridgeSubscription.getCartridge());
-                } else {
-                    subscribedAliases.add(cartridgeSubscription.getAlias());
-                }
-            }
-            if(subscribedAliases.size() == 0) {
-                return new String[]{""};
-            } else {
-                return subscribedAliases.toArray(new String[subscribedAliases.size()]);
-            }
-
-        } catch (Exception e) {
-            String msg = "Exception in getting subscribed cartridge aliases :" + e.getMessage();
-            log.error(msg, e);
-            throw new AxisFault("An error occurred while getting subscribed cartridge aliases", e);
-        }
-    }
-    
-	public PolicyDefinition[] getPolicyDefinitions() {
-		List<PolicyDefinition> policyDefinitions = PolicyHolder.getInstance().getPolicyDefinitions();
-		return policyDefinitions == null || policyDefinitions.isEmpty() ? new PolicyDefinition[0] : policyDefinitions
-				.toArray(new PolicyDefinition[policyDefinitions.size()]);
-	}
-
-	/**
-	 * Subscribe to a cartridge
-	 */
-	public SubscriptionInfo subscribe(String cartridgeType, String alias, String policy, String repoURL,
-			boolean privateRepo, String repoUsername, String repoPassword, String dataCartridgeType,
-			String dataCartridgeAlias) throws ADCException, PolicyException, UnregisteredCartridgeException,
-            InvalidCartridgeAliasException, DuplicateCartridgeAliasException, RepositoryRequiredException,
-            AlreadySubscribedException, RepositoryCredentialsRequiredException, InvalidRepositoryException,
-            RepositoryTransportException {
-
-		checkSuperTenant();
-
-		return ApplicationManagementUtil.doSubscribe(cartridgeType, alias, policy, repoURL, privateRepo, repoUsername,
-				repoPassword, dataCartridgeType, dataCartridgeAlias, getUsername(),
-				ApplicationManagementUtil.getTenantId(getConfigContext()), getTenantDomain());
-
-	}
-
-
-    /**
-     * Unsubscribing the cartridge
-     *
-     * @param alias name of the cartridge to be unsubscribed
-     */
-    public void unsubscribe(String alias) throws ADCException, NotSubscribedException {
-    	checkSuperTenant();
-        CartridgeSubscription subscription = null;
-        
-        try {
-			subscription = PersistenceManager.getSubscription(tenantDomain, alias);
-		} catch (Exception e) {
-			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + alias;
-            log.error(msg, e);
-			throw new ADCException(msg, e);
-		}
-
-        if (subscription == null) {
-            String msg = "Tenant " + tenantDomain + " is not subscribed for " + alias;
-            log.error(msg);
-            throw new NotSubscribedException("You have not subscribed for " + alias, alias);
-        }
-        
-        try {
-            String clusterDomain = subscription.getClusterDomain();
-            String clusterSubDomain = subscription.getClusterSubdomain();
-
-            if (log.isDebugEnabled()) {
-                log.debug("Finding cartridge information for " + subscription.getCartridge());
-            }
-            CartridgeInfo cartridgeInfo = ApplicationManagementUtil.getServiceClient().getCartridgeInfo(subscription.getCartridge());
-            if (log.isDebugEnabled()) {
-                log.debug("Found " + cartridgeInfo.getDisplayName() + " for " + subscription.getCartridge());
-            }
-            if (!cartridgeInfo.getMultiTenant()) {
-                log.info("Terminating all instances of " + clusterDomain + " " + clusterSubDomain);
-                ApplicationManagementUtil.getServiceClient().terminateAllInstances(clusterDomain, clusterSubDomain);
-                log.info("All instances terminated.");
-                log.info("Unregistering services...");
-                ApplicationManagementUtil.getServiceClient().unregisterService(clusterDomain, clusterSubDomain);
-                log.info("Successfully terminated instances ..");
-            } else {
-                if (log.isInfoEnabled()) {
-                    log.info("Cartridge "
-                            + subscription.getCartridge()
-                            + " is a multi-tenant cartridge and therefore will not terminate all instances and unregister services");
-                }
-            }
-
-            new RepositoryFactory().destroyRepository(alias, tenantDomain, getUsername());
-            log.info("Repo is destroyed successfully.. ");
-
-            PersistenceManager.updateSubscriptionState(subscription.getSubscriptionId(), "UNSUBSCRIBED");
-            new DNSManager().removeSubDomain(subscription.getHostName());
-            registryManager.removeDomainMappingFromRegistry(subscription.getHostName());
-            TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
-			
-            String[] ips = topologyMgtService.getActiveIPs(subscription.getCartridge(),
-					subscription.getClusterDomain(), subscription.getClusterSubdomain());
-            PersistenceManager.updateInstanceState("INACTIVE", ips, subscription.getClusterDomain(), subscription.getClusterSubdomain(), subscription.getCartridge());
-
-        } catch (ADCException e) {
-        	log.error(e.getMessage(), e);
-        	throw e;
-        } catch (Exception e1) {
-            String msg1 = "Exception occurred :" + e1.getMessage();
-            log.error(msg1);
-            throw new ADCException("Unsubscribe failed for cartridge " + alias, e1);
-        }
-    }
-
-
-    public String addDomainMapping(String mappedDomain, String cartridgeAlias) throws ADCException, DomainMappingExistsException, NotSubscribedException {
-    	checkSuperTenant();
-    	// TODO Following was in CLI. Fix this
-		//		if (domain.indexOf('.') == -1) {
-		//			System.out.println("\nOwn domain should include a '.' ");
-		//		}
-
-        CartridgeSubscription subscription = null;
-        String actualHost = null;
-        
-        try {
-			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
-		} catch (Exception e) {
-			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + cartridgeAlias;
-            log.error(msg, e);
-			throw new ADCException(msg, e);
-		}
-        if (subscription == null) {
-        	String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
-            log.error(msg);
-            throw new NotSubscribedException("You have not subscribed for " + cartridgeAlias, cartridgeAlias);
-        }
-
-        try {
-        	actualHost = getActualHost(cartridgeAlias);
-            registryManager.addDomainMappingToRegistry(mappedDomain, actualHost);
-            log.info("Domain mapping is added for " + mappedDomain + " tenant: " + tenantDomain);
-            PersistenceManager.updateDomainMapping(
-                    ApplicationManagementUtil.getTenantId(getConfigContext()), cartridgeAlias, mappedDomain);
-        } catch (RegistryException e) {
-            String msg = "Unable to add the mapping due to registry transaction error";
-            log.error(msg, e);
-            throw new ADCException("Unable to add the mapping due to internal error!", e);
-        } catch (DomainMappingExistsException e) {
-            String msg = "Domain mapping already exists.";
-            log.error(msg, e);
-            throw e;
-        } catch (Exception e) {
-            String msg = "Error occurred. Reason : " + e.getMessage();
-            log.error(msg, e);
-            throw new ADCException(msg, e);
-        }
-        return actualHost;
-    }
-
-	private String getActualHost(String cartridgeName) throws Exception {
-		return PersistenceManager.getHostNameForCartridgeName(
-				ApplicationManagementUtil.getTenantId(getConfigContext()), cartridgeName);
-	}
-
-    public void removeDomainMapping(String cartridgeAlias) throws ADCException, NotSubscribedException {
-    	checkSuperTenant();
-        CartridgeSubscription subscription = null;
-        String actualHost = null;
-        
-        try {
-			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
-		} catch (Exception e) {
-			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + cartridgeAlias;
-            log.error(msg, e);
-			throw new ADCException(msg, e);
-		}
-        if (subscription == null) {
-        	String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
-            log.error(msg);
-            throw new NotSubscribedException("You have not subscribed for " + cartridgeAlias, cartridgeAlias);
-        }
-        
-        try {
-        	actualHost = getActualHost(cartridgeAlias);
-            registryManager.removeDomainMappingFromRegistry(actualHost);
-            log.info("Domain mapping is removed for " + actualHost + " tenant: " + tenantDomain);
-            PersistenceManager.updateDomainMapping(ApplicationManagementUtil.getTenantId(getConfigContext()),
-                    cartridgeAlias, null);
-        } catch (RegistryException e) {
-            String msg = "Unable to remove the mapping due to registry transaction error";
-            log.error(msg, e);
-            throw new ADCException("Unable to remove the mapping due to internal error!", e);
-        } catch (Exception e) {
-            String msg = "Error occurred. Reason : " + e.getMessage();
-            log.error(msg, e);
-            throw new ADCException(msg, e);
-        }
-    }
-
-	public void synchronizeRepository(String cartridgeAlias) throws ADCException, NotSubscribedException {
-		checkSuperTenant();
-        CartridgeSubscription subscription = null;
-        
-        // Validating subscription
-        try {
-			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
-		} catch (Exception e) {
-			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + cartridgeAlias;
-            log.error(msg, e);
-			throw new ADCException(msg, e);
-		}
-        if (subscription == null) {
-        	String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
-            log.error(msg);
-            throw new NotSubscribedException("You have not subscribed for " + cartridgeAlias, cartridgeAlias);
-        }
-		
-		try {
-			repoNotificationService.notifyRepoUpdate(tenantDomain, cartridgeAlias);
-		} catch (Exception e) {
-			throw new ADCException(e.getMessage() != null ? e.getMessage() : "Failed to synchronize repository", e);
-		}
-	}
-
-    /**
-     * Validate authentication.
-     * First call of cli tool in the prompt mode after log in.
-     *
-     * @return The tenant domain
-     */
-	public String getTenantDomain() {
-		if (tenantDomain != null) {
-			// This means, authentication is successful
-			log.info("Tenant " + tenantDomain + " is authorized to access Application Management Service!");
-		}
-		return tenantDomain;
-	}
-    
-	/**
-	 * Allow to check whether features are enabled in the back-end
-	 * 
-	 * @param key
-	 *            The propery key
-	 * @return {@code true} if feature is enabled
-	 */
-	public boolean isFeatureEnabled(String key) {
-		if (key != null && key.startsWith("feature.")) {
-			return new Boolean(System.getProperty(key));
-		}
-		return false;
-	}
-
-	
-	public RepositoryInformation testRepositoryConnection(String repoURL, String repoUsername, String repoPassword, boolean privateRepo)
-			throws RepositoryRequiredException, ADCException, RepositoryCredentialsRequiredException,
-			InvalidRepositoryException, RepositoryTransportException {
-		return ApplicationManagementUtil.validateRepository(repoURL, repoUsername, repoPassword, privateRepo, true);
-	}
-	
-	// TODO Remove following when we support cartridge subscription for Super-tenant
-	private void checkSuperTenant() throws ADCException {
-		if (log.isDebugEnabled()) {
-			log.debug("Checking whether super tenant accesses the service methods. Tenant ID: "
-					+ ApplicationManagementUtil.getTenantId(getConfigContext()) + ", Tenant Domain: " + carbonContext.getTenantDomain());
-		}
-		if (MultitenantConstants.SUPER_TENANT_ID == ApplicationManagementUtil.getTenantId(getConfigContext())) {
-			throw new ADCException("Super Tenant is not allowed to complete requested operation");
-		}
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/InstanceInformationManagementService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/InstanceInformationManagementService.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/InstanceInformationManagementService.java
deleted file mode 100644
index 692dafa..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/InstanceInformationManagementService.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.service;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.utils.PersistenceManager;
-
-public class InstanceInformationManagementService {
-
-	
-    private static final Log log = LogFactory.getLog(InstanceInformationManagementService.class);
-
-    /**
-    * Everytime an instance is started up, this operation is invoked
-    *            (by the AgentService)
-    * @param instanceIp
-    * @param tenantId
-    * @param clusterDomain
-    * @param clusterSubDomain
-    * @param cartridge
-    * @param state
-    *
-    */
-    public void updateInstanceState(String instanceIp,
-                                  int tenantId,
-                                  String clusterDomain,
-                                  String clusterSubDomain,
-                                  String cartridge,
-                                  String state) {
-
-      log.info("Message receieved in Instance Info Service.." + instanceIp + tenantId + clusterDomain + clusterSubDomain
-               + cartridge + state);
-
-      try {
-        PersistenceManager.persistCartridgeInstanceInfo(instanceIp, clusterDomain, clusterSubDomain, cartridge, state);
-    } catch (Exception e) {
-       log.error("Exception is occurred in updating instance state. Reason, " + e.getMessage());
-    }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java
deleted file mode 100644
index b26e885..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.service;
-
-import java.io.File;
-import java.util.List;
-import java.util.UUID;
-
-import org.apache.axis2.clustering.ClusteringAgent;
-import org.apache.axis2.clustering.ClusteringFault;
-import org.apache.axis2.clustering.management.GroupManagementAgent;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.dao.CartridgeSubscription;
-import org.apache.stratos.adc.mgt.internal.DataHolder;
-import org.apache.stratos.adc.mgt.utils.CartridgeConstants;
-import org.apache.stratos.adc.mgt.utils.PersistenceManager;
-import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
-import org.wso2.carbon.core.deployment.SynchronizeGitRepositoryRequest;
-import org.wso2.carbon.utils.CarbonUtils;
-
-
-public class RepoNotificationService {
-
-	private static final Log log = LogFactory.getLog(RepoNotificationService.class);
-	
-
-	public void notifyRepoUpdate(String tenantDomain, String cartridgeAlias) throws Exception {
-		// FIXME Throwing generic Exception is wrong
-		log.info("Updating repository of tenant : " + tenantDomain + " , cartridge: " +
-				cartridgeAlias);
-
-		CartridgeSubscription subscription = null;
-		try {
-			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
-		} catch (Exception e) {
-			String msg = "Failed to find subscription for " + cartridgeAlias + ". "
-					+ (e.getMessage() != null ? e.getMessage() : "");
-			log.error(msg, e);
-			throw new Exception(msg, e);
-		}
-		
-		if (subscription == null) {
-			String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
-			log.error(msg);
-			throw new Exception("You have not subscribed for " + cartridgeAlias);
-		}
-		
-		try {
-			handleRepoSynch(subscription);
-		} catch (Exception e) {
-			String msg = "Failed to synchronize the repository for " + cartridgeAlias + ". "
-					+ (e.getMessage() != null ? e.getMessage() : "");
-			log.error(msg, e);
-			throw new Exception(msg, e);
-		}
-		
-	}
-
-	public void synchronize(String repositoryURL) throws Exception {
-
-		log.info(" repository URL received : " + repositoryURL);
-		List<CartridgeSubscription> subscription = PersistenceManager.getSubscription(repositoryURL);
-		for (CartridgeSubscription cartridgeSubscription : subscription) {			
-			handleRepoSynch(cartridgeSubscription);   
-        }
-	}
-
-	private void handleRepoSynch(CartridgeSubscription subscription) throws Exception {
-		if (subscription == null) {
-			throw new Exception("Cannot synchronize repository. subscription is null");
-		}
-
-		if (CartridgeConstants.PROVIDER_NAME_WSO2.equals(subscription.getProvider())) {
-			log.info(" wso2 cartridge.. ");
-			createAndSendClusterMessage(subscription.getTenantId(), subscription.getTenantDomain(),
-			                            UUID.randomUUID(), subscription.getClusterDomain(),
-			                            subscription.getClusterSubdomain());
-			//for manager node
-			           /* if (subscription.getMgtClusterSubDomain() != null && !subscription.getMgtClusterSubDomain().isEmpty()) {
-			                createAndSendClusterMessage(subscription.getTenantId(), subscription.getTenantDomain(),
-			                        UUID.randomUUID(), subscription.getMgtClusterDomain(),
-			                        subscription.getMgtClusterSubDomain());
-			            }
-			            else {
-			                if(log.isDebugEnabled())
-			                    log.debug("Manager node cluster information not found, not sending the SynchronizeGitRepositoryRequest");
-			            }*/
-
-		} else {
-
-			// Query DB and get all the IP s for this tenant 
-			// Invoke update-instance script
-			
-			String appPath = subscription.getBaseDirectory();
-			String cartridgePrivateKey = System.getProperty(CartridgeConstants.CARTRIDGE_KEY);
-			
-			File keyFile = new File(cartridgePrivateKey);
-			if (!keyFile.exists()) {
-				log.error("The key file does not exist! " + cartridgePrivateKey);
-			}
-
-			if (subscription != null) {
-				TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
-
-				
-				if (topologyMgtService == null) {
-					String msg = " Topology Management Service is null ";
-					log.error(msg);
-					throw new Exception(msg);
-				}
-
-				String[] activeIpArray =
-				                         topologyMgtService.getActiveIPs(subscription.getCartridge(),
-				                                                         subscription.getClusterDomain(),
-				                                                         subscription.getClusterSubdomain());
-				try {
-
-					for (String instanceIp : activeIpArray) {
-						String command =
-						                 CarbonUtils.getCarbonHome() + File.separator + "bin" +
-						                         File.separator + "update-instance.sh " +
-						                         instanceIp + " " + appPath + " " +
-						                         cartridgePrivateKey + " /";
-						log.info("Update instance command.... " + command);
-						Process proc = Runtime.getRuntime().exec(command);
-						proc.waitFor();
-					}
-
-				} catch (Exception e) {
-					log.error("Exception is occurred in notify update operation. Reason : " +
-					          e.getMessage());
-					throw e;
-				}
-			}
-		}
-	}
-
-	private void createAndSendClusterMessage(int tenantId, String tenantDomain, UUID uuid,
-	                                         String clusterDomain, String clusterSubdomain) {
-
-		SynchronizeGitRepositoryRequest request =
-		                                          new SynchronizeGitRepositoryRequest(tenantId,
-		                                                                              tenantDomain,
-		                                                                              uuid);
-
-		ClusteringAgent clusteringAgent =
-		                                  DataHolder.getServerConfigContext()
-		                                            .getAxisConfiguration().getClusteringAgent();
-		GroupManagementAgent groupMgtAgent =
-		                                     clusteringAgent.getGroupManagementAgent(clusterDomain,
-		                                                                             clusterSubdomain);
-
-		try {
-			log.info("Sending Request to.. " + clusterDomain + " : " + clusterSubdomain);
-			groupMgtAgent.send(request);
-			
-		} catch (ClusteringFault e) {
-			e.printStackTrace();
-		}
-		 
-
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInfoBean.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInfoBean.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInfoBean.java
deleted file mode 100644
index 7a6380c..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInfoBean.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * 
- */
-package org.apache.stratos.adc.mgt.service;
-
-import org.apache.stratos.cloud.controller.util.xsd.CartridgeInfo;
-
-/**
- * @author wso2
- *
- */
-public class RepositoryInfoBean {
-
-	private String repoURL;
-	private String cartridgeAlias;
-	private String tenantDomain;
-	private String userName;
-	private String password;
-	private String[] dirArray;
-	private CartridgeInfo cartridgeInfo;	
-	
-	
-	public RepositoryInfoBean(String repoURL, String cartridgeAlias, String tenantDomain,
-                              String userName, String password, String[] dirArray, CartridgeInfo cartridgeInfo) {
-	    this.repoURL = repoURL;
-	    this.cartridgeAlias = cartridgeAlias;
-	    this.tenantDomain = tenantDomain;
-	    this.userName = userName;
-	    this.setPassword(password);
-	    this.dirArray = dirArray;
-	    this.cartridgeInfo = cartridgeInfo;
-    }
-	public String getRepoURL() {
-    	return repoURL;
-    }
-	public void setRepoURL(String repoURL) {
-    	this.repoURL = repoURL;
-    }
-	public String getCartridgeAlias() {
-    	return cartridgeAlias;
-    }
-	public void setCartridgeAlias(String cartridgeAlias) {
-    	this.cartridgeAlias = cartridgeAlias;
-    }
-	public String getTenantDomain() {
-    	return tenantDomain;
-    }
-	public void setTenantDomain(String tenantDomain) {
-    	this.tenantDomain = tenantDomain;
-    }
-	public String getUserName() {
-    	return userName;
-    }
-	public void setUserName(String userName) {
-    	this.userName = userName;
-    }
-	public String[] getDirArray() {
-    	return dirArray;
-    }
-	public void setDirArray(String[] dirArray) {
-    	this.dirArray = dirArray;
-    }
-	public CartridgeInfo getCartridgeInfo() {
-    	return cartridgeInfo;
-    }
-	public void setCartridgeInfo(CartridgeInfo cartridgeInfo) {
-    	this.cartridgeInfo = cartridgeInfo;
-    }
-    public String getPassword() {
-        return password;
-    }
-    public void setPassword(String password) {
-        this.password = password;
-    }
-	
-	
-	
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInformationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInformationService.java b/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInformationService.java
deleted file mode 100644
index ad7db58..0000000
--- a/components/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInformationService.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright WSO2, Inc. (http://wso2.com)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.stratos.adc.mgt.service;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.adc.mgt.dao.RepositoryCredentials;
-import org.apache.stratos.adc.mgt.utils.PersistenceManager;
-
-/**
- * 
- * Exposes information related to internally created repositories  
- * 
- */
-public class RepositoryInformationService {
-
-	private static final Log log = LogFactory.getLog(RepositoryInformationService.class);
-
-	public String getRepositoryUrl(int tenantId, String cartridgeType) throws Exception {
-
-		String repoUrl = null;
-		try {
-			repoUrl = PersistenceManager.getRepoURL(tenantId, cartridgeType);
-		} catch (Exception e) {
-			String msg = "System Exception is occurred when retriving repo URL";
-			log.error(msg + ". Reason :" + e.getMessage());
-			throw new Exception(msg);
-		}
-		if (repoUrl == null) {
-			log.error("Repository URL is not successfully retrieved " + "for tenant [" + tenantId +
-			          "] and cartridge [" + cartridgeType + "] ");
-		}
-		return repoUrl;
-	}
-
-    public RepositoryCredentials getRepositoryCredentials(int tenantId, String cartridgeType, String alias) throws Exception {
-
-    	RepositoryCredentials repoCredentials = null;
-        try {
-        	repoCredentials = PersistenceManager.getRepoCredentials(tenantId,cartridgeType, alias);
-        } catch (Exception e) {
-            String msg = "System Exception is occurred when retrieving user credentials";
-            log.error(msg + ". Reason :" + e.getMessage());
-            throw new Exception(msg);
-        }
-        if (repoCredentials == null) {
-            log.error("Repository credentials are not successfully retrieved " + "for tenant [" + tenantId +
-                    "] and cartridge [" + cartridgeType + "] ");
-        }
-        return repoCredentials;
-    }
-}


[15/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreGenerator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreGenerator.java b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreGenerator.java
new file mode 100644
index 0000000..b8e892e
--- /dev/null
+++ b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreGenerator.java
@@ -0,0 +1,229 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.keystore.mgt;
+
+import org.apache.axiom.om.util.UUIDGenerator;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.bouncycastle.jce.X509Principal;
+import org.bouncycastle.jce.X509V3CertificateGenerator;
+import org.wso2.carbon.core.RegistryResources;
+import org.wso2.carbon.core.util.CryptoUtil;
+import org.apache.stratos.keystore.mgt.util.RealmServiceHolder;
+import org.apache.stratos.keystore.mgt.util.RegistryServiceHolder;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.security.SecurityConstants;
+import org.wso2.carbon.security.keystore.KeyStoreAdmin;
+import org.wso2.carbon.user.core.service.RealmService;
+
+import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.security.cert.X509Certificate;
+import java.util.Date;
+
+/**
+ * This class is used to generate a key store for a tenant and store it in the governance registry.
+ */
+public class KeyStoreGenerator {
+
+    private static Log log = LogFactory.getLog(KeyStoreGenerator.class);
+    private UserRegistry govRegistry;
+    private int tenantId;
+    private String tenantDomain;
+    private String password;
+
+
+    public KeyStoreGenerator(int  tenantId) throws KeyStoreMgtException {
+        try {
+            this.tenantId = tenantId;
+            this.tenantDomain = getTenantDomainName();
+            this.govRegistry = RegistryServiceHolder.getRegistryService().
+                    getGovernanceSystemRegistry(tenantId);
+            if(govRegistry == null){
+                log.error("Governance registry instance is null");
+                throw new KeyStoreMgtException("Governance registry instance is null");
+            }
+        } catch (RegistryException e) {
+            String errorMsg = "Error while obtaining the governance registry for tenant : " +
+                      tenantId;
+            log.error(errorMsg, e);
+            throw new KeyStoreMgtException(errorMsg, e);
+        }
+    }
+
+
+    /**
+     * This method first generates the keystore, then persist it in the gov.registry of that tenant
+     *
+     * @throws KeyStoreMgtException Error when generating or storing the keystore
+     */
+    public void generateKeyStore() throws KeyStoreMgtException {
+        try {
+            password = generatePassword();
+            KeyStore keyStore = KeyStore.getInstance("JKS");
+            keyStore.load(null, password.toCharArray());
+            X509Certificate pubCert = generateKeyPair(keyStore);
+            persistKeyStore(keyStore, pubCert);
+        } catch (Exception e) {
+            String msg = "Error while instantiating a keystore";
+            log.error(msg, e);
+            throw new KeyStoreMgtException(msg, e);
+        }
+    }
+
+    /**
+     * This method generates the keypair and stores it in the keystore
+     *
+     * @param keyStore A keystore instance
+     * @return Generated public key for the tenant
+     * @throws KeyStoreMgtException Error when generating key pair
+     */
+    private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException {
+        try {
+            CryptoUtil.getDefaultCryptoUtil();
+            //generate key pair
+            KeyPairGenerator keyPairGenerator = null;
+            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
+            keyPairGenerator.initialize(1024);
+            KeyPair keyPair = keyPairGenerator.generateKeyPair();
+
+            // Common Name and alias for the generated certificate
+            String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None";
+
+            //generate certificates
+            X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
+            v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()));
+            v3CertGen.setIssuerDN(new X509Principal(commonName));
+            v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
+            v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
+            v3CertGen.setSubjectDN(new X509Principal(commonName));
+            v3CertGen.setPublicKey(keyPair.getPublic());
+            v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
+            X509Certificate PKCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());
+
+            //add private key to KS
+            keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(),
+                                 new java.security.cert.Certificate[]{PKCertificate});
+            return PKCertificate;
+        } catch (Exception ex) {
+            String msg = "Error while generating the certificate for tenant :" +
+                         tenantDomain + ".";
+            log.error(msg, ex);
+            throw new KeyStoreMgtException(msg, ex);
+        }
+
+    }
+
+    /**
+     * Persist the keystore in the gov.registry
+     *
+     * @param keyStore created Keystore of the tenant
+     * @param PKCertificate pub. key of the tenant
+     * @throws KeyStoreMgtException Exception when storing the keystore in the registry
+     */
+    private void persistKeyStore(KeyStore keyStore, X509Certificate PKCertificate)
+            throws KeyStoreMgtException {
+        try {
+            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+            keyStore.store(outputStream, password.toCharArray());
+            outputStream.flush();
+            outputStream.close();
+
+            String keyStoreName = generateKSNameFromDomainName();
+            // Use the keystore using the keystore admin
+            KeyStoreAdmin keystoreAdmin = new KeyStoreAdmin(tenantId, govRegistry);
+            keystoreAdmin.addKeyStore(outputStream.toByteArray(), keyStoreName,
+                                      password, " ", "JKS", password);
+            
+            //Create the pub. key resource
+            Resource pubKeyResource = govRegistry.newResource();
+            pubKeyResource.setContent(PKCertificate.getEncoded());
+            pubKeyResource.addProperty(SecurityConstants.PROP_TENANT_PUB_KEY_FILE_NAME_APPENDER,
+                                       generatePubKeyFileNameAppender());
+
+            govRegistry.put(RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE, pubKeyResource);
+
+            //associate the public key with the keystore
+            govRegistry.addAssociation(RegistryResources.SecurityManagement.KEY_STORES + "/" + keyStoreName,
+                                       RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE,
+                                       SecurityConstants.ASSOCIATION_TENANT_KS_PUB_KEY);
+
+        } catch (RegistryException e) {
+            String msg = "Error when writing the keystore/pub.cert to registry";
+            log.error(msg, e);
+            throw new KeyStoreMgtException(msg, e);
+        }
+        catch (Exception e) {
+            String msg = "Error when processing keystore/pub. cert to be stored in registry";
+            log.error(msg, e);
+            throw new KeyStoreMgtException(msg, e);
+        }
+    }
+
+    /**
+     * This method is used to generate a random password for the generated keystore
+     *
+     * @return generated password
+     */
+    private String generatePassword() {
+        SecureRandom random = new SecureRandom();
+        String randString = new BigInteger(130, random).toString(12);
+        return randString.substring(randString.length() - 10, randString.length());
+    }
+
+    /**
+     * This method is used to generate a file name appender for the pub. cert, e.g.
+     * example-com-343743.cert
+     * @return generated string to be used as a file name appender
+     */
+    private String generatePubKeyFileNameAppender(){
+        String uuid = UUIDGenerator.getUUID();
+        return uuid.substring(uuid.length() - 6, uuid.length()-1);
+    }
+
+    /**
+     * This method generates the key store file name from the Domain Name
+     * @return
+     */
+    private String generateKSNameFromDomainName(){
+        String ksName = tenantDomain.trim().replace(".", "-");
+        return (ksName + ".jks" );
+    }
+
+    private String getTenantDomainName() throws KeyStoreMgtException {
+        RealmService realmService = RealmServiceHolder.getRealmService();
+        if (realmService == null) {
+            String msg = "Error in getting the domain name, realm service is null.";
+            log.error(msg);
+            throw new KeyStoreMgtException(msg);
+        }
+        try {
+            return realmService.getTenantManager().getDomain(tenantId);
+        } catch (org.wso2.carbon.user.api.UserStoreException e) {
+            String msg = "Error in getting the domain name for the tenant id: " + tenantId;
+            log.error(msg, e);
+            throw new KeyStoreMgtException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreMgtException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreMgtException.java b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreMgtException.java
new file mode 100644
index 0000000..de486f0
--- /dev/null
+++ b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeyStoreMgtException.java
@@ -0,0 +1,39 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.keystore.mgt;
+
+/**
+ * This class is used to wrap the exceptions thrown from stratos keystore mgt component.
+ */
+public class KeyStoreMgtException extends Exception {
+    public KeyStoreMgtException() {
+    }
+
+    public KeyStoreMgtException(String message) {
+        super(message);
+    }
+
+    public KeyStoreMgtException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    public KeyStoreMgtException(Throwable cause) {
+        super(cause);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeystoreTenantMgtListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeystoreTenantMgtListener.java b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeystoreTenantMgtListener.java
new file mode 100644
index 0000000..b4eaf6c
--- /dev/null
+++ b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/KeystoreTenantMgtListener.java
@@ -0,0 +1,79 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.keystore.mgt;
+
+import org.apache.stratos.common.beans.TenantInfoBean;
+import org.apache.stratos.common.exception.StratosException;
+import org.apache.stratos.common.listeners.TenantMgtListener;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * This class is used to listen to the tenant creation events and fire the keystore creation event
+ */
+public class KeystoreTenantMgtListener implements TenantMgtListener {
+
+    private static Log log = LogFactory.getLog(KeystoreTenantMgtListener.class);
+    private static final int EXEC_ORDER = 20;
+
+    /**
+     * Generate the keystore when a new tenant is registered.
+     * @param tenantInfo Information about the newly created tenant
+     */
+    public void onTenantCreate(TenantInfoBean tenantInfo) throws StratosException {
+        try {
+            KeyStoreGenerator ksGenerator = new KeyStoreGenerator(tenantInfo.getTenantId());
+            ksGenerator.generateKeyStore();
+        } catch (KeyStoreMgtException e) {
+            String message = "Error when generating the keystore";
+            log.error(message, e);
+            throw new StratosException(message, e);
+        }
+    }
+
+    public void onTenantUpdate(TenantInfoBean tenantInfo) throws StratosException {
+        // It is not required to implement this method for keystore mgt. 
+    }
+
+    public void onTenantRename(int tenantId, String oldDomainName,
+                             String newDomainName) throws StratosException {
+        // It is not required to implement this method for keystore mgt.
+    }
+
+    public int getListenerOrder() {
+        return EXEC_ORDER;
+    }
+
+    public void onTenantInitialActivation(int tenantId) throws StratosException {
+        // It is not required to implement this method for keystore mgt. 
+    }
+
+    public void onTenantActivation(int tenantId) throws StratosException {
+        // It is not required to implement this method for keystore mgt. 
+    }
+
+    public void onTenantDeactivation(int tenantId) throws StratosException {
+        // It is not required to implement this method for keystore mgt. 
+    }
+
+    public void onSubscriptionPlanChange(int tenentId, String oldPlan, 
+                                         String newPlan) throws StratosException {
+        // It is not required to implement this method for keystore mgt. 
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/internal/KeyStoreMgtServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/internal/KeyStoreMgtServiceComponent.java b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/internal/KeyStoreMgtServiceComponent.java
new file mode 100644
index 0000000..bc9b44f
--- /dev/null
+++ b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/internal/KeyStoreMgtServiceComponent.java
@@ -0,0 +1,87 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.keystore.mgt.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.apache.stratos.keystore.mgt.KeystoreTenantMgtListener;
+import org.apache.stratos.keystore.mgt.util.RealmServiceHolder;
+import org.apache.stratos.keystore.mgt.util.RegistryServiceHolder;
+
+/**
+ * @scr.component name="org.apache.stratos.keystore.mgt"
+ * immediate="true"
+ * @scr.reference name="registry.service"
+ * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="1..1"
+ * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
+ * @scr.reference name="user.realmservice.default" interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService"
+ * unbind="unsetRealmService"
+ */
+public class KeyStoreMgtServiceComponent {
+
+    private static Log log = LogFactory.getLog(KeyStoreMgtServiceComponent.class);
+
+
+    protected void activate(ComponentContext ctxt){
+        KeystoreTenantMgtListener keystoreTenantMgtListener = new KeystoreTenantMgtListener();
+        ctxt.getBundleContext().registerService(
+                org.apache.stratos.common.listeners.TenantMgtListener.class.getName(),
+                keystoreTenantMgtListener, null);
+        if (log.isDebugEnabled()) {
+            log.debug("*************Stratos Keystore mgt component is activated.**************");
+        }
+    }
+
+    protected void deactivate(ComponentContext ctxt) {
+        if(log.isDebugEnabled()){
+            log.debug("************Stratos keystore mgt component is decativated.*************");
+        }
+    }
+
+    protected void setRegistryService(RegistryService registryService){
+        RegistryServiceHolder.setRegistryService(registryService);
+        if (log.isDebugEnabled()) {
+            log.debug("Registry Service is set for KeyStoreMgtServiceComponent.");
+        }
+    }
+
+    protected void unsetRegistryService(RegistryService registryService){
+        RegistryServiceHolder.setRegistryService(null);
+        if(log.isDebugEnabled()){
+            log.debug("Registry Service is unset for KeyStoreMgtServiceComponent.");
+        }
+    }
+
+    protected void setRealmService(RealmService realmService){
+        RealmServiceHolder.setRealmService(realmService);
+        if (log.isDebugEnabled()) {
+            log.debug("Realm Service is set for KeyStoreMgtServiceComponent.");
+        }
+    }
+
+    protected void unsetRealmService(RealmService realmService){
+        RealmServiceHolder.setRealmService(null);
+        if(log.isDebugEnabled()){
+            log.debug("Realm Service is unset for KeyStoreMgtServiceComponent.");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/util/RealmServiceHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/util/RealmServiceHolder.java b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/util/RealmServiceHolder.java
new file mode 100644
index 0000000..a1e6b16
--- /dev/null
+++ b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/util/RealmServiceHolder.java
@@ -0,0 +1,33 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.keystore.mgt.util;
+
+import org.wso2.carbon.user.core.service.RealmService;
+
+public class RealmServiceHolder {
+
+    private static RealmService realmServiceService;
+
+    public static RealmService getRealmService() {
+        return realmServiceService;
+    }
+
+    public static void setRealmService(RealmService realmService) {
+        RealmServiceHolder.realmServiceService = realmService;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/util/RegistryServiceHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/util/RegistryServiceHolder.java b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/util/RegistryServiceHolder.java
new file mode 100644
index 0000000..5b7ab4a
--- /dev/null
+++ b/components/org.apache.stratos.keystore.mgt/src/main/java/org/apache/stratos/keystore/mgt/util/RegistryServiceHolder.java
@@ -0,0 +1,33 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.keystore.mgt.util;
+
+import org.wso2.carbon.registry.core.service.RegistryService;
+
+public class RegistryServiceHolder {
+
+    private static RegistryService registryService;
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static void setRegistryService(RegistryService registryService) {
+        RegistryServiceHolder.registryService = registryService;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/pom.xml b/components/org.apache.stratos.lb.common/4.1.3/pom.xml
deleted file mode 100644
index 50d9a12..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/pom.xml
+++ /dev/null
@@ -1,120 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-       Licensed to the Apache Software Foundation (ASF) under one
-       or more contributor license agreements.  See the NOTICE file
-       distributed with this work for additional information
-       regarding copyright ownership.  The ASF licenses this file
-       to you under the Apache License, Version 2.0 (the
-       "License"); you may not use this file except in compliance
-       with the License.  You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing,
-       software distributed under the License is distributed on an
-       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-       KIND, either express or implied.  See the License for the
-       specific language governing permissions and limitations
-       under the License.
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-        <relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <groupId>org.apache.stratos</groupId>
-    <artifactId>org.apache.stratos.lb.common</artifactId>
-    <packaging>bundle</packaging>
-    <version>4.1.3</version>
-    <name>Apache Stratos Loadbalancer - Common</name>
-    <url>http://apache.org</url>
-    
-    <dependencies>
-    	<dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.core</artifactId>
-            <version>${wso2carbon.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>com.google.guava.wso2</groupId>
-	        <artifactId>guava</artifactId>
-            <version>${google.guava.wso2.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.synapse</groupId>
-            <artifactId>synapse-core</artifactId>
-            <version>${synapse.core.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>junit</groupId>
-            <artifactId>junit</artifactId>
-            <version>${junit.version}</version>
-        </dependency>
-        <!--dependency>
-          <groupId>org.testng</groupId>
-          <artifactId>testng</artifactId>
-          <version>6.3.1</version>
-          <scope>test</scope>
-        </dependency-->
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.logging</artifactId>
-            <version>4.1.0</version>
-        </dependency>
-        <!--dependency>
-        	<groupId>mysql</groupId>
-        	<artifactId>mysql-connector-java</artifactId>
-        	<version>5.1.6</version>
-        </dependency-->
-        <!-- This mysql dependency is required for tests-->
-    </dependencies>
-
-    <build>
-        <plugins>
-            <!--plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-surefire-plugin</artifactId>
-                <version>2.12</version>
-                <configuration>
-                  <suiteXmlFiles>
-                    <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
-                  </suiteXmlFiles>
-                </configuration>
-              </plugin-->
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Export-Package>
-                            org.apache.stratos.lb.common.*,
-                        </Export-Package>
-                        <Private-Package>
-                        	org.apache.stratos.lb.common.conf.internal;
-                        </Private-Package>
-                        <Import-Package>
-                            !org.apache.commons.logging,
-                            org.apache.commons.logging; version=0.0.0,
-                            *;resolution:=optional
-                        </Import-Package>
-                        <DynamicImport-Package>*</DynamicImport-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/cache/LRUCache.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/cache/LRUCache.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/cache/LRUCache.java
deleted file mode 100644
index 342430c..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/cache/LRUCache.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.cache;
-
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-/**
- * A simple, thread-safe LRU cache implementation. This cache allows concurrent reads.
- * Concurrent write attempts are synchronized using an exclusive lock.
- */
-public class LRUCache<K,V> extends LinkedHashMap<K,V> {
-
-    private static final long serialVersionUID = 5901026458782787628L;
-    private int maxEntries;
-    private ReadWriteLock lock;
-
-    public LRUCache(int maxEntries) {
-        super(maxEntries + 1, 1, false);
-        this.maxEntries = maxEntries;
-        this.lock = new ReentrantReadWriteLock();
-    }
-
-    @Override
-    public V get(Object key) {
-        lock.readLock().lock();
-        try {
-            return super.get(key);
-        } finally {
-            lock.readLock().unlock();
-        }
-    }
-
-    @Override
-    public V put(K key, V value) {
-        lock.writeLock().lock();
-        try {
-            return super.put(key, value);
-        } finally {
-            lock.writeLock().unlock();
-        }
-    }
-
-    @Override
-    public V remove(Object key) {
-        lock.writeLock().lock();
-        try {
-            return super.remove(key);
-        } finally {
-            lock.writeLock().unlock();
-        }
-    }
-
-    @Override
-    public void clear() {
-        lock.writeLock().lock();
-        try {
-            super.clear();
-        } finally {
-            lock.writeLock().unlock();
-        }
-    }
-
-    @Override
-    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
-        boolean remove = size() > maxEntries;
-        if (remove) {
-            handleRemovableEntry(eldest);
-        }
-        return remove;
-    }
-
-    protected void handleRemovableEntry(Map.Entry<K,V> entry) {
-
-    }
-
-    public void exclusiveLock() {
-        lock.writeLock().lock();
-    }
-
-    public void release() {
-        lock.writeLock().unlock();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/cache/URLMappingCache.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/cache/URLMappingCache.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/cache/URLMappingCache.java
deleted file mode 100644
index 3c23efc..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/cache/URLMappingCache.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.cache;
-
-import org.apache.stratos.lb.common.util.DomainMapping;
-import java.util.Map;
-
-public class URLMappingCache {
-    private Map<String,DomainMapping> validMappings;
-
-    private static URLMappingCache instance = null;
-    protected URLMappingCache(int maxValidKeys) {
-        validMappings = new LRUCache<String, DomainMapping>(maxValidKeys);
-    }
-
-    public void addValidMapping(String hostName, DomainMapping mapping) {
-        validMappings.put(hostName, mapping);
-    }
-
-    public DomainMapping getMapping(String hostName) {
-        return validMappings.get(hostName);
-    }
-
-    public static URLMappingCache getInstance(int maxValidKeys) {
-      if(instance == null) {
-
-         instance = new URLMappingCache(maxValidKeys);
-      }
-      return instance;
-   }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/LoadBalancerConfiguration.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/LoadBalancerConfiguration.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/LoadBalancerConfiguration.java
deleted file mode 100644
index 0257b0e..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/LoadBalancerConfiguration.java
+++ /dev/null
@@ -1,1206 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.conf;
-
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.commons.util.PropertyHelper;
-import org.apache.stratos.lb.common.conf.structure.Node;
-import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
-import org.apache.stratos.lb.common.conf.util.Constants;
-import org.apache.stratos.lb.common.conf.util.HostContext;
-import org.apache.stratos.lb.common.conf.util.LoadBalancerConfigUtil;
-import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
-import java.io.*;
-import java.net.URL;
-import java.util.*;
-
-/**
- * Data object which hold configuration data of the load analyzer task
- */
-@SuppressWarnings("unused")
-public class LoadBalancerConfiguration implements Serializable {
-
-    protected static final long serialVersionUID = -5553545217542808233L;
-
-    private static final Log log = LogFactory.getLog(LoadBalancerConfiguration.class);
-
-    /**
-     * This map is there to speed up the lookup time.
-     * Key: domain
-     * <p/>
-     * Value: A map whose key is sub domain and value is ServiceConfiguration
-     */
-    private Map<String, Map<String, ServiceConfiguration>> serviceConfigurations =
-            new HashMap<String, Map<String, ServiceConfiguration>>();
-    
-    /**
-     * Key - host name
-     * Value - {@link HostContext}
-     */
-    private transient Map<String, HostContext> hostCtxt = new HashMap<String, HostContext>();
-    
-    /**
-     * This map is there to speed up the lookup time.
-     * Key: service name/cartridge type (Stratos2). NOTE: that this is not the service cluster domain.
-     * Value: list of {@link ServiceConfiguration} - corresponding objects under a service name.
-     */
-	private Map<String, List<ServiceConfiguration>> serviceNameToServiceConfigurations =
-			new HashMap<String, List<ServiceConfiguration>>();
-
-    /**
-     * This list will be used to identify host name duplications among different services.
-     * Within a service there can be duplications, but among different services you can't have duplications.
-     * Key - service name
-     * Value - hosts under the respective service.
-     */
-    private Map<String, Set<String>> hostNamesTracker = new HashMap<String, Set<String>>();
-
-    protected ServiceConfiguration defaultServiceConfig;
-    protected LBConfiguration lbConfig;
-
-    /**
-     * LBConfig file as a String
-     */
-    protected String lbConfigString;
-
-    /**
-     * Root node object for loadbalancer.conf
-     */
-    protected Node rootNode;
-
-    private LoadBalancerConfiguration(){
-        init(System.getProperty("loadbalancer.conf"));
-    }
-
-    private static LoadBalancerConfiguration instance ;
-    
-    public static LoadBalancerConfiguration getInstance(){
-        if(instance == null){
-            instance = new LoadBalancerConfiguration();
-        }
-        return instance;
-    }
-
-    /**
-     * Sample loadbalancer.conf:
-     * <p/>
-     * loadbalancer {
-     * # minimum number of load balancer instances
-     * instances           1;
-     * # whether autoscaling enable or not
-     * enable_autoscaler   true;
-     * # End point reference of the Autoscaler Service
-     * autoscaler_service_epr  https://10.100.3.81:9443/services/AutoscalerService/;
-     * # interval between two task executions in milliseconds
-     * autoscaler_task_interval 1000;
-     * # after an instance booted up, task will wait till this much of time and let the server started up
-     * server_startup_delay 15000;
-     * }
-     * <p/>
-     * services {
-     * defaults {
-     * min_app_instances       1;
-     * max_app_instances       5;
-     * queue_length_per_node   400;
-     * rounds_to_average       10;
-     * instances_per_scale_up  1;
-     * message_expiry_time     60000;
-     * }
-     * <p/>
-     * appserver {
-     * hosts                   appserver.cloud-test.wso2.com,as.cloud-test.wso2.com;
-     * domains   {
-     * wso2.as1.domain {
-     * tenant_range    1-100;
-     * }
-     * wso2.as2.domain {
-     * tenant_range    101-200;
-     * }
-     * wso2.as3.domain {
-     * tenant_range    *;
-     * }
-     * }
-     * }
-     * }
-     *
-     * @param configURL URL of the load balancer config
-     */
-    public void init(String configURL) {
-
-        if(configURL == null){
-            String msg = "Cannot locate the location of the loadbalancer.conf file." +
-                   " You need to set the 'loadbalancer.conf' system property.";
-            log.error(msg);
-            throw new RuntimeException(msg);
-        }
-        
-        if (configURL.startsWith("$system:")) {
-            configURL = System.getProperty(configURL.substring("$system:".length()));
-        }
-
-        try {
-
-            // get loadbalancer.conf file as a String
-            if (configURL.startsWith(File.separator)) {
-                lbConfigString = createLBConfigString(configURL);
-            } else {
-                lbConfigString = createLBConfigString(new URL(configURL).openStream());
-            }
-
-        } catch (Exception e) {
-            String msg = "Cannot read configuration file from " + configURL;
-            log.error(msg, e);
-            throw new RuntimeException(msg, e);
-        }
-
-        // build a Node object for whole loadbalancer.conf
-        rootNode = new Node();
-        rootNode.setName("root");
-        rootNode = NodeBuilder.buildNode(rootNode, lbConfigString);
-
-        // load 'loadbalancer' node
-        Node lbConfigNode = rootNode.findChildNodeByName(Constants.LOAD_BALANCER_ELEMENT);
-
-        if(lbConfigNode != null){
-        	createConfiguration(lbConfig = new LBConfiguration(), lbConfigNode);
-        }
-
-        // load services node
-        Node servicesConfigNode = rootNode.findChildNodeByName(Constants.SERVICES_ELEMENT);
-
-        if (servicesConfigNode == null) {
-            String msg = "Mandatory " + Constants.SERVICES_ELEMENT +
-                    " element can not be found in the configuration file.";
-            log.error(msg);
-            throw new RuntimeException(msg);
-        }
-
-        // Set services configuration
-        createServicesConfig(servicesConfigNode);
-
-    }
-
-
-    /**
-     * Process the content of the following 'services' element
-     * <p/>
-     * services {
-     * defaults {
-     * min_app_instances       1;
-     * max_app_instances       5;
-     * queue_length_per_node   400;
-     * rounds_to_average       10;
-     * instances_per_scale_up  1;
-     * message_expiry_time     60000;
-     * }
-     * <p/>
-     * appserver {
-     * hosts                   appserver.cloud-test.wso2.com,as.cloud-test.wso2.com;
-     * domains   {
-     * wso2.as1.domain {
-     * tenant_range    1-100;
-     * }
-     * wso2.as2.domain {
-     * tenant_range    101-200;
-     * }
-     * wso2.as3.domain {
-     * tenant_range    *;
-     * }
-     * }
-     * }
-     * }
-     *
-     * @param servicesConfigNode services element's Node
-     */
-    public List<ServiceConfiguration> createServicesConfig(Node servicesConfigNode) {
-
-        // current list of service configs
-        List<ServiceConfiguration> currentServiceConfigs = new ArrayList<ServiceConfiguration>();
-        
-        // Building default configuration
-        Node defaultNode = servicesConfigNode.findChildNodeByName(Constants.DEFAULTS_ELEMENT);
-
-        if (defaultNode != null) {
-
-            createConfiguration(defaultServiceConfig = new ServiceConfiguration(), defaultNode);
-        }
-
-        // Building custom services configuration
-        for (Node serviceNode : servicesConfigNode.getChildNodes()) {
-            //skip default node
-            if (serviceNode != defaultNode) {
-
-                String serviceName = serviceNode.getName();
-
-                // reading domains
-
-                Node domainsNode;
-
-                if (serviceNode.getChildNodes().isEmpty() ||
-                        !(domainsNode = serviceNode.getChildNodes().get(0)).getName().equals(
-                                Constants.DOMAIN_ELEMENT)) {
-
-                    String msg = "The mandatory domains element, child of the " + serviceName +
-                            " element is not specified in the configuration file. \n"+
-                            serviceNode.toString();
-                    log.error(msg);
-                    throw new RuntimeException(msg);
-                }
-
-                if (domainsNode.getChildNodes().isEmpty()) {
-                    // this is probably a mistake, so we don't proceed
-                    String msg = "No domain is specified under " + Constants.DOMAIN_ELEMENT +
-                            " of " + serviceName + " element.";
-                    log.error(msg);
-                    throw new RuntimeException(msg);
-                }
-
-                ServiceConfiguration serviceConfig;
-
-                // iterates through all the service domain specified in this service element. 
-                for (Node domain : domainsNode.getChildNodes()) {
-
-                    // create a new service configuration
-                    serviceConfig = new ServiceConfiguration();
-
-                    // set service name
-                    serviceConfig.setServiceName(serviceName);
-                    
-                    // set domain name
-                    serviceConfig.setDomain(domain.getName());
-
-                    // let's set properties common to all domains specified in this service element.
-                    createConfiguration(serviceConfig, serviceNode);
-
-                    // load properties specified under this service domain element.
-                    createConfiguration(serviceConfig, domain);
-
-                    // check host name duplication 
-                    if(isDuplicatedHost(serviceNode.getName(), serviceConfig)){
-                        // this is probably a mistake, so we don't proceed
-                        String msg = "Duplicated host names detected for different service domains.\n" +
-                                "Element: \n"+serviceNode.toString();
-                        log.error(msg);
-                        throw new RuntimeException(msg);
-                    }
-                    
-                    currentServiceConfigs.add(serviceConfig);
-
-                }
-            }
-        }
-
-        for (ServiceConfiguration serviceConfiguration : currentServiceConfigs) {
-            
-            // add the built ServiceConfiguration, to the map
-            addServiceConfiguration(serviceConfiguration);
-            
-        }
-        
-        return currentServiceConfigs;
-
-    }
-
-
-    public boolean addServiceConfiguration(ServiceConfiguration serviceConfig) {
-
-        Map<String, ServiceConfiguration> map;
-        String domain = serviceConfig.getDomain();
-        
-        if(domain == null){
-            String msg = "Domain of a Service Configuration cannot be null. Hence this " +
-            		"Configuration will be neglected.";
-            log.error(msg);
-            return false;
-        }
-        
-        String subDomain = serviceConfig.getSubDomain();
-
-        if (serviceConfigurations.containsKey(domain)) {
-            map = serviceConfigurations.get(domain);
-        } else {
-            map = new HashMap<String, ServiceConfiguration>();
-        }
-        // put this serviceConfig
-        map.put(subDomain, serviceConfig);
-
-        // update the parent map
-        serviceConfigurations.put(domain, map);
-        
-        // add to serviceNameToServiceConfiguration map
-        List<ServiceConfiguration> configs;
-        if(serviceNameToServiceConfigurations.get(serviceConfig.getServiceName()) == null){
-        	configs = new ArrayList<ServiceConfiguration>();
-        	
-        }else{
-        	configs = serviceNameToServiceConfigurations.get(serviceConfig.getServiceName());
-        }
-        
-        if(!configs.contains(serviceConfig)){
-        	configs.add(serviceConfig);
-        }
-        serviceNameToServiceConfigurations.put(serviceConfig.getServiceName(), configs);
-        
-        return true;
-    }
-    
-    public ServiceConfiguration removeServiceConfiguration(String domain, String subDomain) {
-
-        Map<String, ServiceConfiguration> map;
-        ServiceConfiguration serviceConfig = null;
-        
-        if(domain == null){
-            String msg = "Domain of a Service Configuration cannot be null. Hence this " +
-            		"Configuration will be neglected.";
-            log.error(msg);
-            return null;
-        }
-
-        if (serviceConfigurations.containsKey(domain)) {
-            map = serviceConfigurations.get(domain);
-            
-            if(map != null){
-            	serviceConfig = map.remove(subDomain);
-            }
-        } 
-        
-        if(serviceConfig == null){
-        	String msg = "No matching service configuration found for domain: "+domain+
-        			", sub domain: "+subDomain;
-            log.error(msg);
-        	return null;
-        }
-        
-        String serviceName = serviceConfig.getServiceName();
-        
-        if (serviceName != null && serviceNameToServiceConfigurations.containsKey(serviceName)) {
-            if(serviceConfig != null){
-            	List<ServiceConfiguration> list = serviceNameToServiceConfigurations.get(serviceName);
-            	
-            	list.remove(serviceConfig);
-            	
-            	serviceNameToServiceConfigurations.put(serviceName, list);
-            }
-        } 
-        
-        Set<String> allHosts;
-
-        if (hostNamesTracker.containsKey(serviceName)) {
-            allHosts = hostNamesTracker.get(serviceName);
-            
-            for (String hostName : serviceConfig.getHosts()) {
-	            
-				if (hostName != null) {
-					
-					allHosts.remove(hostName);
-
-					hostCtxt.remove(hostName);
-				}
-            }
-        }
-        
-        return serviceConfig;
-    }
-    
-    public void resetData(){
-    	serviceConfigurations =
-                new HashMap<String, Map<String, ServiceConfiguration>>();
-    	
-    	serviceNameToServiceConfigurations =
-    			new HashMap<String, List<ServiceConfiguration>>();
-    	
-    }
-
-
-    /**
-     * Duplications can only be seen, when you traverse down the configuration file.
-     * 
-     */
-    public boolean isDuplicatedHost(String name, ServiceConfiguration serviceConfig) {
-
-        /**
-         * This will be populated with host names of all other services other than the
-         * service subjected to the test.
-         */
-        List<String> hostsOtherThanMine = new ArrayList<String>(hostNamesTracker.values().size());
-
-        for (Map.Entry<String, Set<String>> entry : hostNamesTracker.entrySet()) {
-            if (!entry.getKey().equals(name)) {
-                hostsOtherThanMine.addAll(entry.getValue());
-            }
-        }
-
-        for (String host : serviceConfig.getHosts()) {
-            if (!hostsOtherThanMine.isEmpty() && hostsOtherThanMine.contains(host)) {
-                return true;
-            }
-        }
-
-        addToHostNameTrackerMap(name, serviceConfig.getHosts());
-
-        return false;
-    }
-
-
-    public void addToHostNameTrackerMap(String name, List<String> hosts) {
-
-        Set<String> allHosts;
-
-        if (hostNamesTracker.containsKey(name)) {
-            allHosts = hostNamesTracker.get(name);
-            allHosts.addAll(hosts);
-        } else {
-            allHosts = new HashSet<String>(hosts);
-        }
-        hostNamesTracker.put(name, allHosts);
-    }
-    
-    public void addToHostContextMap(String hostName, HostContext ctxt) {
-
-        if (hostName != null && ctxt != null) {
-            hostCtxt.put(hostName, ctxt);
-        }
-    }
-    
-    /**
-     * Return a map of {@link HostContext}.
-     * @return
-     */
-    public Map<String, HostContext> getHostContextMap() {
-
-        List<Integer> tenantIds;
-        Map<String, String> URLSuffixes;
-
-        // FIXME if possible! I couldn't think of any other way to do this, at this moment.
-        // Note: some of these for-loops are pretty small, thus no considerable performance overhead.
-        // iterate through each service
-        for (Iterator<Set<String>> it = hostNamesTracker.values().iterator(); it.hasNext();) {
-
-            // iterate through host names of this service
-            for (String hostName : ((Set<String>) it.next())) {
-                                                                  
-                // building HostContext
-                HostContext ctxt = new HostContext(hostName);
-
-                // iterate through domains of this host
-                for (Map.Entry<String, Map<String, ServiceConfiguration>> parentMap : serviceConfigurations.entrySet()) {
-
-                    // iterate through sub domain of this domain
-                    for (Map.Entry<String, ServiceConfiguration> childMap : parentMap.getValue()
-                            .entrySet()) {
-                        // iterate through hosts of this
-                        for (String host : childMap.getValue().getHosts()) {
-                            // if a matching Service configuration is found.
-                            if (host.equals(hostName)) {
-                                
-                                String tenantRange = childMap.getValue().getTenantRange();
-                                String domain = parentMap.getKey();
-                                String subDomain = childMap.getKey();
-                                          
-                                ctxt.addTenantDomainContexts(LoadBalancerConfigUtil.getTenantDomainContexts(tenantRange, domain, subDomain));
-
-                                break;
-                            }
-                        }
-                        
-                        //iterate through URL suffixes
-                        for(Map.Entry<String, String> entry : childMap.getValue().getUrl_suffix().entrySet()) {
-                            if(entry.getKey().equals(hostName)) {
-                                
-                                ctxt.setUrlSuffix(entry.getValue());
-                                
-                                break;
-                            }
-
-                        }
-                    }
-                }
-
-                // add this hostCtxt
-                hostCtxt.put(hostName, ctxt);
-            }
-
-        }
-
-        return hostCtxt;
-
-    }
-
-    protected void createConfiguration(Configuration config, Node node) {
-
-        if (node == null) {
-            String msg = "The configuration element for " +
-                    config.getClass().getName() + " is null.";
-            throw new RuntimeException(msg);
-        }
-
-        try {
-            // load properties
-            for (Map.Entry<String, String> entry : node.getProperties().entrySet()) {
-                String key = entry.getKey();
-                String value = entry.getValue();
-
-                PropertyHelper.setInstanceProperty(key, value, config);
-            }
-
-        } catch (Exception e) {
-            String msg = "Error setting values to " + config.getClass().getName();
-            log.error(msg, e);
-            throw new RuntimeException(msg, e);
-        }
-    }
-
-    public LBConfiguration getLoadBalancerConfig() {
-        return lbConfig;
-    }
-
-    public String[] getServiceDomains() {
-
-        Object[] objs = serviceConfigurations.keySet().toArray();
-
-        return Arrays.copyOf(objs, objs.length, String[].class);
-
-    }
-
-    public String[] getServiceSubDomains(String domain) {
-
-        if (serviceConfigurations.get(domain) != null) {
-            Object[] objs = serviceConfigurations.get(domain).keySet().toArray();
-            return Arrays.copyOf(objs, objs.length, String[].class);
-        }
-
-        return new String[0];
-    }
-
-    public ServiceConfiguration getServiceConfig(String domain, String subDomain) {
-        if (serviceConfigurations.get(domain) != null) {
-            return serviceConfigurations.get(domain).get(subDomain);
-        }
-        return null;
-    }
-    
-    
-    public List<ServiceConfiguration> getServiceConfigs(String serviceName) {
-        return serviceNameToServiceConfigurations.get(serviceName);
-    }
-
-    /**
-     * Convert given configuration file to a single String
-     *
-     * @param configFileName - file name to convert
-     * @return String with complete lb configuration
-     * @throws FileNotFoundException
-     */
-    public String createLBConfigString(String configFileName) throws FileNotFoundException {
-        StringBuilder lbConfigString = new StringBuilder("");
-
-        File configFile = new File(configFileName);
-        Scanner scanner;
-
-        scanner = new Scanner(configFile);
-
-        while (scanner.hasNextLine()) {
-            lbConfigString.append(scanner.nextLine().trim() + "\n");
-        }
-
-        return lbConfigString.toString().trim();
-    }
-
-    public String createLBConfigString(InputStream configFileName) throws IOException {
-
-        // read the stream with BufferedReader
-        BufferedReader br = new BufferedReader(new InputStreamReader(configFileName));
-
-        StringBuilder sb = new StringBuilder();
-
-        String line;
-        while ((line = br.readLine()) != null) {
-            sb.append(line.trim() + "\n");
-        }
-
-        return sb.toString().trim();
-    }
-
-    public abstract class Configuration implements Serializable {
-
-        private static final long serialVersionUID = -5433889427746551250L;
-        protected String imageId = System.getenv("ami_id");
-        protected String payload;
-        protected boolean payloadSet;
-
-        protected String availability_zone = "us-east-1c";
-        protected boolean availabilityZoneSet;
-
-        protected String[] security_groups = new String[]{"default"};
-        protected boolean securityGroupsSet;
-
-        protected String instance_type = "m1.large";
-        protected boolean instanceTypeSet;
-
-        protected String additional_info;
-
-        public String getImageId() {
-            return imageId;
-        }
-
-        public String getAdditionalInfo() {
-            return additional_info;
-        }
-
-        public String getAvailability_zone() {
-            if (this instanceof LBConfiguration) {
-                return availability_zone;
-            }
-            if (availabilityZoneSet) {
-                return availability_zone;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.availabilityZoneSet) {
-                return defaultServiceConfig.availability_zone;
-            }
-            return availability_zone;
-        }
-
-        public String[] getSecurityGroups() {
-            if (this instanceof LBConfiguration) {
-                return security_groups;
-            }
-            if (securityGroupsSet) {
-                return security_groups;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.securityGroupsSet) {
-                return defaultServiceConfig.security_groups;
-            }
-            return security_groups;
-        }
-
-        public String getInstanceType() {
-            if (this instanceof LBConfiguration) {
-                return instance_type;
-            }
-            if (instanceTypeSet) {
-                return instance_type;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.instanceTypeSet) {
-                return defaultServiceConfig.instance_type;
-            }
-            return instance_type;
-        }
-
-
-        public String getUserData() {
-            if (payload == null) {
-                payload = LoadBalancerConfigUtil.getUserData("resources/cluster_node.zip");
-            }
-            if (this instanceof LBConfiguration) {
-                return payload;
-            }
-            if (payloadSet) {
-                return payload;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.payloadSet) {
-                return defaultServiceConfig.payload;
-            }
-            return payload;
-        }
-
-        public void setPayload(String payload) {
-            this.payload = LoadBalancerConfigUtil.getUserData(LoadBalancerConfigUtil.replaceVariables(payload));
-            this.payloadSet = true;
-        }
-
-        public void setAvailability_zone(String availabilityZone) {
-            this.availability_zone = LoadBalancerConfigUtil.replaceVariables(availabilityZone);
-            this.availabilityZoneSet = true;
-        }
-
-        public void setSecurity_groups(String securityGroups) {
-            this.security_groups = LoadBalancerConfigUtil.replaceVariables(securityGroups).split(",");
-            this.securityGroupsSet = true;
-        }
-
-        public void setInstance_type(String instanceType) {
-            this.instance_type = LoadBalancerConfigUtil.replaceVariables(instanceType);
-            this.instanceTypeSet = true;
-        }
-
-    }
-
-    public class LBConfiguration extends Configuration implements Serializable {
-
-        private static final long serialVersionUID = 1357143883932816418L;
-        private String elasticIP;//= LoadBalancerConfigUtil.replaceVariables("${ELASTIC_IP}");
-        private int instances = 1;
-        private boolean isAutoscaleEnabled;
-        private int autoscalerTaskInterval = 30000;
-        private String autoscalerServiceEpr;
-        private int serverStartupDelay = 60000;
-        private int sizeOfCache = 0 ;
-        private boolean failOver;
-        private int sessionTimeOut = -1;
-        private String groupManagementAgentClass;
-        private String autoscalerTaskClass;
-        private String mbServerUrl;
-        private boolean useEmbeddedAutoscaler = true;
-        private String algorithm = "org.apache.synapse.endpoints.algorithms.RoundRobin";
-
-        public String getElasticIP() {
-            return elasticIP;
-        }
-
-        public int getInstances() {
-            return instances;
-        }
-
-        public boolean isAutoscaleEnabled() {
-            return isAutoscaleEnabled;
-        }
-        
-        public boolean useEmbeddedAutoscaler() {
-            return useEmbeddedAutoscaler;
-        }
-        
-        public boolean getFailOver() {
-            return failOver;
-        }
-
-        public String getAutoscalerServiceEpr() {
-            return autoscalerServiceEpr;
-        }
-
-        public int getAutoscalerTaskInterval() {
-            return autoscalerTaskInterval;
-        }
-
-        public int getServerStartupDelay() {
-            return serverStartupDelay;
-        }
-        
-        public int getSessionTimeOut() {
-            return sessionTimeOut;
-        }
-
-        public void setElasticIP(String elasticIP) {
-            this.elasticIP = LoadBalancerConfigUtil.replaceVariables(elasticIP);
-        }
-
-        public void setInstances(int instances) {
-            this.instances = instances;
-        }
-
-        public void setEnable_autoscaler(String isEnabled) {
-            this.isAutoscaleEnabled = Boolean.parseBoolean(isEnabled);
-        }
-        
-        public void setUse_embedded_autoscaler(String use) {
-            this.useEmbeddedAutoscaler = Boolean.parseBoolean(use);
-        }
-        
-        public void setFail_over(String isEnabled) {
-            this.failOver = Boolean.parseBoolean(isEnabled);
-        }
-
-        public void setAutoscaler_service_epr(String epr) {
-            this.autoscalerServiceEpr = epr;
-        }
-
-        public void setMb_server_url(String url) {
-            this.mbServerUrl = url;
-        }
-        
-        public String getMbServerUrl() {
-        	return mbServerUrl;
-        }
-
-		public void setAutoscaler_task_interval(String interval) {
-            this.autoscalerTaskInterval = Integer.parseInt(interval);
-        }
-
-        public void setServer_startup_delay(String delay) {
-            this.serverStartupDelay = Integer.parseInt(delay);
-        }
-        
-        public void setSession_timeout(String timeout) {
-            this.sessionTimeOut = Integer.parseInt(timeout);
-        }
-
-        public String getAlgorithm() {
-            return algorithm;
-        }
-
-        public void setAlgorithm(String algorithm) {
-            if (algorithm != null) {
-                this.algorithm = algorithm;
-            }
-        }
-
-        public int getSizeOfCache() {
-            return sizeOfCache;
-        }
-
-        public void setSize_of_cache(int sizeOfCache) {
-            this.sizeOfCache = sizeOfCache;
-        }
-
-        public String getGroupManagementAgentClass() {
-            return groupManagementAgentClass;
-        }
-        
-        public String getAutoscalerTaskClass() {
-            return autoscalerTaskClass;
-        }
-
-        public void setGroup_mgt_agent(String groupManagementAgentClass){
-            this.groupManagementAgentClass = groupManagementAgentClass;
-        }
-        
-        public void setAutoscaler_task(String autoscalerTaskClass){
-            this.autoscalerTaskClass = autoscalerTaskClass;
-        }
-    }
-
-    public class ServiceConfiguration extends Configuration implements Serializable {
-
-    	private String serviceName;
-    	
-        public String getServiceName() {
-        	return serviceName;
-        }
-
-		public void setServiceName(String name) {
-        	this.serviceName = name;
-        }
-		
-		public String getPublicIp() {
-        	return publicIp;
-        }
-
-		public void setPublic_ip(String publicIp) {
-        	this.publicIp = publicIp;
-        }
-
-		private String publicIp;
-
-		private static final long serialVersionUID = 8707314702788040116L;
-        private int minAppInstances = 1;
-        private boolean minAppInstancesSet;
-
-        private int maxAppInstances = 3;
-        private boolean maxAppInstancesSet;
-
-        private int maxRequestsPerSecond = 100;
-        private boolean maxRequestsPerSecondSet;
-        
-        private double alarmingUpperRate = 0.7;
-        private boolean alarmingUpperRateSet;
-
-        private double alarmingLowerRate = 0.2;
-        private boolean alarmingLowerRateSet;
-        
-        private double scaleDownFactor = 0.25;
-        private boolean scaleDownFactorSet;
-        
-        private int roundsToAverage = 10;
-        private boolean roundsToAverageSet;
-
-        private int instancesPerScaleUp = 1;
-        private boolean instancesPerScaleUpSet;
-
-        private int messageExpiryTime = 60000; // milliseconds
-        private boolean messageExpiryTimeSet;
-
-        private List<String> hosts = new ArrayList<String>();
-        private Map<String, String> urlSuffixes = new HashMap<String, String>();
-        private boolean hostsSet;
-
-        private String domain;
-
-        private String tenantRange;
-        private boolean tenantRangeSet;
-
-        private String subDomain = Constants.DEFAULT_SUB_DOMAIN;
-        private boolean subDomainSet;
-
-        public String getTenantRange() {
-            if (tenantRangeSet) {
-                return tenantRange;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.tenantRangeSet) {
-                return defaultServiceConfig.tenantRange;
-            }
-            return tenantRange;
-        }
-
-        public String getDomain() {
-            return domain;
-        }
-
-        public List<String> getHosts() {
-            if (hostsSet) {
-                return hosts;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.hostsSet) {
-                return defaultServiceConfig.hosts;
-            }
-            return hosts;
-        }
-
-        public int getMinAppInstances() {
-            if (minAppInstancesSet) {
-                return minAppInstances;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.minAppInstancesSet) {
-                return defaultServiceConfig.minAppInstances;
-            }
-            return minAppInstances;
-        }
-
-        public int getMaxAppInstances() {
-            if (maxAppInstancesSet) {
-                return maxAppInstances;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.maxAppInstancesSet) {
-                return defaultServiceConfig.maxAppInstances;
-            }
-            return maxAppInstances;
-        }
-
-        public int getMaxRequestsPerSecond() {
-            if (maxRequestsPerSecondSet) {
-                return maxRequestsPerSecond;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.maxRequestsPerSecondSet) {
-                return defaultServiceConfig.maxRequestsPerSecond;
-            }
-            return maxRequestsPerSecond;
-        }
-
-        public int getRoundsToAverage() {
-            if (roundsToAverageSet) {
-                return roundsToAverage;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.roundsToAverageSet) {
-                return defaultServiceConfig.roundsToAverage;
-            }
-            return roundsToAverage;
-        }
-
-        public int getInstancesPerScaleUp() {
-            if (instancesPerScaleUpSet) {
-                return instancesPerScaleUp;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.instancesPerScaleUpSet) {
-                return defaultServiceConfig.instancesPerScaleUp;
-            }
-            return instancesPerScaleUp;
-        }
-
-        public int getMessageExpiryTime() {
-            if (messageExpiryTimeSet) {
-                return messageExpiryTime;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.messageExpiryTimeSet) {
-                return defaultServiceConfig.messageExpiryTime;
-            }
-            return messageExpiryTime;
-        }
-
-        public String getSubDomain() {
-            if (subDomainSet) {
-                return subDomain;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.subDomainSet) {
-                return defaultServiceConfig.subDomain;
-            }
-            return subDomain;
-        }
-
-        public void setMin_app_instances(int minAppInstances) {
-//            if (minAppInstances < 1) {
-//                LoadBalancerConfigUtil.handleException("minAppInstances in the autoscaler task configuration " +
-//                        "should be at least 1");
-//            }
-            this.minAppInstances = minAppInstances;
-            this.minAppInstancesSet = true;
-        }
-
-        public void setMax_app_instances(int maxAppInstances) {
-            if (maxAppInstances < 1) {
-                LoadBalancerConfigUtil.handleException("maxAppInstances in the autoscaler task configuration " +
-                        "should be at least 1");
-            }
-            this.maxAppInstances = maxAppInstances;
-            this.maxAppInstancesSet = true;
-        }
-        
-		public void setAlarming_upper_rate(double rate) {
-			if (rate > 0 && rate <= 1) {
-				this.alarmingUpperRate = rate;
-				this.alarmingUpperRateSet = true;
-			}
-		}
-
-        public void setAlarming_lower_rate(double rate) {
-			if (rate > 0 && rate <= 1) {
-				this.alarmingLowerRate = rate;
-				this.alarmingLowerRateSet = true;
-			}
-        }
-        
-		public void setScale_down_factor(double factor) {
-			if (factor > 0 && factor <= 1) {
-				this.scaleDownFactor = factor;
-				this.scaleDownFactorSet = true;
-			}
-		}
-        
-        public void setMax_requests_per_second(int rps) {
-            this.maxRequestsPerSecond = rps;
-            this.maxRequestsPerSecondSet = true;
-        }
-
-        public void setRounds_to_average(int roundsToAverage) {
-            this.roundsToAverage = roundsToAverage;
-            this.roundsToAverageSet = true;
-        }
-
-        public void setInstances_per_scale_up(int instancesPerScaleUp) {
-            if (instancesPerScaleUp < 1) {
-                LoadBalancerConfigUtil.handleException("instancesPerScaleUp in the autoscaler task configuration " +
-                        "should be at least 1");
-            }
-            this.instancesPerScaleUp = instancesPerScaleUp;
-            this.instancesPerScaleUpSet = true;
-        }
-
-        public void setMessage_expiry_time(int messageExpiryTime) {
-            if (messageExpiryTime < 1) {
-                LoadBalancerConfigUtil.handleException("messageExpiryTime in the autoscaler task configuration " +
-                        "should be at least 1");
-            }
-            this.messageExpiryTime = messageExpiryTime;
-            this.messageExpiryTimeSet = true;
-        }
-
-        public void setHosts(String hostsStr) {
-            // clear all unnecessary values --> property will get overwritten
-            hosts = new ArrayList<String>();
-            // there can be multiple hosts, let's find out.
-            String[] host = hostsStr.split(Constants.HOSTS_DELIMITER);
-
-            for (String string : host) {
-                if (!string.isEmpty()) {
-                    this.hosts.add(string);
-                }
-            }
-
-        }
-
-        public void setUrl_suffix(String suffix) {
-            // clear all unnecessary values --> property will get overwritten
-            //hosts = new ArrayList<String>();
-            // there can be multiple hosts, let's find out.
-            String[] suffixes = suffix.split(Constants.HOSTS_DELIMITER);
-            int count = 0;
-            if(suffixes.length == this.hosts.size()) {
-                for (String string : suffixes) {
-                    if (!string.isEmpty()) {
-                        this.urlSuffixes.put(this.hosts.get(count), string);
-                        count++;
-                    }
-                }
-            
-            } else {
-                //Error
-            }
-        }
-
-        public Map<String, String> getUrl_suffix() {
-            return this.urlSuffixes;
-        }
-
-        public void setTenant_range(String range) {
-            this.tenantRange = range;
-        }
-
-        public void setSub_domain(String subDomain) {
-            this.subDomain = subDomain;
-            this.subDomainSet = true;
-        }
-
-        public void setDomain(String domain) {
-            this.domain = domain;
-        }
-        
-        public boolean equals(ServiceConfiguration config) {
-            return this.domain.equals(config.getDomain()) &&
-                    this.subDomain.equals(config.getSubDomain());
-        }
-        
-        public int hashCode() {
-            return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
-                    append(domain).
-                    append(subDomain).
-                    toHashCode();
-        }
-
-        public double getAlarmingUpperRate() {
-            if (alarmingUpperRateSet) {
-                return alarmingUpperRate;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.alarmingUpperRateSet) {
-                return defaultServiceConfig.alarmingUpperRate;
-            }
-            return alarmingUpperRate;
-        }
-
-        public double getAlarmingLowerRate() {
-            if (alarmingLowerRateSet) {
-                return alarmingLowerRate;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.alarmingLowerRateSet) {
-                return defaultServiceConfig.alarmingLowerRate;
-            }
-            return alarmingLowerRate;
-        }
-
-        public double getScaleDownFactor() {
-            if (scaleDownFactorSet) {
-                return scaleDownFactor;
-            } else if (defaultServiceConfig != null && defaultServiceConfig.scaleDownFactorSet) {
-                return defaultServiceConfig.scaleDownFactor;
-            }
-            return scaleDownFactor;
-        }
-    }
-
-    public Map<String, Set<String>> getHostNamesTracker() {
-        return hostNamesTracker;
-    }
-
-
-    public Map<String, Map<String, ServiceConfiguration>> getServiceConfigurations() {
-        return serviceConfigurations;
-    }
-
-
-    public Node getRootNode() {
-        return rootNode;
-    }
-
-
-    public void setRootNode(Node rootNode) {
-        this.rootNode = rootNode;
-    }
-
-    public static void setInstance(LoadBalancerConfiguration instance) {
-        LoadBalancerConfiguration.instance = instance;
-    }
-
-	public Map<String, List<ServiceConfiguration>> getServiceNameToServiceConfigurations() {
-    	return serviceNameToServiceConfigurations;
-    }
-	
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java b/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
deleted file mode 100644
index ab58e12..0000000
--- a/components/org.apache.stratos.lb.common/4.1.3/src/main/java/org/apache/stratos/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.conf.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
-import org.apache.stratos.lb.common.service.impl.LoadBalancerConfigurationServiceImpl;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.component.ComponentContext;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
-import org.apache.stratos.lb.common.service.impl.LoadBalancerConfigurationServiceImpl;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
-import org.apache.stratos.lb.common.service.impl.LoadBalancerConfigurationServiceImpl;
-
-/**
- * Registering {@link org.apache.stratos.lb.common.service.LoadBalancerConfigurationService} .
- * @scr.component name="org.wso2.carbon.lb.common" immediate="true"
- */
-public class LoadBalancerConfigurationDSComponent {
-
-    private static final Log log = LogFactory.getLog(LoadBalancerConfigurationDSComponent.class);
-
-    protected void activate(ComponentContext context) {
-        try {
-            BundleContext bundleContext = context.getBundleContext();
-            bundleContext.registerService(LoadBalancerConfigurationService.class.getName(),
-                                          new LoadBalancerConfigurationServiceImpl(), null);
-
-            log.debug("******* Load Balancer Configuration Service bundle is activated ******* ");
-        } catch (Exception e) {
-            log.error("******* Load Balancer Configuration Service bundle is failed to activate ****", e);
-        }
-    }
-}


[23/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/impl/AutoscalerServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/impl/AutoscalerServiceImpl.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/impl/AutoscalerServiceImpl.java
new file mode 100644
index 0000000..b87cb50
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/impl/AutoscalerServiceImpl.java
@@ -0,0 +1,1389 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.impl;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.RunNodesException;
+import org.jclouds.compute.domain.ComputeMetadata;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.NodeMetadata.Status;
+import org.jclouds.compute.domain.Template;
+import org.jclouds.compute.domain.TemplateBuilder;
+import org.jclouds.compute.domain.internal.NodeMetadataImpl;
+import org.jclouds.compute.options.TemplateOptions;
+import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
+import org.apache.stratos.autoscaler.service.IAutoscalerService;
+import org.apache.stratos.autoscaler.service.exception.AutoscalerServiceException;
+import org.apache.stratos.autoscaler.service.exception.DeserializationException;
+import org.apache.stratos.autoscaler.service.exception.SerializationException;
+import org.apache.stratos.autoscaler.service.io.Deserializer;
+import org.apache.stratos.autoscaler.service.io.Serializer;
+import org.apache.stratos.autoscaler.service.jcloud.ComputeServiceBuilder;
+import org.apache.stratos.autoscaler.service.util.AutoscalerConstant;
+import org.apache.stratos.autoscaler.service.util.IaasContext;
+import org.apache.stratos.autoscaler.service.util.IaasProvider;
+import org.apache.stratos.autoscaler.service.util.InstanceContext;
+import org.apache.stratos.autoscaler.service.util.ServiceTemplate;
+import org.apache.stratos.autoscaler.service.xml.ElasticScalerConfigFileReader;
+import org.apache.stratos.lb.common.conf.util.Constants;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * Autoscaler Service is responsible for starting up new server instances, terminating already
+ * started instances, providing pending instance count.
+ * 
+ */
+public class AutoscalerServiceImpl implements IAutoscalerService {
+
+	
+	private static final Log log = LogFactory.getLog(AutoscalerServiceImpl.class);
+
+    /**
+     * pointer to Carbon Home directory.
+     */
+    private static final String CARBON_HOME = CarbonUtils.getCarbonHome();
+
+    /**
+     * pointer to Carbon Temp directory.
+     */
+    private static final String CARBON_TEMP = CarbonUtils.getTmpDir();
+
+    /**
+     * Tenant id Delimiter
+     */
+	private static final String TENANT_ID_DELIMITER = "/t/";
+
+    /**
+     * This directory will be used to store serialized objects.
+     */
+    private String serializationDir;
+
+    /**
+     * List of all <code>IaaSProviders</code> specified in the config file.
+     */
+    private List<IaasProvider> iaasProviders;
+
+    /**
+     * List of all <code>ServiceTemplate</code> objects.
+     */
+    private List<ServiceTemplate> serviceTemps;
+
+    /**
+     * We keep an enum which contains all supported IaaSes.
+     */
+    public enum Iaases {
+        ec2, openstack
+    };
+
+    /**
+     * List which keeps <code>IaasContext</code> objects.
+     */
+    private List<IaasContext> iaasContextList = new ArrayList<IaasContext>();
+
+    /**
+     * We keep track of the IaaS where the last instance of a domain and a sub domain combination is spawned.
+     * This is required when there are multiple <code>IaasProvider</code>s defined.
+     * Key - domain
+     * Value - a map which has a Key - sub domain and Value - name of the {@link IaasProvider}.
+     */
+    private Map<String, Map<String, String>> lastlyUsedIaasMap = new HashMap<String, Map<String, String>>();
+
+    /**
+     * To track whether the {@link #initAutoscaler(boolean)} method has been called.
+     */
+    boolean isInitialized = false;
+
+    @Override
+    public boolean initAutoscaler(boolean isSpi) {
+
+        if (!isInitialized) {
+
+            log.debug("InitAutoscaler has started ...  IsSPI : " + isSpi);
+
+            // load configuration file
+            ElasticScalerConfigFileReader configReader = new ElasticScalerConfigFileReader();
+
+            // read serialization directory from config file if specified, else will use the
+            // default.
+            if ("".equals(serializationDir = configReader.getSerializationDir())) {
+                serializationDir = CARBON_TEMP;
+
+                log.debug("Directory to be used to serialize objects: " + serializationDir);
+            }
+
+            // let's deserialize and load the serialized objects.
+            deserialize();
+
+            // from config file, we grab the details unique to IaaS providers.
+            iaasProviders = configReader.getIaasProvidersList();
+
+            // from config file, we grab the details related to each service domain.
+            serviceTemps = configReader.getTemplates();
+
+            // we iterate through each IaaSProvider which is loaded from the config file.
+            for (IaasProvider iaas : iaasProviders) {
+
+                // build the JClouds specific ComputeService object
+                ComputeService computeService = ComputeServiceBuilder.buildComputeService(iaas);
+                IaasContext entity;
+
+                // let's see whether there's a serialized entity
+                entity = findIaasContext(iaas.getType());
+
+                if (entity != null) {
+
+                    log.debug("Serializable object is loaded for IaaS " + iaas.getType());
+
+                    // ComputeService isn't serializable, hence we need to set it in the
+                    // deserialized
+                    // object.
+                    entity.setComputeService(computeService);
+                }
+
+                // build JClouds Template objects according to different IaaSes
+                if (iaas.getType().equalsIgnoreCase(Iaases.ec2.toString())) {
+
+                    // initiate the IaasContext object, if it is null.
+                    entity =
+                             (entity == null) ? (entity =
+                                                          new IaasContext(Iaases.ec2,
+                                                                          computeService)) : entity;
+
+                    // we should build the templates only if this is not SPI stuff
+                    if (!isSpi) {
+                        // Build the Template
+                        buildEC2Templates(entity, iaas.getTemplate(), isSpi);
+
+                    } else {
+                        // add to data structure
+                        iaasContextList.add(entity);
+                    }
+
+                } else if (iaas.getType().equalsIgnoreCase(Iaases.openstack.toString())) {
+
+                    // initiate the IaasContext object, if it is null.
+                    entity =
+                             (entity == null) ? (entity =
+                                                          new IaasContext(Iaases.openstack,
+                                                                          computeService)) : entity;
+
+                    // we should build the templates only if this is not SPI stuff
+                    if (!isSpi) {
+                        // Build the Template
+                        buildLXCTemplates(entity, iaas.getTemplate(), isSpi, null);
+
+                    } else {
+                        // add to data structure
+                        iaasContextList.add(entity);
+                    }
+
+                } else {
+                    // unsupported IaaS detected. We only complain, since there could be other
+                    // IaaSes.
+                    String msg =
+                                 "Unsupported IaasProvider is specified in the config file: " +
+                                         iaas.getType() + ". Supported IaasProviders are " +
+                                         print(Iaases.values());
+                    log.warn(msg);
+                    continue;
+                }
+
+                // populate scale up order
+                fillInScaleUpOrder();
+
+                // populate scale down order
+                fillInScaleDownOrder();
+
+                // serialize the objects
+                serialize();
+            }
+
+            // we couldn't locate any valid IaaS providers from config file, thus shouldn't proceed.
+            if (iaasContextList.size() == 0) {
+                String msg = "No valid IaaS provider specified in the config file!";
+                log.error(msg);
+                throw new AutoscalerServiceException(msg);
+            }
+
+            // initialization completed.
+            isInitialized = true;
+
+            log.info("Autoscaler service initialized successfully!!");
+
+            return true;
+        }
+        
+        log.debug("Autoscaler Service is already initialized!");
+        return false;
+    }
+
+    
+    @Override
+    public boolean startInstance(String domainName, String subDomainName) {
+
+        // initialize the service, if it's not already initialized.
+        initAutoscaler(false);
+
+        ComputeService computeService;
+        Template template;
+        
+        subDomainName = checkSubDomain(subDomainName);
+
+        log.info("Starting new instance of domain : " + domainName+" and sub domain : "+subDomainName);
+
+        // sort the IaasContext entities according to scale up order
+        Collections.sort(iaasContextList,
+                         IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_UP_SORT)));
+
+        // traverse through IaasContext object instances in scale up order
+        for (IaasContext iaasCtxt : iaasContextList) {
+
+            // get the ComputeService
+            computeService = iaasCtxt.getComputeService();
+
+            // from the list grab the Template corresponds to this domain
+            template = iaasCtxt.getTemplate(domainName, subDomainName);
+            
+            if(template == null){
+                String msg = "Failed to start an instance in " + iaasCtxt.getName().toString() +
+                        ". Reason : Template is null. You have not specify a matching service " +
+                        "element in the configuration file of Autoscaler.\n Hence, will try to " +
+                        "start in another IaaS if available.";
+                log.error(msg);
+                continue;
+            }
+
+            // generate the group id from domain name and sub domain name.
+            // Should have lower-case ASCII letters, numbers, or dashes.
+            String str = domainName.concat("-"+subDomainName);
+            String group = str.replaceAll("[^a-z0-9-]", "");
+
+            try {
+                // create and start a node
+                Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(group,
+                                                                                      1,
+                                                                                      template);
+
+                NodeMetadata node = nodes.iterator().next();
+
+//                // add the details of the started node to maps
+//                iaasCtxt.addNodeIdToDomainMap(node.getId(), domainName);
+                
+                String ip="";
+
+                // set public Ip, if it's available
+                if (node.getPublicAddresses().size() > 0) {
+                    ip = node.getPublicAddresses().iterator().next();
+//                    iaasCtxt.addPublicIpToDomainMap(publicIp, domainName);
+//                    iaasCtxt.addPublicIpToNodeIdMap(publicIp, node.getId());
+                } else if(node.getPrivateAddresses().size() > 0) { // set private IPs if no public IP s are returned
+                	ip = node.getPrivateAddresses().iterator().next();
+//                    iaasCtxt.addPublicIpToDomainMap(privateIp, domainName);
+//                    iaasCtxt.addPublicIpToNodeIdMap(privateIp, node.getId());
+                } else{
+                    log.debug("Public IP of the node : "+node.getId()+" cannot be found.");
+                }
+                
+        
+                if (iaasCtxt.getInstanceContext(domainName, subDomainName) == null) {
+                    String msg = "Failed to start an instance in " + iaasCtxt.getName().toString() +
+                            ". Reason : InstanceContext is null. Hence, will try to start in another IaaS if available.";
+                    log.error(msg);
+                    continue;
+                }
+                
+                if(node.getId() == null){
+                    String msg = "Node id of the starting instance is null.\n"+ node.toString();
+                    log.fatal(msg);
+                    throw new AutoscalerServiceException(msg);
+                }
+
+                // add run time data to InstanceContext
+                iaasCtxt.addNodeDetails(domainName, subDomainName, node.getId(), ip);
+                
+                // since we modified the IaasContext instance, let's replace it.
+                replaceIaasContext(iaasCtxt);
+
+                // update the lastlyUsedIaasMap
+                addToLastlyUsedIaasMap(domainName, subDomainName, iaasCtxt.getName().toString());
+//                lastlyUsedIaasMap.put(domainName, iaasCtxt.getName().toString());
+
+                if (log.isDebugEnabled()) {
+                    log.debug("Node details: \n" + node.toString() +
+                              "\n***************\n");
+                }
+
+            } catch (RunNodesException e) {
+                log.warn("Failed to start an instance in " + iaasCtxt.getName().toString() +
+                         ". Hence, will try to start in another IaaS if available.", e);
+                continue;
+            }
+
+            log.info("Instance is successfully starting up in IaaS " + iaasCtxt.getName()
+                                                                               .toString() + " ...");
+
+            // serialize the objects
+            serialize();
+
+            return true;
+        }
+
+        log.info("Failed to start instance, in any available IaaS.");
+
+        return false;
+
+    }
+
+    private String checkSubDomain(String subDomainName) {
+        // if sub domain is null, we assume it as default one.
+        if (subDomainName == null || "null".equalsIgnoreCase(subDomainName)) {
+            subDomainName = Constants.DEFAULT_SUB_DOMAIN;
+            log.debug("Sub domain is null, hence using the default value : " + subDomainName);
+        }
+        
+        return subDomainName;
+    }
+
+
+    private void addToLastlyUsedIaasMap(String domainName, String subDomainName, String iaasName) {
+
+        Map<String, String> map;
+        
+        if(lastlyUsedIaasMap.get(domainName) == null){
+            map = new HashMap<String, String>();
+            
+        } else{
+            map = lastlyUsedIaasMap.get(domainName);
+        }
+        
+        map.put(subDomainName, iaasName);
+        lastlyUsedIaasMap.put(domainName, map);
+        
+    }
+
+
+    @Override
+    public String startSpiInstance(String domainName, String subDomainName, String imageId) {
+
+        log.debug("Starting an SPI instance ... | domain: " + domainName + " | sub domain: " +
+        subDomainName + " | ImageId: " + imageId);
+        
+        // initialize the service, if it's not already initialized.
+        initAutoscaler(true);
+        
+        String tenantId = null;
+        String spiDomainName = null;       
+        
+        if(domainName != null) {
+        	// domainName will have the pattern <domainName>/t/<tenantId>
+        	String[] arr = domainName.split(TENANT_ID_DELIMITER);
+        	if(arr.length != 2) {
+        		String msg = "Domain name does not match with the expected pattern. Expected " +
+        				"pattern is <domainName>/t/<tenantId>";
+        		log.error(msg);
+        		throw new AutoscalerServiceException(msg);
+        	}
+        	spiDomainName = arr[0];
+        	tenantId = arr[1];
+        }
+        
+        IaasContext entry;
+
+        // FIXME: Build the Templates, for now we're doing a hack here. I don't know whether
+        // there's a proper fix.
+        // handle openstack case
+        if (imageId.startsWith("nova") && ((entry = findIaasContext(Iaases.openstack)) != null)) {
+
+            buildLXCTemplates(entry, imageId, true, tenantId);
+
+        } else if (((entry = findIaasContext(Iaases.ec2)) != null)) {
+
+            buildEC2Templates(entry, imageId, true);
+
+        } else {
+            String msg = "Invalid image id: " + imageId;
+            log.error(msg);
+            throw new AutoscalerServiceException(msg);
+        }
+
+        // let's start the instance
+        if (startInstance(spiDomainName, subDomainName)) {
+
+            // if it's successful, get the public IP of the started instance.
+            // FIXME remove --> String publicIP =
+            // findIaasContext(iaas).getLastMatchingPublicIp(domainName);
+            String publicIP = entry.getLastMatchingPublicIp(spiDomainName, subDomainName);
+
+            // if public IP is null, return an empty string, else return public IP.
+            return (publicIP == null) ? "" : publicIP;
+
+        }
+
+        return "";
+
+    }
+
+	@Override
+    public boolean terminateInstance(String domainName, String subDomainName) {
+
+        // initialize the service, if it's not already initialized.
+	    initAutoscaler(false);
+        
+        subDomainName = checkSubDomain(subDomainName);
+
+        log.info("Starting to terminate an instance of domain : " + domainName + " and sub domain : "+subDomainName);
+
+        // sort the IaasContext entities according to scale down order.
+        Collections.sort(iaasContextList,
+                         IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_DOWN_SORT)));
+
+        // traverse in scale down order
+        for (IaasContext iaasTemp : iaasContextList) {
+
+            String msg = "Failed to terminate an instance in " + iaasTemp.getName().toString() +
+                         ". Hence, will try to terminate an instance in another IaaS if possible.";
+
+            String nodeId = null;
+
+            // grab the node ids related to the given domain and traverse
+            for (String id : iaasTemp.getNodeIds(domainName, subDomainName)) {
+                if (id != null) {
+                    nodeId = id;
+                    break;
+                }
+            }
+
+            // if no matching node id can be found.
+            if (nodeId == null) {
+
+                log.warn(msg + " : Reason- No matching instance found for domain: " +
+                         domainName + " and sub domain: "+subDomainName+
+                         ".");
+                continue;
+            }
+
+            // terminate it!
+            terminate(iaasTemp, nodeId);
+
+            return true;
+
+        }
+
+        log.info("Termination of an instance which is belong to domain '" + domainName +
+                 "' and sub domain '"+subDomainName+"' , failed!\n Reason: No matching " +
+                 		"running instance found in any available IaaS.");
+
+        return false;
+
+    }
+
+    @Override
+    public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) {
+
+        // initialize the service, if it's not already initialized.
+        initAutoscaler(false);
+        
+        subDomainName = checkSubDomain(subDomainName);
+
+        // see whether there is a matching IaaS, where we spawn an instance belongs to given domain.
+        if (lastlyUsedIaasMap.containsKey(domainName)) {
+
+            // grab the name of the IaaS
+            String iaas = lastlyUsedIaasMap.get(domainName).get(subDomainName);
+
+            // find the corresponding IaasContext
+            IaasContext iaasTemp = findIaasContext(iaas);
+
+            String msg = "Failed to terminate the lastly spawned instance of '" + domainName +
+                         "' service domain.";
+
+            if (iaasTemp == null) {
+                log.error(msg + " : Reason- Iaas' data cannot be located!");
+                return false;
+            }
+
+            // find the instance spawned at last of this IaasContext
+            String nodeId = iaasTemp.getLastMatchingNode(domainName, subDomainName);
+
+            if (nodeId == null) {
+                log.error(msg + " : Reason- No matching instance found for domain: " +
+                        domainName + " and sub domain: "+subDomainName+
+                        ".");
+                return false;
+            }
+
+            // terminate it!
+            terminate(iaasTemp, nodeId);
+
+            return true;
+
+        }
+
+        log.info("Termination of an instance which is belong to domain '" + domainName +
+                 "' and sub domain '"+subDomainName+"' , failed!\n Reason: No matching instance found.");
+
+        return false;
+    }
+
+    @Override
+    public boolean terminateSpiInstance(String publicIp) {
+
+        // initialize the service, if it's not already initialized.
+        initAutoscaler(true);
+
+        // sort the IaasContext entities according to scale down order.
+        Collections.sort(iaasContextList,
+                         IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_DOWN_SORT)));
+
+        // traverse in scale down order
+        for (IaasContext iaasTemp : iaasContextList) {
+
+            String msg = "Failed to terminate an instance in " + iaasTemp.getName().toString() +
+                         "" +
+                         ". Hence, will try to terminate an instance in another IaaS if possible.";
+
+            // grab the node maps with the given public IP address
+            String nodeId = iaasTemp.getNodeWithPublicIp(publicIp);
+
+            if (nodeId == null) {
+                log.warn(msg + " : Reason- No matching instance found for public ip '" +
+                         publicIp +
+                         "'.");
+                continue;
+            }
+
+            // terminate it!
+            terminate(iaasTemp, nodeId);
+
+            return true;
+        }
+
+        log.info("Termination of an instance which has the public IP '" + publicIp + "', failed!");
+
+        return false;
+    }
+
+    @Override
+    public int getPendingInstanceCount(String domainName, String subDomain) {
+
+        // initialize the service, if it's not already initialized.
+        initAutoscaler(false);
+        
+        subDomain = checkSubDomain(subDomain);
+
+        int pendingInstanceCount = 0;
+
+        // traverse through IaasContexts
+        for (IaasContext entry : iaasContextList) {
+
+            ComputeService computeService = entry.getComputeService();
+
+            // get list of node Ids which are belong to the requested domain
+            List<String> nodeIds = entry.getNodeIds(domainName, subDomain);
+            
+            if(nodeIds.isEmpty()){
+                log.debug("Zero nodes spawned in the IaaS "+entry.getName()+
+                          " of domain: "+domainName+" and sub domain: "+subDomain);
+                continue;
+            }
+
+            // get all the nodes spawned by this IaasContext
+            Set<? extends ComputeMetadata> set = computeService.listNodes();
+
+            Iterator<? extends ComputeMetadata> iterator = set.iterator();
+
+            // traverse through all nodes of this ComputeService object
+            while (iterator.hasNext()) {
+                NodeMetadataImpl nodeMetadata = (NodeMetadataImpl) iterator.next();
+
+                // if this node belongs to the requested domain
+                if (nodeIds.contains(nodeMetadata.getId())) {
+
+                    // get the status of the node
+                    Status nodeStatus = nodeMetadata.getStatus();
+
+                    // count nodes that are in pending state
+                    if (nodeStatus.toString().equalsIgnoreCase("PENDING")) {
+                        pendingInstanceCount++;
+                    }
+                }
+
+            }
+        }
+
+        log.info("Pending instance count of domain '" + domainName + "' and sub domain '"+
+        subDomain+"' is " + pendingInstanceCount);
+
+        return pendingInstanceCount;
+
+    }
+
+    /**
+     * Returns matching IaasContext for the given {@link Iaases} entry.
+     */
+    private IaasContext findIaasContext(Enum<Iaases> iaas) {
+
+        for (IaasContext entry : iaasContextList) {
+            if (entry.getName().equals(iaas)) {
+                return entry;
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Returns matching IaasContext for the given iaas type.
+     */
+    private IaasContext findIaasContext(String iaasType) {
+
+        for (IaasContext entry : iaasContextList) {
+            if (entry.getName().toString().equals(iaasType)) {
+                return entry;	
+            }
+        }
+
+        return null;
+    }
+
+    private void fillInScaleDownOrder() {
+
+        for (IaasProvider iaas : iaasProviders) {
+            if (findIaasContext(iaas.getType()) != null) {
+                findIaasContext(iaas.getType()).setScaleDownOrder(iaas.getScaleDownOrder());
+            }
+        }
+
+    }
+
+    private void fillInScaleUpOrder() {
+
+        for (IaasProvider iaas : iaasProviders) {
+            if (findIaasContext(iaas.getType()) != null) {
+                findIaasContext(iaas.getType()).setScaleUpOrder(iaas.getScaleUpOrder());
+            }
+        }
+
+    }
+
+    private byte[] getUserData(String payloadFileName, String tenantId) {
+ 
+    	byte[] bytes = null;
+    	File outputFile = null;
+    	String tempfilename = UUID.randomUUID().toString();
+        try {
+            File file = new File(payloadFileName);
+            if (!file.exists()) {
+                handleException("Payload file " + payloadFileName + " does not exist");
+            }
+            if (!file.canRead()) {
+                handleException("Payload file " + payloadFileName + " does cannot be read");
+            }
+            if(tenantId != null) {
+            	// Tenant Id is available. This is an spi scenario. Edit the payload content
+            	editPayload(tenantId,file,tempfilename);
+            	outputFile = new File(CARBON_HOME + File.separator + AutoscalerConstant.RESOURCES_DIR + File.separator + tempfilename+".zip");
+            } else {
+            	outputFile = file;
+            }
+            bytes = getBytesFromFile(outputFile);
+
+        } catch (IOException e) {
+            handleException("Cannot read data from payload file " + payloadFileName, e);
+        }
+        
+        // Remove temporary payload file
+        if (tenantId != null) {
+            outputFile.delete();
+        }
+        
+        return bytes;
+    }
+
+    
+    private void editPayload(String tenantName, File file, String tempfileName) {
+		
+    	unzipFile(file, tempfileName);
+    	editContent(tenantName, file, tempfileName);
+    	zipPayloadFile(tempfileName);    	
+	}
+
+    
+    /**
+	 * unzips the payload file
+	 * 
+	 * @param file
+     * @param tempfileName 
+	 */
+	private void unzipFile(File file, String tempfileName) {
+		
+		int buffer = 2048;
+		BufferedOutputStream dest = null;
+		ZipInputStream zis = null;
+		
+		try {
+			FileInputStream fis = new FileInputStream(file);
+			zis = new ZipInputStream(new BufferedInputStream(fis));
+			ZipEntry entry;
+			
+			while ((entry = zis.getNextEntry()) != null) {
+
+				log.debug("Extracting: " + entry);
+				
+				int count;
+				byte data[] = new byte[buffer];
+				String outputFilename = tempfileName + File.separator + entry.getName();
+				createDirIfNeeded(tempfileName, entry);
+
+				// write the files to the disk
+				if (!entry.isDirectory()) {
+					FileOutputStream fos = new FileOutputStream(outputFilename);
+					dest = new BufferedOutputStream(fos, buffer);
+					while ((count = zis.read(data, 0, buffer)) != -1) {
+						dest.write(data, 0, count);
+					}
+					dest.flush();
+					dest.close();
+				}
+			}
+			
+		} catch (Exception e) {
+			log.error("Exception is occurred in unzipping payload file. Reason:" + e.getMessage());
+			throw new AutoscalerServiceException(e.getMessage(), e);
+		} finally {
+			closeStream(zis);			
+			closeStream(dest);
+		}
+	}
+
+
+	private void closeStream(Closeable stream) {
+		if (stream != null) {
+			try {
+				stream.close();
+			} catch (IOException e) {
+				log.error(" Exception is occurred when closing stream. Reason :" + e.getMessage());
+			}
+		}
+	}
+
+	/**
+	 * 
+	 * Modify contents (tenantName) of the debian_cron_script.sh file
+	 * 
+	 * @param tenantName
+	 * @param file
+	 */
+	private void editContent(String tenantName, File file, String tempfileName) {
+
+		File f = new File(CARBON_HOME + File.separator + tempfileName
+				+ File.separator + AutoscalerConstant.PAYLOAD_DIR + File.separator
+				+ AutoscalerConstant.PARAMS_FILE_NAME);
+
+		FileInputStream fs = null;
+		InputStreamReader in = null;
+		BufferedReader br = null;
+
+		StringBuffer sb = new StringBuffer();
+
+		String textinLine;
+
+		try {
+			fs = new FileInputStream(f);
+			in = new InputStreamReader(fs);
+			br = new BufferedReader(in);
+
+			while (true) {
+				
+				textinLine=br.readLine();
+	            if(textinLine==null)
+	                break;
+	            sb.append(editLine(textinLine, tenantName));
+			}
+		} catch (Exception e) {
+			log.error("Exception is occurred in editing payload content. Reason: "+e.getMessage());
+			throw new AutoscalerServiceException(e.getMessage(), e);
+		} finally {
+			closeStream(fs);
+			closeStream(in);
+			closeStream(br);
+		}
+
+		writeChangesBackToFile(f, sb);
+	}
+
+
+	private String editLine(String textinLine, String tenantName) {
+		
+		// Format of the line will be <IP>=<IPvalue>,<Path>=<PathValue>..
+		
+		StringBuffer outputBuffer = new StringBuffer();
+		Map<String, String> paramMap = new HashMap<String, String>();
+		String[] params = textinLine.split(AutoscalerConstant.ENTRY_SEPARATOR);
+
+		for (int i = 0; i < params.length; i++) {
+
+			// split the params one by one
+			String param = params[i];
+			String[] values = param.split(AutoscalerConstant.VALUE_SEPARATOR);
+			
+			if(values.length != 2) {
+				throw new AutoscalerServiceException("Incorrect format in parameters file");
+			}
+			
+			String key = values[0];
+			String value = values[1];
+
+			String updatedValue = value;
+
+			if (AutoscalerConstant.TENANT_KEY.equals(key)) {
+				updatedValue = tenantName;
+			} else if (AutoscalerConstant.APP_PATH_KEY.equals(key)) {
+				updatedValue = getAppPathForTenant(tenantName,value);
+			} 
+			paramMap.put(key, updatedValue);
+		}
+
+		// Loop through the map and put values into a string
+		reOrganizeContent(outputBuffer, paramMap);
+
+		// cleanup output buffer
+		if (outputBuffer.substring(0, 1).equals(AutoscalerConstant.ENTRY_SEPARATOR)) {
+			outputBuffer.delete(0, 1);
+		}
+
+		return outputBuffer.toString();
+	}
+
+
+	private void reOrganizeContent(StringBuffer outputBuffer, Map<String, String> paramMap) {
+		
+		for (Map.Entry<String, String> entry : paramMap.entrySet()) {
+			outputBuffer.append(AutoscalerConstant.ENTRY_SEPARATOR).append(entry.getKey()).append(AutoscalerConstant.VALUE_SEPARATOR)
+																		.append(entry.getValue());
+		}
+	}
+
+
+	private String getAppPathForTenant(String tenantName, String appPath) {
+		// Assumes app path is /opt/wso2-app/repository/
+		StringBuffer updatedAppPath = new StringBuffer();
+		if(tenantName.equals(AutoscalerConstant.SUPER_TENANT_ID)){ 
+			updatedAppPath.append(appPath).append("deployment").append(File.separator).append("server")
+															   .append(File.separator).append("phpapps");
+		}else{
+			updatedAppPath.append(appPath).append(tenantName).append(File.separator).append("phpapps");
+		}
+		return updatedAppPath.toString();
+	}
+
+
+	private void writeChangesBackToFile(File f, StringBuffer sb) {
+		FileWriter fstream = null;
+		BufferedWriter outobj = null;
+		
+		try {
+			fstream = new FileWriter(f);
+			outobj = new BufferedWriter(fstream);
+			outobj.write(sb.toString());
+		} catch (Exception e) {
+			throw new RuntimeException(e);
+		} finally {
+			closeStream(outobj);
+		}
+	}
+	
+	/**
+	 * 
+	 * Compress the modified files back into payload.zip
+	 * @param tempfileName 
+	 * 
+	 */
+	private void zipPayloadFile(String tempfileName) {
+		
+		int buffer = 2048;
+		BufferedInputStream origin = null;
+		ZipOutputStream out = null;
+		
+		try {
+	         
+	         FileOutputStream dest = new 
+	           FileOutputStream(CARBON_HOME + File.separator + AutoscalerConstant.RESOURCES_DIR + File.separator + tempfileName+".zip");
+	         out = new ZipOutputStream(new BufferedOutputStream(dest));
+	         byte data[] = new byte[buffer];
+	         
+	         File f = new File(CARBON_HOME + File.separator + tempfileName + File.separator + AutoscalerConstant.PAYLOAD_DIR);
+	         String files[] = f.list();
+
+	         for (int i=0; i<files.length; i++) {
+	            FileInputStream fi = new FileInputStream(CARBON_HOME + File.separator + tempfileName
+		 				+ File.separator + AutoscalerConstant.PAYLOAD_DIR + File.separator + files[i]);
+	            origin = new BufferedInputStream(fi, buffer);
+	            ZipEntry entry = new ZipEntry(AutoscalerConstant.PAYLOAD_DIR + File.separator + files[i]);
+	            out.putNextEntry(entry);
+	            
+	            int count;
+	            while((count = origin.read(data, 0, buffer)) != -1) {
+	               out.write(data, 0, count);
+	            }
+	            origin.close();
+	         }
+	         
+	         // delete temp files
+	         deleteDir(f);
+	         File fl = new File(CARBON_HOME + File.separator + tempfileName);
+	         fl.delete();
+	         
+	      } catch(Exception e) {
+	    	  log.error("Exception is occurred in zipping payload file after modification. Reason:" + e.getMessage());
+	    	  throw new AutoscalerServiceException(e.getMessage(),e);
+	      } finally {
+	    	  closeStream(origin);	    	  
+	    	  closeStream(out);
+	      }
+	}	
+
+	private static boolean deleteDir(File dir) {
+	    if (dir.isDirectory()) {
+	        String[] children = dir.list();
+	        for (int i=0; i<children.length; i++) {
+	            boolean success = deleteDir(new File(dir, children[i]));
+	            if (!success) {
+	                return false;
+	            }
+	        }
+	    }
+
+	    // The directory is now empty so delete it
+	    return dir.delete();
+	}
+
+	private void createDirIfNeeded(String destDirectory, ZipEntry entry) {
+		
+		String name = entry.getName();
+
+        if(name.contains("/"))
+        {
+            log.debug("directory will need to be created");
+
+            int index = name.lastIndexOf("/");
+            String dirSequence = name.substring(0, index);
+
+            File newDirs = new File(destDirectory + File.separator + dirSequence);
+
+            //create the directory
+            newDirs.mkdirs();
+        }
+		
+	}
+
+
+	/**
+     * Returns the contents of the file in a byte array
+     * 
+     * @param file
+     *            - Input File
+     * @return Bytes from the file
+     * @throws java.io.IOException
+     *             , if retrieving the file contents failed.
+     */
+    private byte[] getBytesFromFile(File file) throws IOException {
+        if (!file.exists()) {
+            log.error("Payload file " + file.getAbsolutePath() + " does not exist");
+            return null;
+        }
+        InputStream is = new FileInputStream(file);
+        byte[] bytes;
+
+        try {
+            // Get the size of the file
+            long length = file.length();
+
+            // You cannot create an array using a long type.
+            // It needs to be an int type.
+            // Before converting to an int type, check
+            // to ensure that file is not larger than Integer.MAX_VALUE.
+            if (length > Integer.MAX_VALUE) {
+                if (log.isDebugEnabled()) {
+                    log.debug("File is too large");
+                }
+            }
+
+            // Create the byte array to hold the data
+            bytes = new byte[(int) length];
+
+            // Read in the bytes
+            int offset = 0;
+            int numRead;
+            while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
+                offset += numRead;
+            }
+
+            // Ensure all the bytes have been read in
+            if (offset < bytes.length) {
+                throw new IOException("Could not completely read file " + file.getName());
+            }
+        } finally {
+            // Close the input stream and return bytes
+            is.close();
+        }
+
+        return bytes;
+    }
+
+    /**
+     * handles the exception
+     * 
+     * @param msg
+     *            exception message
+     */
+    private void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+
+    /**
+     * handles the exception
+     * 
+     * @param msg
+     *            exception message
+     * @param e
+     *            exception
+     */
+    private static void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new SynapseException(msg, e);
+    }
+
+
+    /**
+     * This will replace an existing entry in iaasEntities list, if there's such.
+     * If not this will add the replacement value to the list.
+     * 
+     * @param replacement
+     *            IaasContext entry to be added.
+     */
+    private void replaceIaasContext(IaasContext replacement) {
+        for (IaasContext entry : iaasContextList) {
+            if (entry.equals(replacement)) {
+                int idx = iaasContextList.indexOf(entry);
+                iaasContextList.remove(idx);
+                iaasContextList.add(idx, replacement);
+                return;
+            }
+        }
+        iaasContextList.add(replacement);
+
+    }
+
+    /**
+     * Builds the LXC Template object.
+     */
+    private void buildLXCTemplates(IaasContext entity, String imageId, boolean blockUntilRunning, String tenantId) {
+
+        if (entity.getComputeService() == null) {
+            throw new AutoscalerServiceException("Compute service is null for IaaS provider: " + entity.getName());
+        }
+
+//        // if domain to template map is null
+//        if (entity.getDomainToTemplateMap() == null) {
+//            // we initialize it
+//            entity.setDomainToTemplateMap(new HashMap<String, Template>());
+//        }
+
+        TemplateBuilder templateBuilder = entity.getComputeService().templateBuilder();
+        templateBuilder.imageId(imageId);
+
+        // to avoid creation of template objects in each and every time, we create all
+        // at once!
+        for (ServiceTemplate temp : serviceTemps) {
+
+            String instanceType;
+
+            // set instance type 
+            if (((instanceType = temp.getProperty("instanceType." + Iaases.openstack.toString())) != null) ) {
+
+                templateBuilder.hardwareId(instanceType);
+            }
+
+            Template template = templateBuilder.build();
+
+            template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
+
+            template.getOptions()
+                    .as(NovaTemplateOptions.class)
+                    .securityGroupNames(temp.getProperty("securityGroups").split(AutoscalerConstant.ENTRY_SEPARATOR));
+
+            if (temp.getProperty(AutoscalerConstant.PAYLOAD_DIR) != null) {
+                template.getOptions()
+                        .as(NovaTemplateOptions.class)
+                        .userData(getUserData(CARBON_HOME + File.separator +
+                                              temp.getProperty(AutoscalerConstant.PAYLOAD_DIR), tenantId));
+            }
+
+            template.getOptions()
+                    .as(NovaTemplateOptions.class)
+                    .keyPairName(temp.getProperty("keyPair"));
+
+            // add to the data structure
+            if (entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()) == null) {
+                entity.addInstanceContext(new InstanceContext(temp.getDomainName(),
+                                                              temp.getSubDomainName(), template));
+            }
+            else{
+                entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()).setTemplate(template);
+            }
+
+        }
+
+        // since we modified the Context, we need to replace
+        replaceIaasContext(entity);
+    }
+
+    /**
+     * Builds EC2 Template object
+     * 
+     */
+    private void buildEC2Templates(IaasContext entity, String imageId, boolean blockUntilRunning) {
+
+        if (entity.getComputeService() == null) {
+            throw new AutoscalerServiceException("Compute service is null for IaaS provider: " + entity.getName());
+        }
+
+//        // if domain to template map is null
+//        if (entity.getDomainToTemplateMap() == null) {
+//            // we initialize it
+//            entity.setDomainToTemplateMap(new HashMap<String, Template>());
+//        }
+
+        TemplateBuilder templateBuilder = entity.getComputeService().templateBuilder();
+
+        // set image id specified
+        templateBuilder.imageId(imageId);
+
+        // to avoid creation of template objects in each and every time, we create all
+        // at once! FIXME we could use caching and lazy loading
+        for (ServiceTemplate temp : serviceTemps) {
+
+            if (temp.getProperty("instanceType." + Iaases.ec2.toString()) != null) {
+                // set instance type eg: m1.large
+                templateBuilder.hardwareId(temp.getProperty("instanceType." + Iaases.ec2.toString()));
+            }
+
+            // build the Template
+            Template template = templateBuilder.build();
+
+            // make it non blocking
+            template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
+
+            // set EC2 specific options
+            template.getOptions()
+                    .as(AWSEC2TemplateOptions.class)
+                    .placementGroup(temp.getProperty("availabilityZone"));
+
+            template.getOptions()
+                    .as(AWSEC2TemplateOptions.class)
+                    .securityGroups(temp.getProperty("securityGroups").split(AutoscalerConstant.ENTRY_SEPARATOR));
+
+            if (temp.getProperty(AutoscalerConstant.PAYLOAD_DIR) != null) {
+                template.getOptions()
+                        .as(AWSEC2TemplateOptions.class)
+                        .userData(getUserData(CARBON_HOME + File.separator +
+                                              temp.getProperty(AutoscalerConstant.PAYLOAD_DIR), null));
+            }
+
+            template.getOptions()
+                    .as(AWSEC2TemplateOptions.class)
+                    .keyPair(temp.getProperty("keyPair"));
+
+            // add to the data structure
+            if (entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()) == null) {
+                entity.addInstanceContext(new InstanceContext(temp.getDomainName(),
+                                                              temp.getSubDomainName(), template));
+            }
+            else{
+                entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()).setTemplate(template);
+            }
+
+        }
+
+        // since we modified the Context, we need to replace
+        replaceIaasContext(entity);
+
+    }
+
+    private String print(Iaases[] values) {
+        String str = "";
+        for (Iaases iaases : values) {
+            str = iaases.name() + ", ";
+        }
+        str = str.trim();
+        return str.endsWith(AutoscalerConstant.ENTRY_SEPARATOR) ? str.substring(0, str.length() - 1) : str;
+    }
+
+    @SuppressWarnings("unchecked")
+    private void deserialize() {
+
+        String path;
+
+        try {
+            path = serializationDir + File.separator +
+                   AutoscalerConstant.IAAS_CONTEXT_LIST_SERIALIZING_FILE;
+
+            Object obj = Deserializer.deserialize(path);
+            if (obj != null) {
+                iaasContextList = (List<IaasContext>) obj;
+                log.debug("Deserialization was successful from file: " + path);
+            }
+
+            path = serializationDir + File.separator +
+                   AutoscalerConstant.LASTLY_USED_IAAS_MAP_SERIALIZING_FILE;
+
+            obj = Deserializer.deserialize(path);
+
+            if (obj != null) {
+                lastlyUsedIaasMap = (Map<String, Map<String, String>>) obj;
+                log.debug("Deserialization was successful from file: " + path);
+            }
+
+        } catch (Exception e) {
+            String msg = "Deserialization of objects failed!";
+            log.fatal(msg, e);
+            throw new DeserializationException(msg, e);
+        }
+
+    }
+
+    /**
+     * Does all the serialization stuff!
+     */
+    private void serialize() {
+
+        try {
+            Serializer.serialize(iaasContextList,
+                                 serializationDir + File.separator +
+                                         AutoscalerConstant.IAAS_CONTEXT_LIST_SERIALIZING_FILE);
+
+            Serializer.serialize(lastlyUsedIaasMap,
+                                 serializationDir + File.separator +
+                                         AutoscalerConstant.LASTLY_USED_IAAS_MAP_SERIALIZING_FILE);
+
+        } catch (IOException e) {
+            String msg = "Serialization of objects failed!";
+            log.fatal(msg, e);
+            throw new SerializationException(msg, e);
+        }
+    }
+
+    /**
+     * A helper method to terminate an instance.
+     */
+    private void terminate(IaasContext iaasTemp, String nodeId) {
+
+        // this is just to be safe
+        if (iaasTemp.getComputeService() == null) {
+            String msg = "Unexpeced error occured! IaasContext's ComputeService is null!";
+            log.error(msg);
+            throw new AutoscalerServiceException(msg);
+        }
+
+        // destroy the node
+        iaasTemp.getComputeService().destroyNode(nodeId);
+
+        // remove the node id from the Context
+        iaasTemp.removeNodeId(nodeId);
+
+        // replace this IaasContext instance, as it reflects the new changes.
+        replaceIaasContext(iaasTemp);
+
+        // serialize the objects
+        serialize();
+
+        log.info("Node with Id: '" + nodeId + "' is terminated!");
+    }
+
+    /**
+     * Comparator to compare IaasContexts on different attributes.
+     */
+    public enum IaasContextComparator implements Comparator<IaasContext> {
+        SCALE_UP_SORT {
+            public int compare(IaasContext o1, IaasContext o2) {
+                return Integer.valueOf(o1.getScaleUpOrder()).compareTo(o2.getScaleUpOrder());
+            }
+        },
+        SCALE_DOWN_SORT {
+            public int compare(IaasContext o1, IaasContext o2) {
+                return Integer.valueOf(o1.getScaleDownOrder()).compareTo(o2.getScaleDownOrder());
+            }
+        };
+
+        public static Comparator<IaasContext> ascending(final Comparator<IaasContext> other) {
+            return new Comparator<IaasContext>() {
+                public int compare(IaasContext o1, IaasContext o2) {
+                    return other.compare(o1, o2);
+                }
+            };
+        }
+
+        public static Comparator<IaasContext>
+                getComparator(final IaasContextComparator... multipleOptions) {
+            return new Comparator<IaasContext>() {
+                public int compare(IaasContext o1, IaasContext o2) {
+                    for (IaasContextComparator option : multipleOptions) {
+                        int result = option.compare(o1, o2);
+                        if (result != 0) {
+                            return result;
+                        }
+                    }
+                    return 0;
+                }
+            };
+        }
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/internal/AutoscalerServiceDSComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/internal/AutoscalerServiceDSComponent.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/internal/AutoscalerServiceDSComponent.java
new file mode 100644
index 0000000..71df23c
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/internal/AutoscalerServiceDSComponent.java
@@ -0,0 +1,48 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.autoscaler.service.internal;
+
+import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.apache.stratos.autoscaler.service.IAutoscalerService;
+
+/**
+ * Registering Autoscaler Service.
+ * @scr.component name="org.apache.stratos.autoscaler.service" immediate="true"
+ */
+public class AutoscalerServiceDSComponent {
+
+    private static final Log log = LogFactory.getLog(AutoscalerServiceDSComponent.class);
+
+    protected void activate(ComponentContext context) {
+        try {
+            BundleContext bundleContext = context.getBundleContext();
+            bundleContext.registerService(IAutoscalerService.class.getName(),
+                                          new AutoscalerServiceImpl(), null);
+
+            log.debug("******* Autoscaler Service bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("******* Autoscaler Service bundle is failed to activate ****", e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/io/Deserializer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/io/Deserializer.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/io/Deserializer.java
new file mode 100644
index 0000000..8732094
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/io/Deserializer.java
@@ -0,0 +1,68 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.io;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class Deserializer {
+    
+    private static final Log log = LogFactory.getLog(Deserializer.class);
+
+    /**
+     * We deserialize only if the path to the serialized object file is exists.
+     * @param filePath path to the serialized object file
+     * @return the object obtained after deserialization or null if file isn't valid.
+     * @throws Exception
+     */
+    public static Object deserialize(String filePath) throws Exception {
+
+        ObjectInputStream objIn = null; 
+        Object obj = null;
+        
+        if(!new File(filePath).isFile()){
+            return obj;
+        }
+        
+        try {
+
+            objIn = new ObjectInputStream(new FileInputStream(filePath));
+            obj = objIn.readObject();
+
+        } catch (IOException e) {
+            log.error("Failed to deserialize the file at "+filePath , e);
+            throw e;
+            
+        } catch (ClassNotFoundException e) {
+            log.error("Failed to deserialize the file at "+filePath , e);
+            throw e;
+            
+        } finally{
+            objIn.close();
+        }
+        
+        return obj;
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/io/Serializer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/io/Serializer.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/io/Serializer.java
new file mode 100644
index 0000000..16f27c4
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/io/Serializer.java
@@ -0,0 +1,61 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.io;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class Serializer {
+    
+    private static final Log log = LogFactory.getLog(Serializer.class);
+
+    public static void serialize(Object serializableObj, String filePath) throws IOException {
+
+        File outFile = new File(filePath);
+        ObjectOutput ObjOut = null;
+        
+        try {
+
+            if(outFile.createNewFile()){
+                log.debug("Serialization file is created at "+filePath);
+            } else{
+                log.debug("Serialization file is already existing at "+filePath);
+            }
+            
+            ObjOut = new ObjectOutputStream(new FileOutputStream(outFile));
+            ObjOut.writeObject(serializableObj);
+
+        } catch (IOException e) {
+            log.error("Failed to serialize the object "+serializableObj.toString()
+                      + " to file "+filePath , e);
+            throw e;
+            
+        } finally{
+            ObjOut.close();
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/jcloud/ComputeServiceBuilder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/jcloud/ComputeServiceBuilder.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/jcloud/ComputeServiceBuilder.java
new file mode 100644
index 0000000..b8d5615
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/jcloud/ComputeServiceBuilder.java
@@ -0,0 +1,65 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.jcloud;
+
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.stratos.autoscaler.service.util.IaasProvider;
+import org.jclouds.ContextBuilder;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.ComputeServiceContext;
+import org.jclouds.enterprise.config.EnterpriseConfigurationModule;
+import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
+import org.jclouds.sshj.config.SshjSshClientModule;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.inject.Module;
+
+/**
+ * This class is responsible for creating a JClouds specific ComputeService object instances.
+ */
+public class ComputeServiceBuilder {
+    
+    public static ComputeService buildComputeService(IaasProvider iaas) {
+
+        Properties properties = new Properties();
+
+        // load properties
+        for (Map.Entry<String, String> entry : iaas.getProperties().entrySet()) {
+            properties.put(entry.getKey(), entry.getValue());
+        }
+
+        // set modules
+        Iterable<Module> modules =
+            ImmutableSet.<Module> of(new SshjSshClientModule(), new SLF4JLoggingModule(),
+                                     new EnterpriseConfigurationModule());
+
+        // build context
+        ContextBuilder builder =
+            ContextBuilder.newBuilder(iaas.getProvider())
+                          .credentials(iaas.getIdentity(), iaas.getCredential()).modules(modules)
+                          .overrides(properties);
+
+        // return the compute service object
+        return builder.buildView(ComputeServiceContext.class).getComputeService();
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/AutoscalerConstant.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/AutoscalerConstant.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/AutoscalerConstant.java
new file mode 100644
index 0000000..ba07a0b
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/AutoscalerConstant.java
@@ -0,0 +1,73 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.util;
+
+public final class AutoscalerConstant {
+
+    /**
+     * elastic-scaler-config XML file's elements
+     */
+    public static final String SERIALIZATION_DIR_ELEMENT = "serializationDir";
+    public static final String IAAS_PROVIDER_ELEMENT = "iaasProvider";
+    public static final String IAAS_PROVIDER_TYPE_ATTR = "type";
+    public static final String IAAS_PROVIDER_NAME_ATTR = "name";
+    public static final String PROPERTY_ELEMENT = "property";
+    public static final String PROPERTY_NAME_ATTR= "name";
+    public static final String PROPERTY_VALUE_ATTR = "value";
+    public static final String IMAGE_ID_ELEMENT = "imageId";
+    public static final String SCALE_DOWN_ORDER_ELEMENT = "scaleDownOrder";
+    public static final String SCALE_UP_ORDER_ELEMENT = "scaleUpOrder";
+    public static final String PROVIDER_ELEMENT = "provider";
+    public static final String IDENTITY_ELEMENT = "identity";
+    public static final String CREDENTIAL_ELEMENT = "credential";
+    public static final String DEFAULT_SERVICE_ELEMENT = "default";
+    public static final String SERVICE_ELEMENT = "service";
+    public static final String SERVICE_DOMAIN_ATTR = "domain";
+    public static final String SERVICE_SUB_DOMAIN_ATTR = "subDomain";
+    
+    /**
+     * Secret Manager related aliases.
+     */
+    public static final String EC2_IDENTITY_ALIAS = "elastic.scaler.ec2.identity";
+    public static final String EC2_CREDENTIAL_ALIAS = "elastic.scaler.ec2.credential";
+    public static final String OPENSTACK_IDENTITY_ALIAS = "elastic.scaler.openstack.identity";
+    public static final String OPENSTACK_CREDENTIAL_ALIAS = "elastic.scaler.openstack.credential";
+    
+    /**
+     * Serializer related constants
+     */
+    public static final String IAAS_CONTEXT_LIST_SERIALIZING_FILE = "iaas-context-list.txt";
+    public static final String LASTLY_USED_IAAS_MAP_SERIALIZING_FILE = "lastly-used-iaas.txt";
+    
+    /**
+     * Payload related constants
+     */
+    public static final String PAYLOAD_DIR = "payload";
+    public static final String PARAMS_FILE_NAME = "launch-params";
+    public static final String RESOURCES_DIR = "resources";
+    public static final String VALUE_SEPARATOR = "=";
+    public static final String ENTRY_SEPARATOR = ",";
+    public static final String APP_PATH_KEY = "APP_PATH";
+    public static final String TENANT_KEY = "TENANT";
+    
+    /**
+	 * Super tenant id
+	 */
+    public static final String SUPER_TENANT_ID = "-1234";
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/IaasContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/IaasContext.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/IaasContext.java
new file mode 100644
index 0000000..82f5473
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/IaasContext.java
@@ -0,0 +1,391 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.util;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+
+import org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl;
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.domain.Template;
+
+/**
+ * This object holds all IaaS related runtime data.
+ */
+public class IaasContext implements Serializable{
+   
+    private static final long serialVersionUID = -922284976926131383L;
+    
+    // name of the IaaS
+    private Enum<AutoscalerServiceImpl.Iaases> name;
+    
+    /* We keep following maps in order to make the look up time, low.*/
+    
+    /**
+     * Key - domain
+     * Value - is another map
+     *          key - sub domain
+     *          value - <code>InstanceContext</code>
+     */
+    private Map<String, Map<String, InstanceContext>> instanceCtxts;
+    
+    /**
+     * Key - public IP
+     * Value - <code>InstanceContext</code>
+     */
+    private Map<String, InstanceContext> publicIpToInstanceCtxt;
+    
+    /**
+     * Key - node id 
+     * Value - <code>InstanceContext</code>
+     */
+    private Map<String, InstanceContext> nodeIdToInstanceCtxt;
+    
+    
+//    private transient Map<String, Template> domainToTemplateMap;
+    private transient ComputeService computeService;
+    
+    // Since Jclouds' NodeMetadata object contains unserializable objects, I had to use 3 maps.
+//    private Map<String, String> nodeIdToDomainMap = new LinkedHashMap<String, String>();
+//    private Map<String, String> publicIpToDomainMap = new LinkedHashMap<String, String>();
+//    private Map<String, String> publicIpToNodeIdMap = new LinkedHashMap<String, String>();
+    
+    private int scaleUpOrder, scaleDownOrder;
+
+    public IaasContext(Enum<AutoscalerServiceImpl.Iaases> name, ComputeService computeService) {
+        this.name = name;
+        this.computeService = computeService;
+        instanceCtxts = new LinkedHashMap<String, Map<String,InstanceContext>>();
+        publicIpToInstanceCtxt = new LinkedHashMap<String, InstanceContext>();
+        nodeIdToInstanceCtxt = new LinkedHashMap<String, InstanceContext>();
+    }
+
+    public Enum<AutoscalerServiceImpl.Iaases> getName() {
+        return name;
+    }
+    
+    public void addInstanceContext(InstanceContext ctx) {
+        
+        if(ctx == null){
+            return;
+        }
+        
+        String domain = ctx.getDomain();
+        String subDomain = ctx.getSubDomain();
+        
+        if(domain != null && subDomain != null){
+            addToInstanceCtxts(domain, subDomain, ctx);
+        }
+        
+    }
+    
+    public void addNodeDetails(String domain, String subDomain, String nodeId, String ip) {
+        
+        if(getInstanceContext(domain, subDomain) != null){
+            getInstanceContext(domain, subDomain).addNode(nodeId, ip);
+            
+            nodeIdToInstanceCtxt.put(nodeId, getInstanceContext(domain, subDomain));
+            publicIpToInstanceCtxt.put(ip, getInstanceContext(domain, subDomain));
+        }
+    }
+    
+    private void addToInstanceCtxts(String domainName, String subDomainName, InstanceContext ctx) {
+
+        Map<String, InstanceContext> map;
+        
+        if(instanceCtxts.get(domainName) == null){
+            map = new HashMap<String, InstanceContext>();
+            
+        } else{
+            map = instanceCtxts.get(domainName);
+        }
+        
+        map.put(subDomainName, ctx);
+        instanceCtxts.put(domainName, map);
+        
+    }
+
+//    public void addToDomainToTemplateMap(String key, Template value) {
+//        domainToTemplateMap.put(key, value);
+//    }
+
+    public Template getTemplate(String domain, String subDomain) {
+        if(getInstanceContext(domain, subDomain) == null){
+            return null;
+        }
+        return getInstanceContext(domain, subDomain).getTemplate();
+    }
+    
+    public InstanceContext getInstanceContext(String domain, String subDomain) {
+        if (instanceCtxts.get(domain) != null) {
+            return instanceCtxts.get(domain).get(subDomain);
+        }
+        return null;
+    }
+
+    public ComputeService getComputeService() {
+        return computeService;
+    }
+    
+    public void setComputeService(ComputeService computeService) {
+        this.computeService = computeService;
+    }
+
+//    public void addNodeIdToDomainMap(String nodeId, String domain) {
+//        nodeIdToDomainMap.put(nodeId, domain);
+//    }
+//    
+//    public void addPublicIpToDomainMap(String ip, String domain) {
+//        publicIpToDomainMap.put(ip, domain);
+//    }
+//    
+//    public void addPublicIpToNodeIdMap(String ip, String nodeId) {
+//        publicIpToNodeIdMap.put(ip, nodeId);
+//    }
+
+    /**
+     * This will return the node id of the node which is belong to the
+     * requesting domain, sub domain and which is the most recently created. If it cannot find a
+     * matching node id, this will return <code>null</code>.
+     * @param domain service domain.
+     * @param subDomain service sub domain. 
+     * @return the node Id of the node
+     */
+    public String getLastMatchingNode(String domain, String subDomain) {
+        
+        InstanceContext ctx = getInstanceContext(domain, subDomain);
+        
+        if(ctx == null){
+            return null;
+        }
+        
+        // iterate in reverse order
+        ListIterator<String> iter =
+            new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
+                                listIterator(ctx.getNodeIdToIpMap().size());
+
+        if (iter.hasPrevious()) {
+            return iter.previous();
+        }
+        
+        return null;
+    }
+    
+    /**
+     * This will return the public IP of the node which is belong to the
+     * requesting domain, sub domain and which is the most recently created. If it cannot find a
+     * matching public IP, this will return <code>null</code>.
+     * @param domain service domain. 
+     * @param subDomain service sub domain. 
+     * @return the public IP of the node
+     */
+    public String getLastMatchingPublicIp(String domain, String subDomain) {
+        
+        InstanceContext ctx = getInstanceContext(domain, subDomain);
+        
+        if(ctx == null){
+            return null;
+        }
+        
+        // iterate in reverse order
+        ListIterator<String> iter =
+            new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
+                                listIterator(ctx.getNodeIdToIpMap().size());
+
+        while (iter.hasPrevious()) {
+            return ctx.getNodeIdToIpMap().get(iter.previous());
+        }
+        
+        return null;
+        
+//        // traverse from the last entry of the map
+//        ListIterator<Map.Entry<String, String>> iter =
+//            new ArrayList<Entry<String, String>>(publicIpToDomainMap.entrySet()).
+//                                listIterator(publicIpToDomainMap.size());
+//
+//        while (iter.hasPrevious()) {
+//            Map.Entry<String, String> entry = iter.previous();
+//            if (entry.getValue().equals(domain)) {
+//                return entry.getKey();
+//            }
+//        }
+//        
+//        return null;
+    }
+
+    /**
+     * This will return the node id of the node which is belong to the
+     * requesting domain, sub domain and which is created at first. If it cannot find a
+     * matching node id, this will return <code>null</code>.
+     * @param domain service domain.
+     * @param subDomain service sub domain.
+     * @return node id of the node
+     */
+    public String getFirstMatchingNode(String domain, String subDomain) {
+        
+        InstanceContext ctx = getInstanceContext(domain, subDomain);
+        
+        if(ctx == null){
+            return null;
+        }
+        
+        // iterate in added order
+        ListIterator<String> iter =
+            new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
+                                listIterator(0);
+
+        while (iter.hasNext()) {
+            return iter.next();
+        }
+        
+        return null;
+        
+//        for (Entry<String, String> entry : nodeIdToDomainMap.entrySet()) {
+//            if (entry.getValue().equals(domain)) {
+//                return entry.getKey();
+//            }
+//        }
+//        return null;
+    }
+
+    /**
+     * This will return the node id of the node which has the given public IP. 
+     * If it cannot find a matching node id, this will return 
+     * <code>null</code>.
+     * @param publicIp public IP of a node.
+     * @return node id of the matching node.
+     */
+    public String getNodeWithPublicIp(String publicIp) {
+
+        InstanceContext ctx;
+
+        for (String ip : publicIpToInstanceCtxt.keySet()) {
+
+            if (ip.equals(publicIp)) {
+
+                ctx = publicIpToInstanceCtxt.get(ip);
+
+                for (String nodeId : nodeIdToInstanceCtxt.keySet()) {
+                    if (ctx.equals(nodeIdToInstanceCtxt.get(nodeId))) {
+                        return nodeId;
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * This will return a list of node Ids that are started in this IaaS and that are 
+     * belong to the given domain, sub domain.
+     * @param domain service domain.
+     * @param subDomain service sub domain.
+     * @return List of node Ids.
+     */
+    public List<String> getNodeIds(String domain, String subDomain) {
+        
+        InstanceContext ctx = getInstanceContext(domain, subDomain);
+        
+        if(ctx == null){
+            return new ArrayList<String>();
+        }
+        
+        return new ArrayList<String>(ctx.getNodeIdToIpMap().keySet());
+        
+
+//        List<String> nodeIds = new ArrayList<String>();
+//
+//        for (Entry<String, String> entry : nodeIdToDomainMap.entrySet()) {
+//            if (entry.getValue().equals(domain)) {
+//                nodeIds.add(entry.getKey());
+//            }
+//        }
+//
+//        return nodeIds;
+    }
+
+    /**
+     * Removes a specific node id and related entries.
+     * @param node id of the node to be removed.
+     */
+    public void removeNodeId(String nodeId) {
+        
+        InstanceContext ctx;
+        
+        if(nodeIdToInstanceCtxt.containsKey(nodeId)){
+            // remove from node id map
+            ctx = nodeIdToInstanceCtxt.remove(nodeId);
+            
+            // remove from public ip map
+            publicIpToInstanceCtxt.remove(ctx.getNodeIdToIpMap().get(nodeId));
+            
+            // remove from main map
+            instanceCtxts.get(ctx.getDomain()).get(ctx.getSubDomain()).removeNode(nodeId);
+            
+        }
+    }
+
+    public boolean equals(Object obj) {
+
+        if (obj instanceof IaasContext) {
+            return new EqualsBuilder().append(getName(), ((IaasContext) obj).getName()).isEquals();
+        }
+        return false;
+
+    }
+    
+    public int hashCode() {
+        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
+        append(name).
+        toHashCode();
+    }
+
+    public int getScaleDownOrder() {
+        return scaleDownOrder;
+    }
+
+    public void setScaleDownOrder(int scaleDownOrder) {
+        this.scaleDownOrder = scaleDownOrder;
+    }
+
+    public int getScaleUpOrder() {
+        return scaleUpOrder;
+    }
+
+    public void setScaleUpOrder(int scaleUpOrder) {
+        this.scaleUpOrder = scaleUpOrder;
+    }
+    
+//    public void setDomainToTemplateMap(Map<String, Template> map) {
+//        domainToTemplateMap = map;
+//    }
+//    
+//    public Map<String, Template> getDomainToTemplateMap() {
+//        return domainToTemplateMap;
+//    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/IaasProvider.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/IaasProvider.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/IaasProvider.java
new file mode 100644
index 0000000..aa123ac
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/IaasProvider.java
@@ -0,0 +1,141 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * This is the basic data structure which holds an IaaS specific details.
+ */
+public class IaasProvider {
+    
+    /**
+     * Unique id to identify this IaaS provider.
+     */
+    private String type;
+    
+    /**
+     * human description of this IaaS provider
+     */
+    private String name;
+    
+    /**
+     * Property map for this IaaS provider.
+     */
+    private Map<String, String> properties = new HashMap<String, String>();
+    
+    /**
+     * Image identifier.
+     */
+    private String template;
+    
+    /**
+     * Scale up order and scale down order of the IaaS.
+     */
+    private int scaleUpOrder, scaleDownOrder;
+    
+    private String provider, identity, credential;
+    
+//    public enum SortParameter {
+//        SCALE_UP, SCALE_DOWN
+//    }
+
+    
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String id) {
+        this.type = id;
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+    
+    public void setProperty(String key, String value) {
+        
+        if(key != null && value != null){
+            properties.put(key, value);
+        }
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+
+    public String getTemplate() {
+        return template;
+    }
+
+    public void setTemplate(String template) {
+        this.template = template;
+    }
+
+    public int getScaleUpOrder() {
+        return scaleUpOrder;
+    }
+
+    public void setScaleUpOrder(int scaleUpOrder) {
+        this.scaleUpOrder = scaleUpOrder;
+    }
+
+    public int getScaleDownOrder() {
+        return scaleDownOrder;
+    }
+
+    public void setScaleDownOrder(int scaleDownOrder) {
+        this.scaleDownOrder = scaleDownOrder;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getProvider() {
+        return provider;
+    }
+
+    public void setProvider(String provider) {
+        this.provider = provider;
+    }
+
+    public String getIdentity() {
+        return identity;
+    }
+
+    public void setIdentity(String identity) {
+        this.identity = identity;
+    }
+
+    public String getCredential() {
+        return credential;
+    }
+
+    public void setCredential(String credential) {
+        this.credential = credential;
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/InstanceContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/InstanceContext.java b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/InstanceContext.java
new file mode 100644
index 0000000..a1544bf
--- /dev/null
+++ b/components/org.apache.stratos.autoscaler.service/src/main/java/org/apache/stratos/autoscaler/service/util/InstanceContext.java
@@ -0,0 +1,93 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.autoscaler.service.util;
+
+import java.io.Serializable;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.jclouds.compute.domain.Template;
+
+/**
+ * This will hold the run-time data related to an instance.
+ * Instance can be an EC2 one, Openstack one etc.
+ */
+public class InstanceContext implements Serializable {
+
+    private static final long serialVersionUID = -2604902942512629140L;
+    private String domain;
+    private String subDomain;
+    private transient Template template;
+
+    /**
+     * Key - node Id
+     * Value - IP
+     */
+    private Map<String, String> nodeIdToIpMap;
+    
+    public InstanceContext(String domain, String subDomain, Template temp) {
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.template = temp;
+        nodeIdToIpMap = new LinkedHashMap<String, String>();
+    }
+//    
+//    public InstanceContext(String domain, String subDomain, Template temp, String nodeId, String publicIp) {
+//        this.domain = domain;
+//        this.subDomain = subDomain;
+//        this.template = temp;
+//        this.nodeId = nodeId;
+//        this.publicIp = publicIp;
+//    }
+
+    
+    public String getDomain() {
+        return domain;
+    }
+
+    public String getSubDomain() {
+        return subDomain;
+    }
+    
+    public Template getTemplate() {
+        return template;
+    }
+    
+    public void setTemplate(Template temp) {
+        this.template = temp;
+    }
+    
+    public void addNode(String nodeId, String ip) {
+        if("".equals(ip)){
+            ip = null;
+        }
+        nodeIdToIpMap.put(nodeId, ip);
+    }
+    
+    public void removeNode(String nodeId) {
+        nodeIdToIpMap.remove(nodeId);
+    }
+
+
+    public Map<String, String> getNodeIdToIpMap() {
+        return nodeIdToIpMap;
+    }
+
+    
+}


[36/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/AddDomainMappingCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/AddDomainMappingCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/AddDomainMappingCommand.java
deleted file mode 100644
index fe25f02..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/AddDomainMappingCommand.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.commons.cli.Options;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.CommandLineService;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class AddDomainMappingCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(AddDomainMappingCommand.class);
-
-	public AddDomainMappingCommand() {
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.ADD_DOMAIN_MAPPING_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "Map domain for the subscribed cartridge";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return "[Cartridge alias] [Domain]";
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args != null && args.length == 2) {
-			String alias = args[0];
-			String domain = args[1];
-			if (logger.isDebugEnabled()) {
-				logger.debug("Adding domain mapping {} for alias {}", domain, alias);
-			}
-
-			String domainToDisplay = null;
-
-			domainToDisplay = CommandLineService.getInstance().addDomainMapping(domain, alias);
-
-			if (StringUtils.isBlank(domainToDisplay)) {
-				System.out.println("Error adding domain mapping.");
-				return CliConstants.BAD_ARGS_CODE;
-			} else {
-				System.out.format("Your own domain is added. Please CNAME it to systems domain %s.%n", domainToDisplay);
-				return CliConstants.SUCCESSFUL_CODE;
-			}
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return null;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/CartridgesCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/CartridgesCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/CartridgesCommand.java
deleted file mode 100644
index fc7461f..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/CartridgesCommand.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.commons.cli.Options;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.CommandLineService;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class CartridgesCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(CartridgesCommand.class);
-
-	public CartridgesCommand() {
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.CARTRIDGES_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "List available cartridges";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return null;
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args == null || args.length == 0) {
-			CommandLineService.getInstance().listAvailableCartridges();
-			return CliConstants.SUCCESSFUL_CODE;
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return null;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ExitCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ExitCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ExitCommand.java
deleted file mode 100644
index e0ff8c3..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ExitCommand.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.commons.cli.Options;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class ExitCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(ExitCommand.class);
-
-	public ExitCommand() {
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.EXIT_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "Exit from Stratos Client Tool";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return null;
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		// Nothing to execute here. This is a special command.
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args == null || args.length == 0) {
-			return CliConstants.SUCCESSFUL_CODE;
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return null;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/HelpCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/HelpCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/HelpCommand.java
deleted file mode 100644
index ca74687..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/HelpCommand.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.commons.cli.Options;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class HelpCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(HelpCommand.class);
-
-	public HelpCommand() {
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.HELP_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "Help for commands";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return "[command]";
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args == null || args.length == 0) {
-			context.getStratosApplication().printHelp();
-			return CliConstants.SUCCESSFUL_CODE;
-		} else if (args != null && args.length == 1) {
-			context.getStratosApplication().printHelp(args[0]);
-			return CliConstants.SUCCESSFUL_CODE;
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return null;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/InfoCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/InfoCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/InfoCommand.java
deleted file mode 100644
index a4ac08e..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/InfoCommand.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.commons.cli.Options;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.CommandLineService;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class InfoCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(InfoCommand.class);
-
-	public InfoCommand() {
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.INFO_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "Get information about a subscribed cartridge";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return "[Cartridge alias]";
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args != null && args.length == 1) {
-			String alias = args[0];
-			if (logger.isDebugEnabled()) {
-				logger.debug("Getting info {}", alias);
-			}
-			CommandLineService.getInstance().info(alias);
-			return CliConstants.SUCCESSFUL_CODE;
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return null;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ListCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ListCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ListCommand.java
deleted file mode 100644
index 1b96182..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ListCommand.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.GnuParser;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.CommandLineService;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class ListCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(ListCommand.class);
-	
-	private final Options options;
-
-	public ListCommand() {
-		options = constructOptions();
-	}
-	
-	/**
-	 * Construct Options.
-	 * 
-	 * @return Options expected from command-line.
-	 */
-	private Options constructOptions() {
-		final Options options = new Options();
-		Option fullOption = new Option(CliConstants.FULL_OPTION, CliConstants.FULL_LONG_OPTION, false,
-				"Display extra details");
-		options.addOption(fullOption);
-		return options;
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.LIST_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "List subscribed cartridges with details";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return null;
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args == null || args.length == 0) {
-			CommandLineService.getInstance().listSubscribedCartridges(false);
-			return CliConstants.SUCCESSFUL_CODE;
-		} else if (args != null && args.length > 0) {
-			String[] remainingArgs = null;
-			boolean full = false;
-			final CommandLineParser parser = new GnuParser();
-			CommandLine commandLine;
-			try {
-				commandLine = parser.parse(options, args);
-				remainingArgs = commandLine.getArgs();
-				if (!(remainingArgs == null || remainingArgs.length == 0)) {
-					context.getStratosApplication().printUsage(getName());
-					return CliConstants.BAD_ARGS_CODE;
-				}
-
-				if (commandLine.hasOption(CliConstants.FULL_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("Full option is passed");
-					}
-					full = true;
-				}
-				if (logger.isDebugEnabled()) {
-					logger.debug("Listing subscribed cartridges, Full Option: {}", full);
-				}
-				CommandLineService.getInstance().listSubscribedCartridges(full);
-				return CliConstants.SUCCESSFUL_CODE;
-			} catch (ParseException e) {
-				if (logger.isErrorEnabled()) {
-					logger.error("Error parsing arguments", e);
-				}
-				System.out.println(e.getMessage());
-				return CliConstants.BAD_ARGS_CODE;
-			}
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return options;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/PoliciesCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/PoliciesCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/PoliciesCommand.java
deleted file mode 100644
index 4811efd..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/PoliciesCommand.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.commons.cli.Options;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.CommandLineService;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class PoliciesCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(PoliciesCommand.class);
-
-	public PoliciesCommand() {
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.POLICIES_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "List available policies";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return null;
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args == null || args.length == 0) {
-			CommandLineService.getInstance().listAvailablePolicies();
-			return CliConstants.SUCCESSFUL_CODE;
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return null;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/RemoveDomainMappingCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/RemoveDomainMappingCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/RemoveDomainMappingCommand.java
deleted file mode 100644
index a3b4cc0..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/RemoveDomainMappingCommand.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.CommandLineService;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-import org.apache.commons.cli.Options;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class RemoveDomainMappingCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(RemoveDomainMappingCommand.class);
-
-	public RemoveDomainMappingCommand() {
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.REMOVE_DOMAIN_MAPPING_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "Remove domain mapping for the subscribed cartridge";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return "[Cartridge alias]";
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args != null && args.length == 1) {
-			String alias = args[0];
-			if (logger.isDebugEnabled()) {
-				logger.debug("Removing domain mapping for {}", alias);
-			}
-			CommandLineService.getInstance().removeDomainMapping(alias);
-			return CliConstants.SUCCESSFUL_CODE;
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return null;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SubscribeCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SubscribeCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SubscribeCommand.java
deleted file mode 100644
index 90908e9..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SubscribeCommand.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.CommandLineService;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.GnuParser;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class SubscribeCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(ListCommand.class);
-
-	private final Options options;;
-
-	public SubscribeCommand() {
-		options = constructOptions();
-	}
-
-	/**
-	 * Construct Options.
-	 * 
-	 * @return Options expected from command-line.
-	 */
-	private Options constructOptions() {
-		final Options options = new Options();
-		Option policyOption = new Option(CliConstants.POLICY_OPTION, CliConstants.POLICY_LONG_OPTION, true,
-				"Auto-scaling policy.\nPlease use \"" + CliConstants.POLICIES_ACTION
-						+ "\" command to view the available policies.");
-		policyOption.setArgName("policy name");
-		options.addOption(policyOption);
-
-		Option connectOption = new Option(CliConstants.CONNECT_OPTION, CliConstants.CONNECT_LONG_OPTION, true,
-				"Data cartridge type");
-		connectOption.setArgName("data cartridge type");
-		options.addOption(connectOption);
-
-		Option aliasOption = new Option(CliConstants.DATA_ALIAS_OPTION, CliConstants.DATA_ALIAS_LONG_OPTION, true,
-				"Data cartridge alias");
-		aliasOption.setArgName("alias");
-		options.addOption(aliasOption);
-
-		Option urlOption = new Option(CliConstants.REPO_URL_OPTION, CliConstants.REPO_URL_LONG_OPTION, true,
-				"GIT repository URL");
-		urlOption.setArgName("url");
-		options.addOption(urlOption);
-
-		options.addOption(CliConstants.PRIVATE_REPO_OPTION, CliConstants.PRIVATE_REPO_LONG_OPTION, false,
-				"Private repository");
-
-		Option usernameOption = new Option(CliConstants.USERNAME_OPTION, CliConstants.USERNAME_LONG_OPTION, true,
-				"GIT repository username");
-		usernameOption.setArgName("username");
-		options.addOption(usernameOption);
-
-		Option passwordOption = new Option(CliConstants.PASSWORD_OPTION, CliConstants.PASSWORD_LONG_OPTION, true,
-				"GIT repository password");
-		passwordOption.setArgName("password");
-		passwordOption.setOptionalArg(true);
-		options.addOption(passwordOption);
-		return options;
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.SUBSCRIBE_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "Subscribe to a cartridge";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return "[Cartridge type] [Cartridge alias]";
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args != null && args.length > 0) {
-			String[] remainingArgs = null;
-			String type = null;
-			String alias = null;
-			String policy = null;
-			String repoURL = null, dataCartridgeType = null, dataCartridgeAlias = null, username = "", password = "";
-			boolean privateRepo = false;
-			final CommandLineParser parser = new GnuParser();
-			CommandLine commandLine;
-			try {
-				commandLine = parser.parse(options, args);
-				remainingArgs = commandLine.getArgs();
-				if (remainingArgs != null && remainingArgs.length == 2) {
-					// Get type
-					type = remainingArgs[0];
-					alias = remainingArgs[1];
-				} else {
-					context.getStratosApplication().printUsage(getName());
-					return CliConstants.BAD_ARGS_CODE;
-				}
-
-				if (logger.isDebugEnabled()) {
-					logger.debug("Subscribing to {} cartridge with alias {}", type, alias);
-				}
-
-				if (commandLine.hasOption(CliConstants.POLICY_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("Policy option is passed");
-					}
-					policy = commandLine.getOptionValue(CliConstants.POLICY_OPTION);
-				}
-				if (commandLine.hasOption(CliConstants.REPO_URL_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("RepoURL option is passed");
-					}
-					repoURL = commandLine.getOptionValue(CliConstants.REPO_URL_OPTION);
-				}
-				if (commandLine.hasOption(CliConstants.PRIVATE_REPO_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("privateRepo option is passed");
-					}
-					privateRepo = true;
-				}
-				if (commandLine.hasOption(CliConstants.USERNAME_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("Username option is passed");
-					}
-					username = commandLine.getOptionValue(CliConstants.USERNAME_OPTION);
-				}
-				if (commandLine.hasOption(CliConstants.PASSWORD_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("Password option is passed");
-					}
-					password = commandLine.getOptionValue(CliConstants.PASSWORD_OPTION);
-				}
-				if (commandLine.hasOption(CliConstants.CONNECT_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("Connect option is passed");
-					}
-					dataCartridgeType = commandLine.getOptionValue(CliConstants.CONNECT_OPTION);
-				}
-				if (commandLine.hasOption(CliConstants.DATA_ALIAS_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("Data alias option is passed");
-					}
-					dataCartridgeAlias = commandLine.getOptionValue(CliConstants.DATA_ALIAS_OPTION);
-				}
-				
-				if (StringUtils.isNotBlank(username) && StringUtils.isBlank(password)) {
-					password = context.getApplication().getInput("GIT Repository Password", '*');
-				}
-
-				if (StringUtils.isNotBlank(dataCartridgeType) && !StringUtils.isNotBlank(dataCartridgeAlias)) {
-					System.out.println("Data cartridge alias is required.");
-					context.getStratosApplication().printUsage(getName());
-					return CliConstants.BAD_ARGS_CODE;
-				}
-				CommandLineService.getInstance().subscribe(type, alias, policy, repoURL, privateRepo, username,
-						password, dataCartridgeType, dataCartridgeAlias);
-				return CliConstants.SUCCESSFUL_CODE;
-			} catch (ParseException e) {
-				if (logger.isErrorEnabled()) {
-					logger.error("Error parsing arguments", e);
-				}
-				System.out.println(e.getMessage());
-				return CliConstants.BAD_ARGS_CODE;
-			}
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return options;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SyncCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SyncCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SyncCommand.java
deleted file mode 100644
index 6e21a4d..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SyncCommand.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.commons.cli.Options;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.CommandLineService;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class SyncCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(SyncCommand.class);
-
-	public SyncCommand() {
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.SYNC_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "Synchronize GIT repository for the subscribed cartridge";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return "[Cartridge alias]";
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args != null && args.length == 1) {
-			String alias = args[0];
-			if (logger.isDebugEnabled()) {
-				logger.debug("Synchronizing repository for alias {}", alias);
-			}
-
-			CommandLineService.getInstance().sync(alias);
-			return CliConstants.SUCCESSFUL_CODE;
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return null;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/UnsubscribeCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/UnsubscribeCommand.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/UnsubscribeCommand.java
deleted file mode 100644
index 9b178e4..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/commands/UnsubscribeCommand.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.commands;
-
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.GnuParser;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.CommandLineService;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.exception.CommandException;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class UnsubscribeCommand implements Command<StratosCommandContext> {
-
-	private static final Logger logger = LoggerFactory.getLogger(UnsubscribeCommand.class);
-	
-	private final Options options;;
-
-	public UnsubscribeCommand() {
-		options = constructOptions();
-	}
-	
-	/**
-	 * Construct Options.
-	 * 
-	 * @return Options expected from command-line.
-	 */
-	private Options constructOptions() {
-		final Options options = new Options();
-		Option forceOption = new Option(CliConstants.FORCE_OPTION, CliConstants.FORCE_LONG_OPTION, false,
-				"Never prompt for confirmation");
-		options.addOption(forceOption);
-		return options;
-	}
-
-	@Override
-	public String getName() {
-		return CliConstants.UNSUBSCRIBE_ACTION;
-	}
-
-	@Override
-	public String getDescription() {
-		return "Unsubscribe from a subscribed cartridge";
-	}
-
-	@Override
-	public String getArgumentSyntax() {
-		return "[Cartridge alias]";
-	}
-
-	@Override
-	public int execute(StratosCommandContext context, String[] args) throws CommandException {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Executing {} command...", getName());
-		}
-		if (args != null && args.length > 0) {
-			String[] remainingArgs = null;
-			String alias = null;
-			boolean force = false;
-			final CommandLineParser parser = new GnuParser();
-			CommandLine commandLine;
-			try {
-				commandLine = parser.parse(options, args);
-				remainingArgs = commandLine.getArgs();
-				if (remainingArgs != null && remainingArgs.length == 1) {
-					// Get alias
-					alias = remainingArgs[0];
-				} else {
-					if (logger.isDebugEnabled()) {
-						logger.debug("Unsubscribe: not enough arguments");
-					}
-					context.getStratosApplication().printUsage(getName());
-					return CliConstants.BAD_ARGS_CODE;
-				}
-
-				if (commandLine.hasOption(CliConstants.FORCE_OPTION)) {
-					if (logger.isTraceEnabled()) {
-						logger.trace("Force option is passed");
-					}
-					force = true;
-				}
-				if (logger.isDebugEnabled()) {
-					logger.debug("Unsubscribing {}, Force Option: {}", alias, force);
-				}
-				if (force || context.getApplication().getConfirmation("Are you sure you want to unsubscribe?")) {
-					System.out.format("Unsubscribing the cartridge %s%n", alias);
-					CommandLineService.getInstance().unsubscribe(alias);
-				}
-				return CliConstants.SUCCESSFUL_CODE;
-			} catch (ParseException e) {
-				if (logger.isErrorEnabled()) {
-					logger.error("Error parsing arguments", e);
-				}
-				System.out.println(e.getMessage());
-				return CliConstants.BAD_ARGS_CODE;
-			}
-		} else {
-			context.getStratosApplication().printUsage(getName());
-			return CliConstants.BAD_ARGS_CODE;
-		}
-	}
-
-	@Override
-	public Options getOptions() {
-		return options;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/completer/CommandCompleter.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/completer/CommandCompleter.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/completer/CommandCompleter.java
deleted file mode 100644
index 3405762..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/completer/CommandCompleter.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.completer;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import jline.console.completer.ArgumentCompleter;
-import jline.console.completer.Completer;
-import jline.console.completer.StringsCompleter;
-
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.text.StrTokenizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.stratos.adc.mgt.cli.Command;
-import org.apache.stratos.adc.mgt.cli.StratosApplication;
-import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
-import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
-
-public class CommandCompleter implements Completer {
-
-	private static final Logger logger = LoggerFactory.getLogger(StratosApplication.class);
-
-	/**
-	 * Keep arguments for each command
-	 */
-	private final Map<String, Collection<String>> argumentMap;
-	
-	private final Completer helpCommandCompleter;
-
-	private final Completer defaultCommandCompleter;
-
-	public CommandCompleter(Map<String, Command<StratosCommandContext>> commands) {
-		if (logger.isDebugEnabled()) {
-			logger.debug("Creating auto complete for {} commands", commands.size());
-		}
-		argumentMap = new HashMap<String, Collection<String>>();
-		defaultCommandCompleter = new StringsCompleter(commands.keySet());
-		helpCommandCompleter = new ArgumentCompleter(new StringsCompleter(CliConstants.HELP_ACTION),
-				defaultCommandCompleter);
-		for (String action : commands.keySet()) {
-			Command<StratosCommandContext> command = commands.get(action);
-			Options commandOptions = command.getOptions();
-			if (commandOptions != null) {
-				if (logger.isDebugEnabled()) {
-					logger.debug("Creating argument completer for command: {}", action);
-				}
-				List<String> arguments = new ArrayList<String>();
-				Collection<?> allOptions = commandOptions.getOptions();
-				for (Object o : allOptions) {
-					Option option = (Option) o;
-					String longOpt = option.getLongOpt();
-					String opt = option.getOpt();
-					if (StringUtils.isNotBlank(longOpt)) {
-						arguments.add("--" + longOpt);
-					} else if (StringUtils.isNotBlank(opt)) {
-						arguments.add("-" + opt);
-					}
-				}
-
-				argumentMap.put(action, arguments);
-			}
-		}
-	}
-
-	@Override
-	public int complete(String buffer, int cursor, List<CharSequence> candidates) {
-		if (logger.isTraceEnabled()) {
-			logger.trace("Buffer: {}, cursor: {}", buffer, cursor);
-			logger.trace("Candidates {}", candidates);
-		}
-		if (StringUtils.isNotBlank(buffer)) {
-			// User is typing a command
-			StrTokenizer strTokenizer = new StrTokenizer(buffer);
-			String action = strTokenizer.next();
-			Collection<String> arguments = argumentMap.get(action);
-			if (arguments != null) {
-				if (logger.isTraceEnabled()) {
-					logger.trace("Arguments found for {}, Tokens: {}", action, strTokenizer.getTokenList());
-					logger.trace("Arguments for {}: {}", action, arguments);
-				}
-				List<String> args = new ArrayList<String>(arguments);
-				List<Completer> completers = new ArrayList<Completer>();
-				for (String token : strTokenizer.getTokenList()) {
-					boolean argContains = arguments.contains(token);
-					if (token.startsWith("-") && !argContains) {
-						continue;
-					}
-					if (argContains) {
-						if (logger.isTraceEnabled()) {
-							logger.trace("Removing argument {}", token);
-						}
-						args.remove(token);
-					}
-					completers.add(new StringsCompleter(token));
-				}
-				completers.add(new StringsCompleter(args));
-				Completer completer = new ArgumentCompleter(completers);
-				return completer.complete(buffer, cursor, candidates);
-			} else if (CliConstants.HELP_ACTION.equals(action)) {
-				// For help action, we need to display available commands as arguments
-				return helpCommandCompleter.complete(buffer, cursor, candidates);
-			}
-		}
-		if (logger.isTraceEnabled()) {
-			logger.trace("Using Default Completer...");
-		}
-		return defaultCommandCompleter.complete(buffer, cursor, candidates);
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/exception/CommandException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/exception/CommandException.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/exception/CommandException.java
deleted file mode 100644
index a462500..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/exception/CommandException.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.exception;
-
-public class CommandException extends Exception {
-
-	private static final long serialVersionUID = 1L;
-
-	public CommandException() {
-	}
-
-	public CommandException(String message) {
-		super(message);
-	}
-
-	public CommandException(Throwable cause) {
-		super(cause);
-	}
-
-	public CommandException(String message, Throwable cause) {
-		super(message, cause);
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CliConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CliConstants.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CliConstants.java
deleted file mode 100644
index 986bb72..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CliConstants.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-
-package org.apache.stratos.adc.mgt.cli.utils;
-
-/**
- * Constants for CLI Tool
- */
-public class CliConstants {
-
-	public static final String STRATOS_APPLICATION_NAME = "stratos";
-
-	public static final String STRATOS_URL_ENV_PROPERTY = "STRATOS_URL";
-
-	public static final String STRATOS_USERNAME_ENV_PROPERTY = "STRATOS_USERNAME";
-
-	public static final String STRATOS_PASSWORD_ENV_PROPERTY = "STRATOS_PASSWORD";
-
-	public static final String STRATOS_SHELL_PROMPT = "stratos> ";
-	
-	public static final int SUCCESSFUL_CODE = 0;
-	public static final int BAD_ARGS_CODE = 1;
-	public static final int ERROR_CODE = 2;
-
-
-	/**
-	 * The Directory for storing configuration
-	 */
-	public static final String STRATOS_DIR = ".stratos";
-	public static final String STRATOS_HISTORY_DIR = ".history";
-
-	public static final String HELP_ACTION = "help";
-
-	/**
-	 * Subscribe to a cartridge.
-	 */
-	public static final String SUBSCRIBE_ACTION = "subscribe";
-
-	public static final String UNSUBSCRIBE_ACTION = "unsubscribe";
-
-	/**
-	 * List the subscribed cartridges
-	 */
-	public static final String LIST_ACTION = "list";
-
-	/**
-	 * List the available cartridges
-	 */
-	public static final String CARTRIDGES_ACTION = "cartridges";
-
-	/**
-	 * Give information of a cartridge.
-	 */
-	public static final String INFO_ACTION = "info";
-
-	/**
-	 * Synchronize repository
-	 */
-	public static final String SYNC_ACTION = "sync";
-
-	/**
-	 * Domain mapping
-	 */
-	public static final String ADD_DOMAIN_MAPPING_ACTION = "add-domain-mapping";
-	/**
-	 * Remove Domain mapping
-	 */
-	public static final String REMOVE_DOMAIN_MAPPING_ACTION = "remove-domain-mapping";
-	
-	/**
-	 * List the available policies
-	 */
-	public static final String POLICIES_ACTION = "policies";
-
-	/**
-	 * Exit action
-	 */
-	public static final String EXIT_ACTION = "exit";
-
-	public static final String REPO_URL_OPTION = "r";
-	public static final String REPO_URL_LONG_OPTION = "repoURL";
-	
-	public static final String PRIVATE_REPO_OPTION = "i";
-	public static final String PRIVATE_REPO_LONG_OPTION = "privateRepo";
-
-	public static final String USERNAME_OPTION = "u";
-	public static final String USERNAME_LONG_OPTION = "username";
-
-	public static final String PASSWORD_OPTION = "p";
-	public static final String PASSWORD_LONG_OPTION = "password";
-
-	public static final String HELP_OPTION = "h";
-	public static final String HELP_LONG_OPTION = "help";
-	
-	public static final String POLICY_OPTION = "o";
-	public static final String POLICY_LONG_OPTION = "policy";
-	
-	public static final String CONNECT_OPTION = "c";
-	public static final String CONNECT_LONG_OPTION = "connect";
-	
-	public static final String DATA_ALIAS_OPTION = "d";
-	public static final String DATA_ALIAS_LONG_OPTION = "data-alias";
-	
-	public static final String FULL_OPTION = "f";
-	public static final String FULL_LONG_OPTION = "full";
-	
-	public static final String FORCE_OPTION = "f";
-	public static final String FORCE_LONG_OPTION = "force";
-	
-	public static final String TRACE_OPTION = "trace";
-	
-	public static final String DEBUG_OPTION = "debug";
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CommandLineUtils.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CommandLineUtils.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CommandLineUtils.java
deleted file mode 100644
index c6167f2..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/CommandLineUtils.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.utils;
-
-import java.text.MessageFormat;
-import java.util.ResourceBundle;
-
-public class CommandLineUtils {
-	
-	private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("Resources");
-
-	public static <T> void printTable(T[] data, RowMapper<T> mapper, String... headers) {
-		if (data == null) {
-			return;
-		}
-		// The maximum number of columns
-		// All data String[] length must be equal to this
-		int columns = headers.length;
-		int rows = data.length + 1;
-
-		String[][] table = new String[rows][columns];
-		table[0] = headers;
-
-		for (int i = 0; i < data.length; i++) {
-			T t = data[i];
-			table[i + 1] = mapper.getData(t);
-		}
-
-		// Find the maximum length of a string in each column
-		int[] lengths = new int[columns];
-		for (int i = 0; i < table.length; i++) {
-			for (int j = 0; j < table[i].length; j++) {
-				lengths[j] = Math.max(table[i][j].length(), lengths[j]);
-			}
-		}
-
-		// The border rows
-		String borders[] = new String[lengths.length];
-		// Generate a format string for each column
-		String[] formats = new String[lengths.length];
-		for (int i = 0; i < lengths.length; i++) {
-			StringBuilder stringBuilder = new StringBuilder();
-			stringBuilder.append("+");
-			for (int j = 0; j < lengths[i] + 2; j++) {
-				stringBuilder.append("-");
-			}
-			boolean finalColumn = (i + 1 == lengths.length);
-			if (finalColumn) {
-				stringBuilder.append("+\n");
-			}
-			borders[i] = stringBuilder.toString();
-			formats[i] = "| %1$-" + lengths[i] + "s " + (finalColumn ? "|\n" : "");
-		}
-
-		// Print the table
-		for (int i = 0; i < table.length; i++) {
-			for (int j = 0; j < table[i].length; j++) {
-				System.out.print(borders[j]);
-			}
-			for (int j = 0; j < table[i].length; j++) {
-				System.out.format(formats[j], table[i][j]);
-			}
-			if (i + 1 == table.length) {
-				for (int j = 0; j < table[i].length; j++) {
-					System.out.print(borders[j]);
-				}
-			}
-		}
-	}
-	
-	public static String getMessage(String key, Object... args) {
-		String message = BUNDLE.getString(key);
-		if (args != null && args.length > 0) {
-			message = MessageFormat.format(message, args);
-		}
-		return message;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/RowMapper.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/RowMapper.java b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/RowMapper.java
deleted file mode 100644
index 0a61ad7..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/java/org/apache/stratos/adc/mgt/cli/utils/RowMapper.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.adc.mgt.cli.utils;
-
-public interface RowMapper<T> {
-	String[] getData(T t);
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/Resources.properties
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/Resources.properties b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/Resources.properties
deleted file mode 100644
index fcec66f..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/Resources.properties
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-cannot.list.available.cartridges=An error occurred when getting available cartridges.
-cannot.list.subscribed.cartridges=An error occurred when getting subscribed cartridges.
-cannot.get.cartridge.info=An error occurred when getting cartridge information.
-cannot.syncrepo=Synchronization failed
-cannot.subscribe=Subscribe failed
-cannot.unsubscribe=Unsubscribe failed
-cannot.mapdomain=Map Domain failed
-cannot.removedomain=Mapped Domain removal failed
-
-notsubscribed.error=You have not subscribed to {0}
-domainmapping.exists.error=The domain mapping {0} already exists for {1}
-
-cartridge.notregistered=Cartridge {0} is not registered
-cartridge.invalid.alias=The provided cartridge alias is not valid. The alias can contain only lowercase characters and numbers.
-cartridge.already.subscribed=You have already subscribed for cartridge type {0}
-cartridge.alias.duplicate=Duplicate cartridge alias {0}
-
-policy.error=Could not load policy.
-repository.required=An external repository required
-repository.credentials.required=Username and Password are required for the repository: {0}
-repository.transport.error=Error connecting to the repository: {0}
-repository.invalid.error=Invalid repository: {0}
-remote.error=Error connecting to back-end service.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/log4j.properties b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/log4j.properties
deleted file mode 100755
index 958eb9c..0000000
--- a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/log4j.properties
+++ /dev/null
@@ -1,15 +0,0 @@
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-log4j.appender.console.Target=System.out
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} [%t] %n%m%n
-
-log4j.appender.file=org.apache.log4j.RollingFileAppender
-log4j.appender.file.File=${user.home}/.stratos/.stratos-cli.log
-log4j.appender.file.MaxFileSize=10MB
-log4j.appender.file.MaxBackupIndex=100
-log4j.appender.file.layout=org.apache.log4j.PatternLayout
-log4j.appender.file.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} [%t] %n%m%n
-
-#Loggers
-log4j.rootLogger=info, file
-log4j.logger.org.wso2.carbon.adc.mgt.cli=info
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/wso2carbon.jks
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/wso2carbon.jks b/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/wso2carbon.jks
deleted file mode 100644
index 7942c53..0000000
Binary files a/components/org.apache.stratos.adc.mgt.cli/2.1.3/src/main/resources/wso2carbon.jks and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/pom.xml b/components/org.apache.stratos.adc.mgt.cli/pom.xml
new file mode 100644
index 0000000..ed8090c
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/pom.xml
@@ -0,0 +1,123 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights 
+	Reserved. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); 
+	~ you may not use this file except in compliance with the License. ~ You 
+	may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 
+	~ ~ Unless required by applicable law or agreed to in writing, software ~ 
+	distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT 
+	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the 
+	License for the specific language governing permissions and ~ limitations 
+	under the License. -->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+	<parent>
+		<groupId>org.apache.stratos</groupId>
+		<artifactId>stratos-components-parent</artifactId>
+		<version>3.0.0-SNAPSHOT</version>
+	</parent>
+
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>org.apache.stratos.adc.mgt.cli</artifactId>
+	<packaging>jar</packaging>
+	<name>Apache Stratos - ADC Management CLI</name>
+	<description>ADC management CLI bundle</description>
+	<url>http://apache.org</url>
+	
+	<properties>
+		<slf4j.version>1.7.5</slf4j.version>
+	</properties>
+
+	<dependencies>
+		<!-- <dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.ui</artifactId>
+		</dependency> -->
+		<!-- Adding HttpClient dependencies. Those were resolved with above one -->
+		<dependency>
+			<groupId>commons-httpclient</groupId>
+			<artifactId>commons-httpclient</artifactId>
+			<version>${commons-httpclient.version}</version>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.securevault</groupId>
+			<artifactId>org.wso2.securevault</artifactId>
+			<version>1.0.0-wso2v2</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.httpcomponents.wso2</groupId>
+			<artifactId>httpcore</artifactId>
+			<version>4.1.0-wso2v1</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.stratos</groupId>
+			<artifactId>org.apache.stratos.adc.mgt.stub</artifactId>
+			<version>${apache.stratos.version}</version>
+		</dependency>
+		<dependency>
+			<groupId>commons-cli</groupId>
+			<artifactId>commons-cli</artifactId>
+			<version>1.2</version>
+		</dependency>
+		<dependency>
+			<groupId>jline</groupId>
+			<artifactId>jline</artifactId>
+			<version>2.11</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.commons</groupId>
+			<artifactId>commons-lang3</artifactId>
+			<version>3.1</version>
+		</dependency>
+		<dependency>
+			<groupId>commons-validator</groupId>
+			<artifactId>commons-validator</artifactId>
+			<version>1.4.0</version>
+		</dependency>
+		<!-- Logging -->
+		<dependency>
+			<groupId>org.slf4j</groupId>
+			<artifactId>slf4j-api</artifactId>
+			<version>${slf4j.version}</version>
+		</dependency>
+		<dependency>
+			<groupId>org.slf4j</groupId>
+			<artifactId>slf4j-log4j12</artifactId>
+			<version>${slf4j.version}</version>
+			<scope>runtime</scope>
+		</dependency>
+		<dependency>
+			<groupId>com.google.code.gson</groupId>
+			<artifactId>gson</artifactId>
+			<version>2.1</version>
+		</dependency>
+	</dependencies>
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-assembly-plugin</artifactId>
+				<configuration>
+					<archive>
+						<manifest>
+							<mainClass>org.apache.stratos.adc.mgt.cli.CliTool</mainClass>
+						</manifest>
+					</archive>
+					<descriptors>
+						<descriptor>src/main/assembly/src.xml</descriptor>
+					</descriptors>
+				</configuration>
+				<executions>
+					<execution>
+						<id>make-assembly</id> <!-- this is used for inheritance merges -->
+						<phase>package</phase> <!-- bind to the packaging phase -->
+						<goals>
+							<goal>single</goal>
+						</goals>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/assembly/src.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/assembly/src.xml b/components/org.apache.stratos.adc.mgt.cli/src/main/assembly/src.xml
new file mode 100644
index 0000000..ec41ef1
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/assembly/src.xml
@@ -0,0 +1,36 @@
+<!--
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+ -->
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+	<id>Tool</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<dependencySets>
+		<dependencySet>
+			<outputDirectory>/</outputDirectory>
+			<useProjectArtifact>true</useProjectArtifact>
+			<unpack>true</unpack>
+			<scope>runtime</scope>
+		</dependencySet>
+	</dependencySets>
+</assembly>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/Main.iml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/Main.iml b/components/org.apache.stratos.adc.mgt.cli/src/main/java/Main.iml
new file mode 100644
index 0000000..9a9b340
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/Main.iml
@@ -0,0 +1,204 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="JAVA_MODULE" version="4">
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+  <component name="org.twodividedbyzero.idea.findbugs">
+    <option name="_basePreferences">
+      <map>
+        <entry key="property.analysisEffortLevel" value="default" />
+        <entry key="property.analyzeAfterCompile" value="false" />
+        <entry key="property.annotationGutterIconEnabled" value="true" />
+        <entry key="property.annotationSuppressWarningsClass" value="edu.umd.cs.findbugs.annotations.SuppressWarnings" />
+        <entry key="property.annotationTextRangeMarkupEnabled" value="true" />
+        <entry key="property.exportAsHtml" value="true" />
+        <entry key="property.exportAsXml" value="true" />
+        <entry key="property.exportBaseDir" value="" />
+        <entry key="property.exportCreateArchiveDir" value="false" />
+        <entry key="property.exportOpenBrowser" value="true" />
+        <entry key="property.minPriorityToReport" value="Medium" />
+        <entry key="property.runAnalysisInBackground" value="false" />
+        <entry key="property.showHiddenDetectors" value="false" />
+        <entry key="property.toolWindowToFront" value="true" />
+      </map>
+    </option>
+    <option name="_detectors">
+      <map>
+        <entry key="AppendingToAnObjectOutputStream" value="true" />
+        <entry key="AtomicityProblem" value="true" />
+        <entry key="BadAppletConstructor" value="false" />
+        <entry key="BadResultSetAccess" value="true" />
+        <entry key="BadSyntaxForRegularExpression" value="true" />
+        <entry key="BadUseOfReturnValue" value="true" />
+        <entry key="BadlyOverriddenAdapter" value="true" />
+        <entry key="BooleanReturnNull" value="true" />
+        <entry key="BuildInterproceduralCallGraph" value="false" />
+        <entry key="BuildObligationPolicyDatabase" value="true" />
+        <entry key="CallToUnsupportedMethod" value="false" />
+        <entry key="CalledMethods" value="true" />
+        <entry key="CheckCalls" value="false" />
+        <entry key="CheckExpectedWarnings" value="false" />
+        <entry key="CheckImmutableAnnotation" value="true" />
+        <entry key="CheckTypeQualifiers" value="true" />
+        <entry key="CloneIdiom" value="true" />
+        <entry key="ComparatorIdiom" value="true" />
+        <entry key="ConfusedInheritance" value="true" />
+        <entry key="ConfusionBetweenInheritedAndOuterMethod" value="true" />
+        <entry key="CrossSiteScripting" value="true" />
+        <entry key="DefaultEncodingDetector" value="true" />
+        <entry key="DoInsideDoPrivileged" value="true" />
+        <entry key="DontCatchIllegalMonitorStateException" value="true" />
+        <entry key="DontIgnoreResultOfPutIfAbsent" value="true" />
+        <entry key="DontUseEnum" value="true" />
+        <entry key="DroppedException" value="true" />
+        <entry key="DumbMethodInvocations" value="true" />
+        <entry key="DumbMethods" value="true" />
+        <entry key="DuplicateBranches" value="true" />
+        <entry key="EmptyZipFileEntry" value="true" />
+        <entry key="EqualsOperandShouldHaveClassCompatibleWithThis" value="true" />
+        <entry key="ExplicitSerialization" value="true" />
+        <entry key="FieldItemSummary" value="true" />
+        <entry key="FinalizerNullsFields" value="true" />
+        <entry key="FindBadCast2" value="true" />
+        <entry key="FindBadForLoop" value="true" />
+        <entry key="FindBugsSummaryStats" value="true" />
+        <entry key="FindCircularDependencies" value="false" />
+        <entry key="FindDeadLocalStores" value="true" />
+        <entry key="FindDoubleCheck" value="true" />
+        <entry key="FindEmptySynchronizedBlock" value="true" />
+        <entry key="FindFieldSelfAssignment" value="true" />
+        <entry key="FindFinalizeInvocations" value="true" />
+        <entry key="FindFloatEquality" value="true" />
+        <entry key="FindFloatMath" value="false" />
+        <entry key="FindHEmismatch" value="true" />
+        <entry key="FindInconsistentSync2" value="true" />
+        <entry key="FindJSR166LockMonitorenter" value="true" />
+        <entry key="FindLocalSelfAssignment2" value="true" />
+        <entry key="FindMaskedFields" value="true" />
+        <entry key="FindMismatchedWaitOrNotify" value="true" />
+        <entry key="FindNakedNotify" value="true" />
+        <entry key="FindNonSerializableStoreIntoSession" value="false" />
+        <entry key="FindNonSerializableValuePassedToWriteObject" value="false" />
+        <entry key="FindNonShortCircuit" value="true" />
+        <entry key="FindNullDeref" value="true" />
+        <entry key="FindNullDerefsInvolvingNonShortCircuitEvaluation" value="true" />
+        <entry key="FindOpenStream" value="true" />
+        <entry key="FindPuzzlers" value="true" />
+        <entry key="FindRefComparison" value="true" />
+        <entry key="FindReturnRef" value="true" />
+        <entry key="FindRunInvocations" value="true" />
+        <entry key="FindSelfComparison" value="true" />
+        <entry key="FindSelfComparison2" value="true" />
+        <entry key="FindSleepWithLockHeld" value="true" />
+        <entry key="FindSpinLoop" value="true" />
+        <entry key="FindSqlInjection" value="true" />
+        <entry key="FindTwoLockWait" value="true" />
+        <entry key="FindUncalledPrivateMethods" value="true" />
+        <entry key="FindUnconditionalWait" value="true" />
+        <entry key="FindUninitializedGet" value="true" />
+        <entry key="FindUnrelatedTypesInGenericContainer" value="true" />
+        <entry key="FindUnreleasedLock" value="true" />
+        <entry key="FindUnsatisfiedObligation" value="true" />
+        <entry key="FindUnsyncGet" value="true" />
+        <entry key="FindUseOfNonSerializableValue" value="true" />
+        <entry key="FindUselessControlFlow" value="true" />
+        <entry key="FormatStringChecker" value="true" />
+        <entry key="FunctionsThatMightBeMistakenForProcedures" value="true" />
+        <entry key="HugeSharedStringConstants" value="true" />
+        <entry key="IDivResultCastToDouble" value="true" />
+        <entry key="IncompatMask" value="true" />
+        <entry key="InconsistentAnnotations" value="true" />
+        <entry key="InefficientMemberAccess" value="false" />
+        <entry key="InefficientToArray" value="true" />
+        <entry key="InfiniteLoop" value="true" />
+        <entry key="InfiniteRecursiveLoop" value="true" />
+        <entry key="InheritanceUnsafeGetResource" value="true" />
+        <entry key="InitializationChain" value="true" />
+        <entry key="InitializeNonnullFieldsInConstructor" value="true" />
+        <entry key="InstantiateStaticClass" value="true" />
+        <entry key="IntCast2LongAsInstant" value="true" />
+        <entry key="InvalidJUnitTest" value="true" />
+        <entry key="IteratorIdioms" value="true" />
+        <entry key="LazyInit" value="true" />
+        <entry key="LoadOfKnownNullValue" value="true" />
+        <entry key="LostLoggerDueToWeakReference" value="true" />
+        <entry key="MethodReturnCheck" value="true" />
+        <entry key="Methods" value="true" />
+        <entry key="MultithreadedInstanceAccess" value="true" />
+        <entry key="MutableLock" value="true" />
+        <entry key="MutableStaticFields" value="true" />
+        <entry key="Naming" value="true" />
+        <entry key="Noise" value="false" />
+        <entry key="NoiseNullDeref" value="false" />
+        <entry key="NoteAnnotationRetention" value="true" />
+        <entry key="NoteCheckReturnValueAnnotations" value="true" />
+        <entry key="NoteDirectlyRelevantTypeQualifiers" value="true" />
+        <entry key="NoteJCIPAnnotation" value="true" />
+        <entry key="NoteNonNullAnnotations" value="true" />
+        <entry key="NoteNonnullReturnValues" value="true" />
+        <entry key="NoteSuppressedWarnings" value="true" />
+        <entry key="NoteUnconditionalParamDerefs" value="true" />
+        <entry key="NumberConstructor" value="true" />
+        <entry key="OverridingEqualsNotSymmetrical" value="true" />
+        <entry key="PreferZeroLengthArrays" value="true" />
+        <entry key="PublicSemaphores" value="false" />
+        <entry key="QuestionableBooleanAssignment" value="true" />
+        <entry key="ReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass" value="true" />
+        <entry key="ReadReturnShouldBeChecked" value="true" />
+        <entry key="RedundantInterfaces" value="true" />
+        <entry key="ReflectiveClasses" value="true" />
+        <entry key="RepeatedConditionals" value="true" />
+        <entry key="ResolveAllReferences" value="false" />
+        <entry key="RuntimeExceptionCapture" value="true" />
+        <entry key="SerializableIdiom" value="true" />
+        <entry key="StartInConstructor" value="true" />
+        <entry key="StaticCalendarDetector" value="true" />
+        <entry key="StringConcatenation" value="true" />
+        <entry key="SuperfluousInstanceOf" value="true" />
+        <entry key="SuspiciousThreadInterrupted" value="true" />
+        <entry key="SwitchFallthrough" value="true" />
+        <entry key="SynchronizationOnSharedBuiltinConstant" value="true" />
+        <entry key="SynchronizeAndNullCheckField" value="true" />
+        <entry key="SynchronizeOnClassLiteralNotGetClass" value="true" />
+        <entry key="SynchronizingOnContentsOfFieldToProtectField" value="true" />
+        <entry key="TestASM" value="false" />
+        <entry key="TestDataflowAnalysis" value="false" />
+        <entry key="TestingGround" value="false" />
+        <entry key="TestingGround2" value="false" />
+        <entry key="TrainFieldStoreTypes" value="true" />
+        <entry key="TrainLongInstantfParams" value="true" />
+        <entry key="TrainNonNullAnnotations" value="true" />
+        <entry key="TrainUnconditionalDerefParams" value="true" />
+        <entry key="URLProblems" value="true" />
+        <entry key="UncallableMethodOfAnonymousClass" value="true" />
+        <entry key="UnnecessaryMath" value="true" />
+        <entry key="UnreadFields" value="true" />
+        <entry key="UselessSubclassMethod" value="false" />
+        <entry key="VarArgsProblems" value="true" />
+        <entry key="VolatileUsage" value="true" />
+        <entry key="WaitInLoop" value="true" />
+        <entry key="WrongMapIterator" value="true" />
+        <entry key="XMLFactoryBypass" value="true" />
+      </map>
+    </option>
+    <option name="_reportCategories">
+      <map>
+        <entry key="BAD_PRACTICE" value="true" />
+        <entry key="CORRECTNESS" value="true" />
+        <entry key="EXPERIMENTAL" value="true" />
+        <entry key="I18N" value="true" />
+        <entry key="MALICIOUS_CODE" value="true" />
+        <entry key="MT_CORRECTNESS" value="true" />
+        <entry key="PERFORMANCE" value="true" />
+        <entry key="SECURITY" value="true" />
+        <entry key="STYLE" value="true" />
+      </map>
+    </option>
+  </component>
+</module>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CliTool.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CliTool.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CliTool.java
new file mode 100644
index 0000000..4a824a4
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CliTool.java
@@ -0,0 +1,76 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli;
+
+import static org.apache.stratos.adc.mgt.cli.utils.CliConstants.STRATOS_DIR;
+
+import java.io.File;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is used for input the commands through CLITool, command prompt.
+ */
+public class CliTool {
+
+	private static final Logger logger = LoggerFactory.getLogger(CliTool.class);
+
+	/**
+	 * Main executable method used to call from CLI.
+	 * 
+	 */
+	public static void main(final String[] args) {
+		CliTool cliTool = new CliTool();
+		cliTool.createConfigDirectory();
+		cliTool.handleConsoleInputs(args);
+	}
+
+	/**
+	 * Here is the place all the command line inputs get processed
+	 * 
+	 * @param arguments
+	 *            passed to CLI tool.
+	 */
+	private void handleConsoleInputs(String[] arguments) {
+		if (logger.isInfoEnabled()) {
+			logger.info("Stratos CLI Started...");
+		}
+		StratosApplication application = new StratosApplication();
+		application.start(arguments);
+	}
+
+	private void createConfigDirectory() {
+		File stratosFile = new File(System.getProperty("user.home"), STRATOS_DIR);
+		if (stratosFile.exists()) {
+			if (logger.isInfoEnabled()) {
+				logger.info("Using directory: {}", stratosFile.getPath());
+			}
+		} else {
+			if (stratosFile.mkdir()) {
+				if (logger.isInfoEnabled()) {
+					logger.info("Created directory: {}", stratosFile.getPath());
+				}
+			} else if (logger.isWarnEnabled()) {
+				logger.warn("Failed to created directory: {}", stratosFile.getPath());
+			}
+		}
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/Command.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/Command.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/Command.java
new file mode 100644
index 0000000..caebaa4
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/Command.java
@@ -0,0 +1,67 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli;
+
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.commons.cli.Options;
+
+public interface Command<T extends CommandContext> {
+
+	/**
+	 * @return The name of the command
+	 */
+	String getName();
+
+	/**
+	 * Information about the command
+	 * 
+	 * @return The description of the command
+	 */
+	String getDescription();
+
+	/**
+	 * This should return the syntax required for the command.
+	 * 
+	 * Used to display help.
+	 * 
+	 * @return The syntax for this command
+	 */
+	String getArgumentSyntax();
+
+	/**
+	 * The options accepted by the command
+	 * 
+	 * @return The Options for the commands
+	 */
+	Options getOptions();
+
+	/**
+	 * Executing the commands. Returns a code
+	 * 
+	 * @param context
+	 *            The context assoicated with the Command Line Application
+	 * @param args
+	 *            The arguments for the command
+	 * @return The status code
+	 * @throws org.apache.stratos.adc.mgt.cli.exception.CommandException
+	 *             if any errors occur when executing the command
+	 */
+	int execute(T context, String[] args) throws CommandException;
+
+}


[35/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandContext.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandContext.java
new file mode 100644
index 0000000..745b2f4
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandContext.java
@@ -0,0 +1,88 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Observable;
+
+public class CommandContext extends Observable {
+
+	/**
+	 * Properties for the context.
+	 */
+	private Map<String, Object> properties;
+
+	/**
+	 * The application
+	 */
+	private final CommandLineApplication<? extends CommandContext> application;
+
+	public CommandContext(CommandLineApplication<? extends CommandContext> application) {
+		properties = new HashMap<String, Object>();
+		this.application = application;
+	}
+
+	public final CommandLineApplication<? extends CommandContext> getApplication() {
+		return application;
+	}
+
+	/**
+	 * Set property in the context
+	 * 
+	 * @param key
+	 *            The key
+	 * @param o
+	 *            The value for the key
+	 * @return The previous value or null
+	 */
+	public Object put(String key, Object o) {
+		Object previous = properties.put(key, o);
+		setChanged();
+		notifyObservers();
+		return previous;
+	}
+
+	/**
+	 * Get property value from the context
+	 * 
+	 * @param key
+	 *            The key
+	 * @return The value
+	 */
+	public Object getObject(String key) {
+		return properties.get(key);
+	}
+
+	/**
+	 * Get the string value, or null
+	 * 
+	 * @param key
+	 *            The key
+	 * @return The string value, or null.
+	 */
+	public String getString(String key) {
+		Object o = getObject(key);
+		if (o instanceof String) {
+			return (String) o;
+		}
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineApplication.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineApplication.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineApplication.java
new file mode 100644
index 0000000..010948f
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineApplication.java
@@ -0,0 +1,190 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli;
+
+import java.io.File;
+import java.io.IOException;
+
+import jline.console.ConsoleReader;
+import jline.console.history.FileHistory;
+
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class CommandLineApplication<T extends CommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(CommandLineApplication.class);
+
+	protected final ConsoleReader reader;
+	protected FileHistory history;
+
+	public CommandLineApplication() {
+		reader = createConsoleReader();
+	}
+
+	/**
+	 * Creates new jline ConsoleReader.
+	 * 
+	 * @return a jline ConsoleReader instance
+	 */
+	protected ConsoleReader createConsoleReader() {
+		ConsoleReader consoleReader = null;
+		try {
+			consoleReader = new ConsoleReader();
+			consoleReader.setPrompt(getPrompt());
+			history = new FileHistory(getHistoryFile());
+			consoleReader.setHistory(history);
+		} catch (IOException e) {
+			throw new IllegalStateException("Cannot create jline console reader", e);
+		}
+		return consoleReader;
+	}
+
+	public ConsoleReader getConsoleReader() {
+		return reader;
+	}
+
+	protected abstract String getPrompt();
+
+	/**
+	 * Get the history file for the Console Reader.
+	 * 
+	 * @return File for storing history
+	 */
+	protected abstract File getHistoryFile();
+
+	public final void start(String[] args) {
+		Thread shutdownHookThread = new Thread("CLI Shutdown Hook") {
+			@Override
+			public void run() {
+				performDestroy();
+			}
+		};
+		Runtime.getRuntime().addShutdownHook(shutdownHookThread);
+		int returnCode = run(args);
+		if (logger.isDebugEnabled()) {
+			logger.debug("Exiting with error code {}", returnCode);
+		}
+		System.exit(returnCode);
+	}
+
+	protected abstract int run(String[] args);
+
+	protected void promptLoop() {
+		String line = null;
+		boolean exit = false;
+
+		try {
+			while (!exit && (reader != null && ((line = reader.readLine()) != null))) {
+				if ("".equals(line)) {
+					continue;
+				}
+				if (StringUtils.isNotBlank(line)) {
+					execute(line);
+					exit = CliConstants.EXIT_ACTION.equals(line.trim());
+				}
+			}
+		} catch (IOException e) {
+			throw new IllegalStateException("Error in reading line", e);
+		}
+	}
+
+	private int execute(String line) {
+		try {
+			if (logger.isDebugEnabled()) {
+				logger.debug("Executing command line: \"{}\"", line);
+			}
+			int returnCode = executeCommand(line);
+			if (logger.isDebugEnabled()) {
+				logger.debug("Command line executed \"{}\". Return code: {}", line, returnCode);
+			}
+			return returnCode;
+		} catch (RuntimeException e) {
+			if (logger.isErrorEnabled()) {
+				logger.error("Error executing command line: " + line, e);
+			}
+			return 1;
+		}
+	}
+
+	protected abstract int executeCommand(String line);
+
+	private void performDestroy() {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Shutting down application... Invoking destroy methods");
+		}
+		if (history != null) {
+			try {
+				history.flush();
+			} catch (IOException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error flushing history.", e);
+				}
+			}
+		}
+		destroy();
+	}
+
+	/**
+	 * May override to perform action before destroying
+	 */
+	protected void destroy() {
+	};
+
+	public String getInput(String prompt) {
+		return getInput(prompt, null);
+	}
+
+	public String getInput(String prompt, Character mask) {
+		String line = null;
+		try {
+			reader.setPrompt(prompt + ": ");
+			while ((line = reader.readLine(mask)) != null) {
+				if ("".equals(line)) {
+					continue;
+				}
+				return line;
+			}
+		} catch (IOException e) {
+			throw new IllegalStateException("Error in reading line", e);
+		} finally {
+			reader.setPrompt(CliConstants.STRATOS_SHELL_PROMPT);
+		}
+		return line;
+	}
+	
+	/**
+	 * @return {@code true if user confirmed}
+	 */
+	public boolean getConfirmation(String prompt) {
+		prompt = prompt + " [yes/no]";
+
+		String input = "";
+		int tries = 0;
+		do {
+			tries++;
+			input = getInput(prompt);
+		} while (!"y".equals(input) && !"yes".equals(input) && !"n".equals(input) && !"no".equals(input) && tries < 3);
+
+		return "y".equals(input) || "yes".equals(input);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineService.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineService.java
new file mode 100644
index 0000000..2aa9f2b
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/CommandLineService.java
@@ -0,0 +1,556 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli;
+
+import java.rmi.RemoteException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.apache.axis2.description.TransportOutDescription;
+import org.apache.axis2.transport.http.HttpTransportProperties;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.stratos.adc.mgt.cli.utils.CommandLineUtils;
+import org.apache.stratos.adc.mgt.cli.utils.RowMapper;
+import org.apache.stratos.adc.mgt.dto.xsd.Cartridge;
+import org.apache.stratos.adc.mgt.dto.xsd.PolicyDefinition;
+import org.apache.stratos.adc.mgt.dto.xsd.SubscriptionInfo;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceADCExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceAlreadySubscribedExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceDomainMappingExistsExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceDuplicateCartridgeAliasExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceInvalidCartridgeAliasExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceInvalidRepositoryExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceNotSubscribedExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServicePolicyExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceRepositoryRequiredExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceRepositoryTransportExceptionException;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceStub;
+import org.apache.stratos.adc.mgt.stub.ApplicationManagementServiceUnregisteredCartridgeExceptionException;
+
+import com.google.gson.Gson;
+
+public class CommandLineService {
+
+	private static final Logger logger = LoggerFactory.getLogger(CommandLineService.class);
+
+	private ApplicationManagementServiceStub stub;
+
+	private CommandLineService() {
+	}
+
+	private static class SingletonHolder {
+		private final static CommandLineService INSTANCE = new CommandLineService();
+	}
+
+	public static CommandLineService getInstance() {
+		return SingletonHolder.INSTANCE;
+	}
+	
+	private void initializeApplicationManagementStub(String serverURL, String username, String password) throws AxisFault {
+		HttpTransportProperties.Authenticator authenticator = new HttpTransportProperties.Authenticator();
+        authenticator.setUsername(username);
+        authenticator.setPassword(password);
+        authenticator.setPreemptiveAuthentication(true);
+		
+        ApplicationManagementServiceStub stub;
+        ConfigurationContext configurationContext = null;
+        try {
+            configurationContext = ConfigurationContextFactory.createDefaultConfigurationContext();
+        } catch (Exception e) {
+            String msg = "Backend error occurred. Please contact the service admins!";
+            throw new AxisFault(msg, e);
+        }
+        HashMap<String, TransportOutDescription> transportsOut = configurationContext
+                .getAxisConfiguration().getTransportsOut();
+        for (TransportOutDescription transportOutDescription : transportsOut.values()) {
+            transportOutDescription.getSender().init(configurationContext, transportOutDescription);
+        }
+        stub = new ApplicationManagementServiceStub(configurationContext, serverURL + "/services/ApplicationManagementService");
+        ServiceClient client = stub._getServiceClient();
+        Options option = client.getOptions();
+        option.setManageSession(true);
+        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, authenticator);
+        option.setTimeOutInMilliSeconds(300000);
+        this.stub = stub;
+    }
+
+	public boolean login(String serverURL, String username, String password, boolean validateLogin) throws CommandException {
+		try {
+			// Following code will avoid validating certificate
+			SSLContext sc;
+			// Get SSL context
+			sc = SSLContext.getInstance("SSL");
+			// Create empty HostnameVerifier
+			HostnameVerifier hv = new HostnameVerifier() {
+				public boolean verify(String urlHostName, SSLSession session) {
+					return true;
+				}
+			};
+			// Create a trust manager that does not validate certificate
+			// chains
+			TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
+				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+					return null;
+				}
+
+				public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
+				}
+
+				public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
+				}
+			} };
+			sc.init(null, trustAllCerts, new java.security.SecureRandom());
+			SSLContext.setDefault(sc);
+			HttpsURLConnection.setDefaultHostnameVerifier(hv);
+		} catch (Exception e) {
+			throw new RuntimeException("Error while authentication process!", e);
+		}
+
+		// Initialize Service Stub
+		try {
+			initializeApplicationManagementStub(serverURL, username, password);
+		} catch (AxisFault e) {
+			System.out.println("Error connecting to the back-end");
+			throw new CommandException(e);
+		}
+		
+		try {
+			if (validateLogin) {
+				String tenantDomain = stub.getTenantDomain();
+				if (logger.isDebugEnabled()) {
+					logger.debug("Tenant Domain {}", tenantDomain);
+				}
+				return (tenantDomain != null);
+			} else {
+				// Just return true as we don't need to validate
+				return true;
+			}
+		} catch (RemoteException e) {
+			System.out.println("Authentication failed!");
+			throw new CommandException(e);
+		}
+	}
+
+	public void listSubscribedCartridges(final boolean full) throws CommandException {
+		try {
+			Cartridge[] cartridges = stub.getSubscribedCartridges();
+
+			if (cartridges == null) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("No subscribed cartridges found");
+				}
+				System.out.println("There are no subscribed cartridges");
+				return;
+			}
+
+			RowMapper<Cartridge> cartridgeMapper = new RowMapper<Cartridge>() {
+
+				@Override
+				public String[] getData(Cartridge cartridge) {
+					String[] data = full ? new String[9] : new String[7];
+					data[0] = cartridge.getCartridgeType();
+					data[1] = cartridge.getDisplayName();
+					data[2] = cartridge.getVersion();
+					data[3] = cartridge.getMultiTenant() ? "Multi-Tenant" : "Single-Tenant";
+					data[4] = cartridge.getCartridgeAlias();
+					data[5] = cartridge.getStatus();
+					data[6] = cartridge.getMultiTenant() ? "N/A" : String.valueOf(cartridge.getActiveInstances());
+					if (full) {
+						data[7] = getAccessURLs(cartridge);
+						data[8] = cartridge.getRepoURL() != null ? cartridge.getRepoURL() : "";
+					}
+					return data;
+				}
+			};
+			
+			List<String> headers = new ArrayList<String>();
+			headers.add("Type");
+			headers.add("Name");
+			headers.add("Version");
+			headers.add("Tenancy Model");
+			headers.add("Alias");
+			headers.add("Status");
+			headers.add("Running Instances");
+			if (full) {
+				headers.add("Access URL(s)");
+				headers.add("Repo URL");
+			}
+
+			System.out.println("Subscribed Cartridges:");
+			CommandLineUtils.printTable(cartridges, cartridgeMapper, headers.toArray(new String[headers.size()]));
+
+			System.out.println();
+
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.list.subscribed.cartridges", e);
+		} catch (RemoteException e) {
+			handleException(e);
+		}
+	}
+
+	public void listAvailableCartridges() throws CommandException {
+		try {
+			Cartridge[] multiTenantCatridges = stub.getAvailableCartridges(true);
+
+			if (multiTenantCatridges == null) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("No multi-tenant cartridges available");
+				}
+				System.out.println("There are no multi-tenant cartridges available");
+			}
+
+			RowMapper<Cartridge> cartridgeMapper = new RowMapper<Cartridge>() {
+
+				@Override
+				public String[] getData(Cartridge cartridge) {
+					String[] data = new String[3];
+					data[0] = cartridge.getCartridgeType();
+					data[1] = cartridge.getDisplayName();
+					data[2] = cartridge.getVersion();
+					return data;
+				}
+			};
+
+			System.out.println("Available Multi-Tenant Cartridges:");
+			CommandLineUtils.printTable(multiTenantCatridges, cartridgeMapper, "Type", "Name", "Version");
+			System.out.println();
+			
+			Cartridge[] singleTenantCatridges = stub.getAvailableCartridges(false);
+
+			if (multiTenantCatridges == null) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("No single-tenant cartridges available");
+				}
+				System.out.println("There are no single-tenant cartridges available");
+			}
+			
+			System.out.println("Available Single-Tenant Cartridges:");
+			CommandLineUtils.printTable(singleTenantCatridges, cartridgeMapper, "Type", "Name", "Version");
+			System.out.println();
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.list.available.cartridges", e);
+		} catch (RemoteException e) {
+			handleException(e);
+		}
+	}
+	
+	public void listAvailablePolicies() throws CommandException {
+		try {
+			PolicyDefinition[] policies = stub.getPolicyDefinitions();
+
+			if (policies == null) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("No policies available");
+				}
+				System.out.println("There are no policies available");
+			}
+
+			RowMapper<PolicyDefinition> policyMapper = new RowMapper<PolicyDefinition>() {
+
+				@Override
+				public String[] getData(PolicyDefinition policyDefinition) {
+					String[] data = new String[3];
+					data[0] = policyDefinition.getName();
+					data[1] = policyDefinition.getDescription();
+					data[2] = policyDefinition.getDefaultPolicy() ? "Yes" : "No";
+					return data;
+				}
+			};
+
+			CommandLineUtils.printTable(policies, policyMapper, "Policy Name", "Description", "Default");
+			System.out.println();
+		} catch (RemoteException e) {
+			handleException(e);
+		}
+	}
+
+	public void info(String alias) throws CommandException {
+		try {
+            Cartridge cartridge = null;
+            try {
+                cartridge = stub.getCartridgeInfo(alias);
+            } catch (ApplicationManagementServiceADCExceptionException e) {
+            	handleException(e);
+                return;
+            } catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+            	handleException("notsubscribed.error", e, alias);
+			}
+			if (logger.isDebugEnabled()) {
+				logger.debug("Cartridge Info: {}", new Gson().toJson(cartridge));
+			}
+			final String FORMAT = "%-20s: %s%n";
+			System.out.println();
+			System.out.println("Cartridge Information");
+			System.out.println("---------------------");
+			System.out.format(FORMAT, "Cartridge", cartridge.getCartridgeType());
+			System.out.format(FORMAT, "Name", cartridge.getDisplayName());
+			System.out.format(FORMAT, "Description", cartridge.getDescription());
+			System.out.format(FORMAT, "Version", cartridge.getVersion());
+			System.out.format(FORMAT, "Tenancy Model", cartridge.getMultiTenant() ? "Multi-Tenant" : "Single-Tenant");
+			System.out.format(FORMAT, "Alias", cartridge.getCartridgeAlias());
+			if (StringUtils.isNotBlank(cartridge.getPolicyDescription())) {
+				System.out.format(FORMAT, "Policy", cartridge.getPolicyDescription());
+			}
+			System.out.format(FORMAT, "Access URL(s)", getAccessURLs(cartridge));
+			if (StringUtils.isNotBlank(cartridge.getIp())) {
+				System.out.format(FORMAT, "Host", cartridge.getIp());
+			}
+			if (StringUtils.isNotBlank(cartridge.getDbUserName())) {
+				System.out.format(FORMAT, "Database Username", cartridge.getDbUserName());
+			}
+			if (StringUtils.isNotBlank(cartridge.getPassword())) {
+				System.out.format(FORMAT, "Password", cartridge.getPassword());
+			}
+			if (StringUtils.isNotBlank(cartridge.getRepoURL())) {
+				System.out.format(FORMAT, "Repository URL", cartridge.getRepoURL());
+			}
+			System.out.format(FORMAT, "Status", cartridge.getStatus());
+			System.out.format(FORMAT, "Running Instances",
+					cartridge.getMultiTenant() ? "N/A" : String.valueOf(cartridge.getActiveInstances()));
+			System.out.println();
+
+        } catch (RemoteException e) {
+        	handleException(e);
+        }
+	}
+
+	public void unsubscribe(String alias) throws CommandException {
+		try {
+			stub.unsubscribe(alias);
+			System.out.println("You have successfully unsubscribed " + alias);
+        } catch (ApplicationManagementServiceADCExceptionException e) {
+        	handleException("cannot.unsubscribe", e);
+        } catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, alias);
+        } catch (RemoteException e) {
+        	handleException(e);
+        }
+	}
+
+	public void sync(String alias) throws CommandException {
+		try {
+			System.out.format("Synchronizing repository for alias: %s%n", alias);
+			stub.synchronizeRepository(alias);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.syncrepo", e);
+		} catch (RemoteException e) {
+			handleException(e);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, alias);
+		}
+	}
+
+	public String addDomainMapping(String domain, String alias) throws CommandException {
+		try {
+			return stub.addDomainMapping(domain, alias);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.mapdomain", e);
+		} catch (RemoteException e) {
+			handleException(e);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, alias);
+		} catch (ApplicationManagementServiceDomainMappingExistsExceptionException e) {
+			handleException("domainmapping.exists.error", e, domain, alias);
+		}
+		return null;
+	}
+
+	public void removeDomainMapping(String alias) throws CommandException {
+		try {
+			stub.removeDomainMapping(alias);
+			System.out.format("Domain mapping removed for alias: %s.%n", alias);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.removedomain", e);
+		} catch (RemoteException e) {
+			handleException(e);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, alias);
+		}
+	}
+
+	public void subscribe(String cartridgeType, String alias, String policy, String externalRepoURL,
+			boolean privateRepo, String username, String password, String dataCartridgeType, String dataCartridgeAlias)
+			throws CommandException {
+		
+		SubscriptionInfo subcriptionConnectInfo = null;
+		if (StringUtils.isNotBlank(dataCartridgeType) && StringUtils.isNotBlank(dataCartridgeAlias)) {
+			System.out.format("Subscribing to data cartridge %s with alias %s.%n", dataCartridgeType,
+					dataCartridgeAlias);
+			try {
+				subcriptionConnectInfo = stub.subscribe(dataCartridgeType, dataCartridgeAlias, null, null, false, null,
+						null, null, null);
+				System.out.format("You have successfully subscribed to %s cartridge with alias %s.%n",
+						dataCartridgeType, dataCartridgeAlias);
+				System.out.format("%nSubscribing to %s cartridge and connecting with %s data cartridge.%n", alias,
+						dataCartridgeAlias);
+			} catch (RemoteException e) {
+				handleException(e);
+			} catch (ApplicationManagementServiceADCExceptionException e) {
+				handleException("cannot.subscribe", e);
+			} catch (ApplicationManagementServiceRepositoryRequiredExceptionException e) {
+				handleException("repository.required", e);
+			} catch (ApplicationManagementServiceUnregisteredCartridgeExceptionException e) {
+				handleException("cartridge.notregistered", e, dataCartridgeType);
+			} catch (ApplicationManagementServiceInvalidCartridgeAliasExceptionException e) {
+				handleException("cartridge.invalid.alias", e);
+			} catch (ApplicationManagementServiceAlreadySubscribedExceptionException e) {
+				handleException("cartridge.already.subscribed", e, e.getFaultMessage().getAlreadySubscribedException()
+						.getCartridgeType());
+			} catch (ApplicationManagementServiceDuplicateCartridgeAliasExceptionException e) {
+				handleException("cartridge.alias.duplicate", e, dataCartridgeAlias);
+			} catch (ApplicationManagementServicePolicyExceptionException e) {
+				handleException("policy.error", e);
+			} catch (ApplicationManagementServiceRepositoryTransportExceptionException e) {
+				handleException("repository.transport.error", e, externalRepoURL);
+			} catch (ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException e) {
+				handleException("repository.credentials.required", e, externalRepoURL);
+			} catch (ApplicationManagementServiceInvalidRepositoryExceptionException e) {
+				handleException("repository.invalid.error", e, externalRepoURL);
+			}
+		}
+		
+		
+		try {
+			SubscriptionInfo subcriptionInfo = stub.subscribe(cartridgeType, alias, policy, externalRepoURL,
+					privateRepo, username, password, dataCartridgeType, dataCartridgeAlias);
+
+			System.out
+					.format("You have successfully subscribed to %s cartridge with alias %s.%n", cartridgeType, alias);
+
+			String repoURL = null;
+			String hostnames = null;
+			String hostnamesLabel = null;
+			if (subcriptionInfo != null) {
+				repoURL = subcriptionInfo.getRepositoryURL();
+				hostnames = subcriptionInfo.getHostname();
+				hostnamesLabel = "host name";
+
+				if (repoURL != null) {
+					System.out.println("GIT Repository URL: " + repoURL);
+				}
+
+				Cartridge cart = stub.getCartridgeInfo(alias);
+				System.out.format("Your application is being published here. %s%n", getAccessURLs(cart));
+			}
+			if (subcriptionConnectInfo != null) {
+				hostnames += ", " + subcriptionConnectInfo.getHostname();
+				hostnamesLabel = "host names";
+
+				Cartridge cart = stub.getCartridgeInfo(alias);
+				System.out.format("Your data application is being published here. %s%n", getAccessURLs(cart));
+			}
+			if (externalRepoURL != null) {
+				String takeTimeMsg = "(this might take few minutes... depending on repo size)\n";
+				System.out.println(takeTimeMsg);
+			}
+
+			System.out.format("Please map the %s \"%s\" to ELB IP%n", hostnamesLabel, hostnames);
+		} catch (RemoteException e) {
+			handleException(e);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.subscribe", e);
+		} catch (ApplicationManagementServiceRepositoryRequiredExceptionException e) {
+			handleException("repository.required", e);
+		} catch (ApplicationManagementServiceUnregisteredCartridgeExceptionException e) {
+			handleException("cartridge.notregistered", e, cartridgeType);
+		} catch (ApplicationManagementServiceInvalidCartridgeAliasExceptionException e) {
+			handleException("cartridge.invalid.alias", e);
+		} catch (ApplicationManagementServiceAlreadySubscribedExceptionException e) {
+			handleException("cartridge.already.subscribed", e, e.getFaultMessage().getAlreadySubscribedException()
+					.getCartridgeType());
+		} catch (ApplicationManagementServiceDuplicateCartridgeAliasExceptionException e) {
+			handleException("cartridge.alias.duplicate", e, alias);
+		} catch (ApplicationManagementServicePolicyExceptionException e) {
+			handleException("policy.error", e);
+		} catch (ApplicationManagementServiceRepositoryTransportExceptionException e) {
+			handleException("repository.transport.error", e, externalRepoURL);
+		} catch (ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException e) {
+			handleException("repository.credentials.required", e, externalRepoURL);
+		} catch (ApplicationManagementServiceInvalidRepositoryExceptionException e) {
+			handleException("repository.invalid.error", e, externalRepoURL);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, alias);
+		}
+	}
+
+	private String getAccessURLs(Cartridge cartridge) {
+		String[] accessURLs = cartridge.getAccessURLs();
+		StringBuilder urlBuilder = new StringBuilder();
+		if (accessURLs != null) {
+			for (int i = 0; i < accessURLs.length; i++) {
+				String url = accessURLs[i];
+				if (url != null) {
+					if (i > 0) {
+						urlBuilder.append(", ");
+					}
+					urlBuilder.append(url);
+				}
+			}
+		}
+		return urlBuilder.toString();
+	}
+
+	private void handleException(Exception e) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Displaying message from Exception {}\n{}", e.getClass(), e.getMessage());
+		}
+		// TODO: Fix handling error message.
+		// Sometimes the Axis2 stub throws only the RemoteException (an
+		// AxisFault)
+		// So, other exceptions won't come here.
+		String message = e.getMessage();
+		if (message == null || (message != null && message.contains("Exception"))) {
+			message = "Error executing command!";
+		}
+		if (logger.isErrorEnabled()) {
+			logger.error(message);
+		}
+		System.out.println(message);
+		throw new CommandException(message, e);
+	}
+    
+    private void handleException(String key, Exception e, Object... args) throws CommandException {
+    	if (logger.isDebugEnabled()) {
+    		logger.debug("Displaying message for {}. Exception thrown is {}", key, e.getClass());
+    	}
+    	String message = CommandLineUtils.getMessage(key, args);
+        if (logger.isErrorEnabled()) {
+        	logger.error(message);
+        }
+        System.out.println(message);
+        throw new CommandException(message, e);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/StratosApplication.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/StratosApplication.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/StratosApplication.java
new file mode 100644
index 0000000..74caf39
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/StratosApplication.java
@@ -0,0 +1,504 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli;
+
+import static org.apache.stratos.adc.mgt.cli.utils.CliConstants.STRATOS_DIR;
+import static org.apache.stratos.adc.mgt.cli.utils.CliConstants.STRATOS_HISTORY_DIR;
+
+import java.io.File;
+import java.io.PrintWriter;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.stratos.adc.mgt.cli.completer.CommandCompleter;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.text.StrTokenizer;
+import org.apache.commons.validator.routines.UrlValidator;
+import org.apache.log4j.Level;
+import org.apache.log4j.LogManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.commands.AddDomainMappingCommand;
+import org.apache.stratos.adc.mgt.cli.commands.CartridgesCommand;
+import org.apache.stratos.adc.mgt.cli.commands.ExitCommand;
+import org.apache.stratos.adc.mgt.cli.commands.HelpCommand;
+import org.apache.stratos.adc.mgt.cli.commands.InfoCommand;
+import org.apache.stratos.adc.mgt.cli.commands.ListCommand;
+import org.apache.stratos.adc.mgt.cli.commands.PoliciesCommand;
+import org.apache.stratos.adc.mgt.cli.commands.RemoveDomainMappingCommand;
+import org.apache.stratos.adc.mgt.cli.commands.SubscribeCommand;
+import org.apache.stratos.adc.mgt.cli.commands.SyncCommand;
+import org.apache.stratos.adc.mgt.cli.commands.UnsubscribeCommand;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class StratosApplication extends CommandLineApplication<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(StratosApplication.class);
+
+	private final Map<String, Command<StratosCommandContext>> commands;
+	private final StratosCommandContext context;
+
+	private final Options options;
+
+	public StratosApplication() {
+		commands = new HashMap<String, Command<StratosCommandContext>>();
+		context = new StratosCommandContext(this);
+
+		options = constructOptions();
+
+		createCommands();
+		createAutocomplete();
+	}
+
+	/**
+	 * Construct Options.
+	 * 
+	 * @return Options expected from command-line.
+	 */
+	private Options constructOptions() {
+		final Options options = new Options();
+		Option usernameOption = new Option(CliConstants.USERNAME_OPTION, CliConstants.USERNAME_LONG_OPTION, true,
+				"Username");
+		usernameOption.setArgName("username");
+		options.addOption(usernameOption);
+
+		Option passwordOption = new Option(CliConstants.PASSWORD_OPTION, CliConstants.PASSWORD_LONG_OPTION, true,
+				"Password");
+		passwordOption.setArgName("password");
+		passwordOption.setOptionalArg(true);
+		options.addOption(passwordOption);
+		options.addOption(CliConstants.HELP_OPTION, CliConstants.HELP_LONG_OPTION, false, "Display this help");
+		options.addOption(CliConstants.TRACE_OPTION, false, "Enable trace logging");
+		options.addOption(CliConstants.DEBUG_OPTION, false, "Enable debug logging");
+		return options;
+	}
+
+	private void createCommands() {
+		Command<StratosCommandContext> command = new HelpCommand();
+		commands.put(command.getName(), command);
+
+		command = new ExitCommand();
+		commands.put(command.getName(), command);
+
+		command = new SubscribeCommand();
+		commands.put(command.getName(), command);
+
+		command = new UnsubscribeCommand();
+		commands.put(command.getName(), command);
+		
+		command = new CartridgesCommand();
+		commands.put(command.getName(), command);
+		
+		command = new ListCommand();
+		commands.put(command.getName(), command);
+		
+		command = new InfoCommand();
+		commands.put(command.getName(), command);
+		
+		command = new AddDomainMappingCommand();
+		commands.put(command.getName(), command);
+		
+		command = new RemoveDomainMappingCommand();
+		commands.put(command.getName(), command);
+		
+		command = new SyncCommand();
+		commands.put(command.getName(), command);
+		
+		command = new PoliciesCommand();
+		commands.put(command.getName(), command);
+
+		if (logger.isDebugEnabled()) {
+			logger.debug("Created {} commands for the application. {}", commands.size(), commands.keySet());
+		}
+	}
+
+	private void createAutocomplete() {
+		reader.addCompleter(new CommandCompleter(commands));
+	}
+
+	@Override
+	protected String getPrompt() {
+		return CliConstants.STRATOS_SHELL_PROMPT;
+	}
+
+	@Override
+	protected File getHistoryFile() {
+		File stratosFile = new File(System.getProperty("user.home"), STRATOS_DIR);
+		File historyFile = new File(stratosFile, STRATOS_HISTORY_DIR);
+		return historyFile;
+	}
+
+	@Override
+	public int run(String[] args) {
+		boolean loaded = loadRequiredProperties();
+		if (!loaded) {
+			return CliConstants.ERROR_CODE;
+		}
+
+		// To get the command action from arguments
+		String[] remainingArgs = null;
+
+		// Command action
+		String action = null;
+
+		String usernameInput = null;
+		String passwordInput = null;
+
+		if (args != null && args.length > 0) {
+			// Arguments are passed.
+			if (logger.isDebugEnabled()) {
+				logger.debug("Arguments:");
+				for (String arg : args) {
+					logger.debug(arg);
+				}
+			}
+
+			final CommandLineParser parser = new GnuParser();
+			CommandLine commandLine;
+			try {
+				// Must add all options. Otherwise actions cannot be performed directly by command line.
+				Options allCommandOptions = new Options();
+				for (Command<StratosCommandContext> command : commands.values()) {
+					Options commandOptions = command.getOptions();
+					if (commandOptions != null) {
+						Collection<?> allOptions = commandOptions.getOptions();
+						for (Object o : allOptions) {
+							allCommandOptions.addOption((Option) o);
+						}
+					}
+				}
+				// Add options in this application
+				Collection<?> allOptions = options.getOptions();
+				for (Object o : allOptions) {
+					allCommandOptions.addOption((Option) o);
+				}
+				
+				commandLine = parser.parse(allCommandOptions, args);
+				remainingArgs = commandLine.getArgs();
+				if (remainingArgs != null && remainingArgs.length > 0) {
+					// Get command action
+					action = remainingArgs[0];
+				}
+
+				// Set logger levels from this point onwards
+				setLoggerLevel(commandLine.hasOption(CliConstants.TRACE_OPTION),
+						commandLine.hasOption(CliConstants.DEBUG_OPTION));
+
+				if (commandLine.hasOption(CliConstants.USERNAME_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Username option is passed");
+					}
+					usernameInput = commandLine.getOptionValue(CliConstants.USERNAME_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.PASSWORD_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Password option is passed");
+					}
+					passwordInput = commandLine.getOptionValue(CliConstants.PASSWORD_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.HELP_ACTION)) {
+					printHelp();
+					return CliConstants.SUCCESSFUL_CODE;
+				}
+			} catch (ParseException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error parsing arguments when trying to login", e);
+				}
+				System.out.println(e.getMessage());
+				return CliConstants.BAD_ARGS_CODE; 
+			}
+
+		}
+
+		if (StringUtils.isNotBlank(action)) {
+			// User is executing an action
+			if (logger.isDebugEnabled()) {
+				logger.debug("Action: {}", action);
+			}
+			Command<StratosCommandContext> command = commands.get(action);
+			if (command == null) {
+				printHelp();
+				return CliConstants.BAD_ARGS_CODE;
+			}
+
+			boolean loginRequired = !CliConstants.HELP_ACTION.equals(action);
+			
+			if (loginRequired && logger.isDebugEnabled()) {
+				logger.debug("Trying to login...");
+			}
+
+			if (loginRequired && !login(usernameInput, passwordInput, false)) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("Exiting from CLI. Login required but login might have failed: {}", action);
+				}
+				// Exit
+				return CliConstants.ERROR_CODE;
+			}
+
+			try {
+				String[] actionArgs = Arrays.copyOfRange(remainingArgs, 1, remainingArgs.length);
+				if (logger.isDebugEnabled()) {
+					logger.debug("Executing Action: {} {}", action, Arrays.asList(actionArgs));
+				}
+				int returnCode = command.execute(context, actionArgs);
+				if (logger.isDebugEnabled()) {
+					logger.debug("Exiting with error code {} after executing action {}", returnCode, action);
+				}
+				System.exit(returnCode);
+			} catch (CommandException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error executing command: " + action, e);
+				}
+				return CliConstants.ERROR_CODE;
+			}
+		} else {
+			if (login(usernameInput, passwordInput, true)) {
+				System.out.println("Successfully Authenticated.");
+			} else {
+				// Exit
+				return CliConstants.ERROR_CODE;
+			}
+
+			promptLoop();
+		}
+		return CliConstants.SUCCESSFUL_CODE;
+	}
+
+	private boolean login(String usernameInput, String passwordInput, boolean validateLogin) {
+		// TODO Previous CLI version uses a keystore. Here we are not using it.
+		// Check whether user has passed username and password
+		if (StringUtils.isBlank(usernameInput) && StringUtils.isBlank(passwordInput)) {
+			// User has not passed any arguments.
+			// Try authenticating from the values found
+			usernameInput = context.getString(CliConstants.STRATOS_USERNAME_ENV_PROPERTY);
+			passwordInput = context.getString(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY);
+
+			if (logger.isDebugEnabled()) {
+				if (StringUtils.isNotBlank(usernameInput) && StringUtils.isNotBlank(passwordInput)) {
+					logger.debug("Found authentication details for {} from context", usernameInput);
+				}
+			}
+
+		}
+		// Get user input if not passed as args
+		if (StringUtils.isBlank(usernameInput)) {
+			usernameInput = getInput("Username");
+		} else {
+			System.out.format("Username: %s%n", usernameInput);
+		}
+		if (StringUtils.isBlank(passwordInput)) {
+			passwordInput = getInput("Password", '*');
+		}
+
+		boolean success = false;
+		String stratosURL = null;
+		stratosURL = context.getString(CliConstants.STRATOS_URL_ENV_PROPERTY);
+
+		try {
+			success = CommandLineService.getInstance().login(stratosURL, usernameInput, passwordInput, validateLogin);
+		} catch (Exception e) {
+			if (logger.isErrorEnabled()) {
+				logger.error("Error when trying to login", e);
+			}
+		}
+		if (success) {
+			if (logger.isDebugEnabled()) {
+				logger.debug("Successfully Authenticated.");
+			}
+		} else {
+			if (logger.isDebugEnabled()) {
+				logger.debug("Authentication failed.");
+			}
+		}
+		return success;
+	}
+
+	@Override
+	protected int executeCommand(String line) {
+		String[] tokens = new StrTokenizer(line).getTokenArray();
+		String action = tokens[0];
+		String[] actionArgs = Arrays.copyOfRange(tokens, 1, tokens.length);
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing command action: {}, Tokens: {}", action, tokens.length);
+		}
+		Command<StratosCommandContext> command = commands.get(action);
+		if (command == null) {
+			System.out.println(action + ": command not found.");
+			return CliConstants.BAD_ARGS_CODE;
+		}
+		try {
+			return command.execute(context, actionArgs);
+		} catch (CommandException e) {
+			if (logger.isErrorEnabled()) {
+				logger.error("Error executing command: " + action, e);
+			}
+			return CliConstants.ERROR_CODE;
+		}
+	}
+
+	/**
+	 * @return {@code true} if required properties are loaded
+	 */
+	private boolean loadRequiredProperties() {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Loading properties...");
+		}
+		// Load properties
+		String stratosURL = null;
+		String username = null;
+		String password = null;
+
+		stratosURL = System.getenv(CliConstants.STRATOS_URL_ENV_PROPERTY);
+		username = System.getenv(CliConstants.STRATOS_USERNAME_ENV_PROPERTY);
+		password = System.getenv(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY);
+
+		if (StringUtils.isBlank(stratosURL)) {
+			if (logger.isDebugEnabled()) {
+				logger.debug("Required configuration not found.");
+			}
+			// Stratos Controller details are not set.
+			System.out.format("Could not find required \"%s\" variable in your environment.%n",
+					CliConstants.STRATOS_URL_ENV_PROPERTY);
+			return false;
+		} else {
+			if (logger.isDebugEnabled()) {
+				logger.debug("Required configuration found. Validating {}", stratosURL);
+			}
+			UrlValidator urlValidator = new UrlValidator(new String[] { "https" });
+			if (!urlValidator.isValid(stratosURL)) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("Stratos Controller URL {} is not valid", stratosURL);
+				}
+				System.out.format(
+						"The \"%s\" variable in your environment is not a valid URL. You have provided \"%s\".%n"
+								+ "Please provide the Stratos Controller URL as follows%nhttps://<host>:<port>%n",
+						CliConstants.STRATOS_URL_ENV_PROPERTY, stratosURL);
+				return false;
+			}
+			if (logger.isDebugEnabled()) {
+				logger.debug("Stratos Controller URL {} is valid.", stratosURL);
+				logger.debug("Adding the values to context.");
+			}
+			context.put(CliConstants.STRATOS_URL_ENV_PROPERTY, stratosURL);
+			context.put(CliConstants.STRATOS_USERNAME_ENV_PROPERTY, username);
+			context.put(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY, password);
+			return true;
+		}
+	}
+	
+	private void setLoggerLevel(boolean trace, boolean debug) {
+		// We are using Log4j. So, get the logger and set log levels.
+		org.apache.log4j.Logger logger = LogManager.getLogger(StratosApplication.class.getPackage().getName());
+		if (logger != null && trace) {
+			logger.setLevel(Level.TRACE);
+			LogManager.getRootLogger().setLevel(Level.TRACE);
+		} else if (logger != null && debug) {
+			logger.setLevel(Level.DEBUG);
+			LogManager.getRootLogger().setLevel(Level.DEBUG);
+		}
+	}
+
+	public void printHelp(final String action) {
+		Command<StratosCommandContext> command = commands.get(action);
+		if (command == null) {
+			System.out.println(action + ": command not found. Help not available.");
+			return;
+		}
+		System.out.println(command.getDescription());
+		Options options = command.getOptions();
+		if (options != null) {
+			if (StringUtils.isNotBlank(command.getArgumentSyntax())) {
+				printHelp(command.getName() + " " + command.getArgumentSyntax(), options);
+			} else {
+				printHelp(command.getName(), options);
+			}
+		} else {
+			// No options. Just print the usage.
+			printUsage(command);
+		}
+	}
+
+	public void printHelp() {
+		printHelp(CliConstants.STRATOS_APPLICATION_NAME, options);
+		System.out.println("\n\nAvailable Commands: ");
+		for (String action : commands.keySet()) {
+			Command<StratosCommandContext> command = commands.get(action);
+			if (command != null) {
+				System.out.format("%-25s %s%n", command.getName(), command.getDescription());
+			}
+		}
+
+		System.out.println("\nFor help on a specific command type:\nhelp [command]");
+	}
+
+	/**
+	 * Print "help" with usage
+	 */
+	private void printHelp(final String commandLineSyntax, final Options options) {
+		final HelpFormatter helpFormatter = new HelpFormatter();
+		helpFormatter.printHelp(commandLineSyntax, options, true);
+	}
+	
+	public void printUsage(final String action) {
+		Command<StratosCommandContext> command = commands.get(action);
+		if (command == null) {
+			return;
+		}
+		printUsage(command);
+	}
+	
+	private void printUsage(Command<StratosCommandContext> command) {
+		Options options = command.getOptions();
+		if (options != null) {
+			if (StringUtils.isNotBlank(command.getArgumentSyntax())) {
+				printUsage(command.getName() + " " + command.getArgumentSyntax(), options);
+			} else {
+				printUsage(command.getName(), options);
+			}
+		} else {
+			System.out.print("usage: ");
+			if (StringUtils.isNotBlank(command.getArgumentSyntax())) {
+				System.out.println(command.getName() + " " + command.getArgumentSyntax());
+			} else {
+				System.out.println(command.getName());
+			}
+		}
+	}
+	
+	/**
+	 * Print "usage"
+	 */
+	private void printUsage(final String commandLineSyntax, final Options options) {
+		final PrintWriter writer = new PrintWriter(System.out);
+		final HelpFormatter usageFormatter = new HelpFormatter();
+		usageFormatter.printUsage(writer, 80, commandLineSyntax, options);
+		writer.flush();
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/StratosCommandContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/StratosCommandContext.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/StratosCommandContext.java
new file mode 100644
index 0000000..e4f7652
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/StratosCommandContext.java
@@ -0,0 +1,31 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli;
+
+public class StratosCommandContext extends CommandContext {
+
+	public StratosCommandContext(StratosApplication application) {
+		super(application);
+	}
+
+	public StratosApplication getStratosApplication() {
+		return (StratosApplication) getApplication();
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/AddDomainMappingCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/AddDomainMappingCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/AddDomainMappingCommand.java
new file mode 100644
index 0000000..fe25f02
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/AddDomainMappingCommand.java
@@ -0,0 +1,87 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.commons.cli.Options;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.CommandLineService;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class AddDomainMappingCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(AddDomainMappingCommand.class);
+
+	public AddDomainMappingCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.ADD_DOMAIN_MAPPING_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Map domain for the subscribed cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge alias] [Domain]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length == 2) {
+			String alias = args[0];
+			String domain = args[1];
+			if (logger.isDebugEnabled()) {
+				logger.debug("Adding domain mapping {} for alias {}", domain, alias);
+			}
+
+			String domainToDisplay = null;
+
+			domainToDisplay = CommandLineService.getInstance().addDomainMapping(domain, alias);
+
+			if (StringUtils.isBlank(domainToDisplay)) {
+				System.out.println("Error adding domain mapping.");
+				return CliConstants.BAD_ARGS_CODE;
+			} else {
+				System.out.format("Your own domain is added. Please CNAME it to systems domain %s.%n", domainToDisplay);
+				return CliConstants.SUCCESSFUL_CODE;
+			}
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/CartridgesCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/CartridgesCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/CartridgesCommand.java
new file mode 100644
index 0000000..fc7461f
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/CartridgesCommand.java
@@ -0,0 +1,71 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.CommandLineService;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class CartridgesCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(CartridgesCommand.class);
+
+	public CartridgesCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.CARTRIDGES_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "List available cartridges";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return null;
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args == null || args.length == 0) {
+			CommandLineService.getInstance().listAvailableCartridges();
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ExitCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ExitCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ExitCommand.java
new file mode 100644
index 0000000..e0ff8c3
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ExitCommand.java
@@ -0,0 +1,70 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class ExitCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(ExitCommand.class);
+
+	public ExitCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.EXIT_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Exit from Stratos Client Tool";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return null;
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		// Nothing to execute here. This is a special command.
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args == null || args.length == 0) {
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/HelpCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/HelpCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/HelpCommand.java
new file mode 100644
index 0000000..ca74687
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/HelpCommand.java
@@ -0,0 +1,73 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class HelpCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(HelpCommand.class);
+
+	public HelpCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.HELP_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Help for commands";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[command]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args == null || args.length == 0) {
+			context.getStratosApplication().printHelp();
+			return CliConstants.SUCCESSFUL_CODE;
+		} else if (args != null && args.length == 1) {
+			context.getStratosApplication().printHelp(args[0]);
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/InfoCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/InfoCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/InfoCommand.java
new file mode 100644
index 0000000..a4ac08e
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/InfoCommand.java
@@ -0,0 +1,75 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.CommandLineService;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class InfoCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(InfoCommand.class);
+
+	public InfoCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.INFO_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Get information about a subscribed cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge alias]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length == 1) {
+			String alias = args[0];
+			if (logger.isDebugEnabled()) {
+				logger.debug("Getting info {}", alias);
+			}
+			CommandLineService.getInstance().info(alias);
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ListCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ListCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ListCommand.java
new file mode 100644
index 0000000..1b96182
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/ListCommand.java
@@ -0,0 +1,123 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.CommandLineService;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class ListCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(ListCommand.class);
+	
+	private final Options options;
+
+	public ListCommand() {
+		options = constructOptions();
+	}
+	
+	/**
+	 * Construct Options.
+	 * 
+	 * @return Options expected from command-line.
+	 */
+	private Options constructOptions() {
+		final Options options = new Options();
+		Option fullOption = new Option(CliConstants.FULL_OPTION, CliConstants.FULL_LONG_OPTION, false,
+				"Display extra details");
+		options.addOption(fullOption);
+		return options;
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.LIST_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "List subscribed cartridges with details";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return null;
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args == null || args.length == 0) {
+			CommandLineService.getInstance().listSubscribedCartridges(false);
+			return CliConstants.SUCCESSFUL_CODE;
+		} else if (args != null && args.length > 0) {
+			String[] remainingArgs = null;
+			boolean full = false;
+			final CommandLineParser parser = new GnuParser();
+			CommandLine commandLine;
+			try {
+				commandLine = parser.parse(options, args);
+				remainingArgs = commandLine.getArgs();
+				if (!(remainingArgs == null || remainingArgs.length == 0)) {
+					context.getStratosApplication().printUsage(getName());
+					return CliConstants.BAD_ARGS_CODE;
+				}
+
+				if (commandLine.hasOption(CliConstants.FULL_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Full option is passed");
+					}
+					full = true;
+				}
+				if (logger.isDebugEnabled()) {
+					logger.debug("Listing subscribed cartridges, Full Option: {}", full);
+				}
+				CommandLineService.getInstance().listSubscribedCartridges(full);
+				return CliConstants.SUCCESSFUL_CODE;
+			} catch (ParseException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error parsing arguments", e);
+				}
+				System.out.println(e.getMessage());
+				return CliConstants.BAD_ARGS_CODE;
+			}
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return options;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/PoliciesCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/PoliciesCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/PoliciesCommand.java
new file mode 100644
index 0000000..4811efd
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/PoliciesCommand.java
@@ -0,0 +1,71 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.CommandLineService;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class PoliciesCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(PoliciesCommand.class);
+
+	public PoliciesCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.POLICIES_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "List available policies";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return null;
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args == null || args.length == 0) {
+			CommandLineService.getInstance().listAvailablePolicies();
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/RemoveDomainMappingCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/RemoveDomainMappingCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/RemoveDomainMappingCommand.java
new file mode 100644
index 0000000..a3b4cc0
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/RemoveDomainMappingCommand.java
@@ -0,0 +1,75 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.CommandLineService;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class RemoveDomainMappingCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(RemoveDomainMappingCommand.class);
+
+	public RemoveDomainMappingCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.REMOVE_DOMAIN_MAPPING_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Remove domain mapping for the subscribed cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge alias]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length == 1) {
+			String alias = args[0];
+			if (logger.isDebugEnabled()) {
+				logger.debug("Removing domain mapping for {}", alias);
+			}
+			CommandLineService.getInstance().removeDomainMapping(alias);
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SubscribeCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SubscribeCommand.java b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SubscribeCommand.java
new file mode 100644
index 0000000..90908e9
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt.cli/src/main/java/org/apache/stratos/adc/mgt/cli/commands/SubscribeCommand.java
@@ -0,0 +1,208 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.adc.mgt.cli.commands;
+
+import org.apache.stratos.adc.mgt.cli.Command;
+import org.apache.stratos.adc.mgt.cli.CommandLineService;
+import org.apache.stratos.adc.mgt.cli.StratosCommandContext;
+import org.apache.stratos.adc.mgt.cli.exception.CommandException;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.stratos.adc.mgt.cli.utils.CliConstants;
+
+public class SubscribeCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(ListCommand.class);
+
+	private final Options options;;
+
+	public SubscribeCommand() {
+		options = constructOptions();
+	}
+
+	/**
+	 * Construct Options.
+	 * 
+	 * @return Options expected from command-line.
+	 */
+	private Options constructOptions() {
+		final Options options = new Options();
+		Option policyOption = new Option(CliConstants.POLICY_OPTION, CliConstants.POLICY_LONG_OPTION, true,
+				"Auto-scaling policy.\nPlease use \"" + CliConstants.POLICIES_ACTION
+						+ "\" command to view the available policies.");
+		policyOption.setArgName("policy name");
+		options.addOption(policyOption);
+
+		Option connectOption = new Option(CliConstants.CONNECT_OPTION, CliConstants.CONNECT_LONG_OPTION, true,
+				"Data cartridge type");
+		connectOption.setArgName("data cartridge type");
+		options.addOption(connectOption);
+
+		Option aliasOption = new Option(CliConstants.DATA_ALIAS_OPTION, CliConstants.DATA_ALIAS_LONG_OPTION, true,
+				"Data cartridge alias");
+		aliasOption.setArgName("alias");
+		options.addOption(aliasOption);
+
+		Option urlOption = new Option(CliConstants.REPO_URL_OPTION, CliConstants.REPO_URL_LONG_OPTION, true,
+				"GIT repository URL");
+		urlOption.setArgName("url");
+		options.addOption(urlOption);
+
+		options.addOption(CliConstants.PRIVATE_REPO_OPTION, CliConstants.PRIVATE_REPO_LONG_OPTION, false,
+				"Private repository");
+
+		Option usernameOption = new Option(CliConstants.USERNAME_OPTION, CliConstants.USERNAME_LONG_OPTION, true,
+				"GIT repository username");
+		usernameOption.setArgName("username");
+		options.addOption(usernameOption);
+
+		Option passwordOption = new Option(CliConstants.PASSWORD_OPTION, CliConstants.PASSWORD_LONG_OPTION, true,
+				"GIT repository password");
+		passwordOption.setArgName("password");
+		passwordOption.setOptionalArg(true);
+		options.addOption(passwordOption);
+		return options;
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.SUBSCRIBE_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Subscribe to a cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge type] [Cartridge alias]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length > 0) {
+			String[] remainingArgs = null;
+			String type = null;
+			String alias = null;
+			String policy = null;
+			String repoURL = null, dataCartridgeType = null, dataCartridgeAlias = null, username = "", password = "";
+			boolean privateRepo = false;
+			final CommandLineParser parser = new GnuParser();
+			CommandLine commandLine;
+			try {
+				commandLine = parser.parse(options, args);
+				remainingArgs = commandLine.getArgs();
+				if (remainingArgs != null && remainingArgs.length == 2) {
+					// Get type
+					type = remainingArgs[0];
+					alias = remainingArgs[1];
+				} else {
+					context.getStratosApplication().printUsage(getName());
+					return CliConstants.BAD_ARGS_CODE;
+				}
+
+				if (logger.isDebugEnabled()) {
+					logger.debug("Subscribing to {} cartridge with alias {}", type, alias);
+				}
+
+				if (commandLine.hasOption(CliConstants.POLICY_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Policy option is passed");
+					}
+					policy = commandLine.getOptionValue(CliConstants.POLICY_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.REPO_URL_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("RepoURL option is passed");
+					}
+					repoURL = commandLine.getOptionValue(CliConstants.REPO_URL_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.PRIVATE_REPO_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("privateRepo option is passed");
+					}
+					privateRepo = true;
+				}
+				if (commandLine.hasOption(CliConstants.USERNAME_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Username option is passed");
+					}
+					username = commandLine.getOptionValue(CliConstants.USERNAME_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.PASSWORD_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Password option is passed");
+					}
+					password = commandLine.getOptionValue(CliConstants.PASSWORD_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.CONNECT_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Connect option is passed");
+					}
+					dataCartridgeType = commandLine.getOptionValue(CliConstants.CONNECT_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.DATA_ALIAS_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Data alias option is passed");
+					}
+					dataCartridgeAlias = commandLine.getOptionValue(CliConstants.DATA_ALIAS_OPTION);
+				}
+				
+				if (StringUtils.isNotBlank(username) && StringUtils.isBlank(password)) {
+					password = context.getApplication().getInput("GIT Repository Password", '*');
+				}
+
+				if (StringUtils.isNotBlank(dataCartridgeType) && !StringUtils.isNotBlank(dataCartridgeAlias)) {
+					System.out.println("Data cartridge alias is required.");
+					context.getStratosApplication().printUsage(getName());
+					return CliConstants.BAD_ARGS_CODE;
+				}
+				CommandLineService.getInstance().subscribe(type, alias, policy, repoURL, privateRepo, username,
+						password, dataCartridgeType, dataCartridgeAlias);
+				return CliConstants.SUCCESSFUL_CODE;
+			} catch (ParseException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error parsing arguments", e);
+				}
+				System.out.println(e.getMessage());
+				return CliConstants.BAD_ARGS_CODE;
+			}
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return options;
+	}
+
+}


[06/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/DefaultTenantPersistor.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/DefaultTenantPersistor.java b/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/DefaultTenantPersistor.java
deleted file mode 100644
index 583d9de..0000000
--- a/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/DefaultTenantPersistor.java
+++ /dev/null
@@ -1,340 +0,0 @@
-/*
- * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- * http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.stratos.tenant.mgt.core;
-
-import org.apache.stratos.tenant.mgt.core.internal.TenantMgtCoreServiceComponent;
-import org.wso2.carbon.CarbonConstants;
-import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
-import org.wso2.carbon.registry.core.RegistryConstants;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.stratos.common.config.CloudServiceConfigParser;
-import org.wso2.carbon.stratos.common.config.CloudServicesDescConfig;
-import org.wso2.carbon.stratos.common.constants.StratosConstants;
-import org.wso2.carbon.stratos.common.util.CloudServicesUtil;
-import org.wso2.carbon.stratos.common.util.CommonUtil;
-import org.apache.stratos.tenant.mgt.core.util.TenantCoreUtil;
-import org.wso2.carbon.user.api.RealmConfiguration;
-import org.wso2.carbon.user.api.TenantMgtConfiguration;
-import org.wso2.carbon.user.core.AuthorizationManager;
-import org.wso2.carbon.user.core.UserCoreConstants;
-import org.wso2.carbon.user.core.UserRealm;
-import org.wso2.carbon.user.core.UserStoreException;
-import org.wso2.carbon.user.core.UserStoreManager;
-import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.user.core.tenant.Tenant;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-import org.wso2.carbon.user.mgt.UserMgtConstants;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * TenantPersistenceManager - Methods related to persisting the tenant.
- */
-public class DefaultTenantPersistor implements TenantPersistor {
-
-    private static final Log log = LogFactory.getLog(DefaultTenantPersistor.class);
-    private static final String ILLEGAL_CHARACTERS_FOR_PATH = ".*[~!#$;%^*()+={}\\[\\]\\|\\\\<>].*";
-
-    private static CloudServicesDescConfig cloudServicesDesc = null;
-        
-
-    /**
-     * Persists the given tenant
-     * @param tenant - tenant to be persisted
-     * @param checkDomainValidation - true, if domain is validated.
-     * @param successKey - successKey
-     * @param originatedService - The Service that the tenant registration was originated.
-     * @return tenant Id - the tenant id
-     * @throws Exception, if persisting tenant failed.
-     */
-    public int persistTenant(Tenant tenant, boolean checkDomainValidation, String successKey,
-                             String originatedService) throws Exception {
-        int tenantId;
-        validateAdminUserName(tenant);
-        String tenantDomain = tenant.getDomain();
-
-        boolean isDomainAvailable = CommonUtil.isDomainNameAvailable(tenantDomain);
-        if (!isDomainAvailable) {
-            throw new Exception("Domain is not available to register");
-        }
-
-        RealmService realmService = TenantMgtCoreServiceComponent.getRealmService();
-        RealmConfiguration realmConfig = realmService.getBootstrapRealmConfiguration();
-        TenantMgtConfiguration tenantMgtConfiguration = realmService.getTenantMgtConfiguration();
-        MultiTenantRealmConfigBuilder builder = TenantMgtCoreServiceComponent.
-                getRealmService().getMultiTenantRealmConfigBuilder();
-        RealmConfiguration realmConfigToPersist =
-                builder.getRealmConfigForTenantToPersist(realmConfig, tenantMgtConfiguration,
-                                                         tenant, -1);
-        tenant.setRealmConfig(realmConfigToPersist);
-        tenantId = addTenant(tenant);
-        tenant.setId(tenantId);
-
-        if (checkDomainValidation) { 
-            if (successKey != null) {
-                if (CommonUtil.validateDomainFromSuccessKey(TenantMgtCoreServiceComponent.
-                        getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID),
-                                                            tenant.getDomain(), successKey)) {
-                    storeDomainValidationFlagToRegistry(tenant);
-                } else {
-                    String msg = "Failed to validate domain";
-                    throw new Exception(msg);
-                }
-            }
-        } else {
-            storeDomainValidationFlagToRegistry(tenant);
-        }
-        
-        try {
-            doPostTenantCreationActions(tenant, originatedService);
-        } catch (Exception e) {
-            String msg = "Error performing post tenant creation actions";
-            throw new Exception(msg, e);
-        }
-
-        return tenantId;
-    }
-
-    private void doPostTenantCreationActions(Tenant tenant,
-                                             String originatedService) throws Exception {
-        RealmService realmService = TenantMgtCoreServiceComponent.getRealmService();
-        UserRealm userRealm;
-        try {
-            userRealm = (UserRealm) realmService.getTenantUserRealm(tenant.getId());
-        } catch (UserStoreException e) {
-            String msg = "Error in creating Realm for tenant: " + tenant.getDomain();
-            throw new Exception(msg, e);
-        }
-
-        updateTenantAdminPassword(userRealm, tenant);
-        TenantMgtCoreServiceComponent.getRegistryLoader().loadTenantRegistry(tenant.getId());
-        copyUIPermissions(tenant.getId());
-
-        TenantCoreUtil.setOriginatedService(tenant.getId(), originatedService);
-        setActivationFlags(tenant.getId(), originatedService);
-
-        TenantCoreUtil.initializeRegistry(tenant.getId());
-
-    }
-
-    /**
-     * Store the domain validation flag in the registry if the domain has been
-     * validated.
-     * 
-     * @param tenant - the tenant
-     * @throws RegistryException, if storing the domain validation flag failed.
-     */
-    private void storeDomainValidationFlagToRegistry(Tenant tenant) throws RegistryException {
-
-        try {
-            String domainValidationPath = StratosConstants.TENANT_DOMAIN_VERIFICATION_FLAG_PATH +
-                                                  RegistryConstants.PATH_SEPARATOR + tenant.getId();
-            UserRegistry superTenantRegistry = TenantMgtCoreServiceComponent.
-                    getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
-            Resource validationFlagR = superTenantRegistry.newResource();
-            validationFlagR.setProperty(tenant.getDomain(), "true");
-            superTenantRegistry.put(domainValidationPath, validationFlagR);
-
-        } catch (RegistryException e) {
-            String msg = "Error in storing the domain validation flag to the registry";
-            log.error(msg, e);
-            throw new RegistryException(msg, e);
-        }
-        if (log.isDebugEnabled()) {
-            log.debug("Domain Validation Flag is stored to the registry.");
-        }
-    }
-
-    /**
-     * Adds a tenant to the tenant manager
-     * 
-     * @param tenant - the tenant
-     * @return tenantId - the tenant id
-     * @throws Exception - UserStoreException
-     */
-    private int addTenant(Tenant tenant) throws Exception {
-        int tenantId;
-        TenantManager tenantManager = TenantMgtCoreServiceComponent.getTenantManager();
-        try {
-            tenantId = tenantManager.addTenant(tenant);
-            if (log.isDebugEnabled()) {
-                log.debug("Tenant is successfully added: " + tenant.getDomain());
-            }
-        } catch (UserStoreException e) {
-            String msg = "Error in adding tenant with domain: " + tenant.getDomain();
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-        return tenantId;
-    }
-
-    /**
-     * Sets the password for the tenant
-     * 
-     * @param tenant - the tenant
-     * @param userRealm - user realm
-     * @throws Exception - UserStoreException
-     */
-    private void updateTenantAdminPassword(UserRealm userRealm, Tenant tenant) throws Exception {
-        try {
-            UserStoreManager userStoreManager = userRealm.getUserStoreManager();
-            if (!userStoreManager.isReadOnly()) {
-                userStoreManager.updateCredentialByAdmin(tenant.getAdminName(),
-                                                         tenant.getAdminPassword());
-                if (log.isDebugEnabled()) {
-                    log.debug("Successfully set the password for the tenant.");
-                }
-            }
-        } catch (UserStoreException e) {
-            String msg = "Error in changing the tenant admin password for tenant domain: " +
-                                 tenant.getDomain() + ".";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-    }
-
-    /**
-     * Authorize the role
-     *
-     * @param tenantId - tenant id
-     * @throws Exception - UserStoreException
-     */
-    private void copyUIPermissions(int tenantId) throws Exception {
-        try {
-            UserRealm realm = (UserRealm) TenantMgtCoreServiceComponent.
-                    getRealmService().getTenantUserRealm(tenantId);
-            String adminRole = realm.getRealmConfiguration().getAdminRoleName();
-            AuthorizationManager authMan = realm.getAuthorizationManager();
-            // Authorize the admin role, if not authorized yet.
-            if (!authMan.isRoleAuthorized(adminRole,
-                                          CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION,
-                                          UserMgtConstants.EXECUTE_ACTION)) {
-                authMan.authorizeRole(adminRole, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION,
-                                      UserMgtConstants.EXECUTE_ACTION);
-            }
-        } catch (UserStoreException e) {
-            String msg = "Error in authorizing the admin role.";
-            log.error(msg, e);
-            throw new Exception(msg, e);
-        }
-        if (log.isDebugEnabled()) {
-            log.debug("Role has successfully been authorized.");
-        }
-    }
-    
-    private void setActivationFlags(int tenantId, String originalService) throws Exception {
-
-        boolean useDefaultConfig = true;
-        try {
-            
-            if(cloudServicesDesc == null ) { 
-                cloudServicesDesc = CloudServiceConfigParser.loadCloudServicesConfiguration();
-            }
-
-            if (originalService != null &&
-                !originalService.equals(StratosConstants.CLOUD_MANAGER_SERVICE) ) {
-                CloudServicesUtil.activateOriginalAndCompulsoryServices(cloudServicesDesc,
-                                                                        originalService, tenantId);
-                useDefaultConfig = false;
-            }
-
-            if (useDefaultConfig) {
-                CloudServicesUtil.activateAllServices(cloudServicesDesc, tenantId);
-            }
-        } catch (Exception e) {
-            log.error("Error registering the originated service", e);
-            throw e;
-        }
-        
-    }
-
-    /**
-     * Validates that the chosen AdminUserName is valid.
-     * 
-     * @param tenant
-     *            tenant information
-     * @throws Exception
-     *             UserStoreException
-     */
-    private void validateAdminUserName(Tenant tenant) throws Exception {
-        UserRealm superTenantUserRealm =
-                                        TenantMgtCoreServiceComponent.getRealmService().
-                                                                      getBootstrapRealm();
-        RealmConfiguration realmConfig = TenantMgtCoreServiceComponent.
-                getBootstrapRealmConfiguration();
-        String uniqueAcrossTenants = realmConfig.getUserStoreProperty(
-                UserCoreConstants.RealmConfig.PROPERTY_USERNAME_UNIQUE);
-        if ("true".equals(uniqueAcrossTenants)) {
-            try {
-                if (superTenantUserRealm.getUserStoreManager().isExistingUser(
-                        tenant.getAdminName())) {
-                    throw new Exception("User name : " + tenant.getAdminName() +
-                                        " exists in the system. " +
-                                        "Please pick another user name for tenant Administrator.");
-                }
-            } catch (UserStoreException e) {
-                String msg = "Error in checking whether the user already exists in the system";
-                log.error(msg, e);
-                throw new Exception(msg, e);
-            }
-        }
-        if (tenant.getAdminName().matches(DefaultTenantPersistor.ILLEGAL_CHARACTERS_FOR_PATH)) {
-            String msg = "The tenant admin ' " + tenant.getAdminName() +
-                                 " ' contains one or more illegal characters" +
-                                 " (~!@#$;%^*()+={}[]|\\<>)";
-            log.error(msg);
-            throw new Exception(msg);
-        }
-        if (log.isDebugEnabled()) {
-            log.debug("Admin User Name has been validated.");
-        }
-    }
-
-    /**
-     * Persists the given tenant
-     * @param tenant - tenant to be persisted
-     * @return tenant Id
-     * @throws Exception, if persisting tenant failed.
-     */
-    public int persistTenant(Tenant tenant) throws Exception {
-        String tenantDomain = tenant.getDomain();
-        int tenantId;
-        validateAdminUserName(tenant);
-        boolean isDomainAvailable = CommonUtil.isDomainNameAvailable(tenantDomain);
-        if (!isDomainAvailable) {
-            throw new Exception("Domain is not available to register");
-        }
-
-        tenantId = addTenant(tenant);
-        tenant.setId(tenantId);
-
-        try {
-            doPostTenantCreationActions(tenant, null);
-        } catch (Exception e) {
-            String msg = "Error performing post tenant creation actions";
-            if(log.isDebugEnabled()) {
-                log.debug(msg, e);
-            }
-            throw new Exception(msg);
-        }
-        return tenantId;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/internal/TenantMgtCoreServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/internal/TenantMgtCoreServiceComponent.java b/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/internal/TenantMgtCoreServiceComponent.java
deleted file mode 100644
index 6b1dab9..0000000
--- a/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/internal/TenantMgtCoreServiceComponent.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.tenant.mgt.core.internal;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.BundleContext;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.user.api.RealmConfiguration;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-import org.apache.stratos.tenant.mgt.core.DefaultTenantPersistor;
-
-/**
- * @scr.component name="org.wso2.carbon.tenant.mgt.core" immediate="true"
- * @scr.reference name="registry.service"
- *                interface="org.wso2.carbon.registry.core.service.RegistryService"
- *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
- *                unbind="unsetRegistryService"
- * @scr.reference name="user.realmservice.default"
- *                interface="org.wso2.carbon.user.core.service.RealmService"
- *                cardinality="1..1" policy="dynamic" bind="setRealmService"
- *                unbind="unsetRealmService"
- * @scr.reference name="tenant.registryloader"
- *                interface="org.wso2.carbon.registry.core.service.TenantRegistryLoader"
- *                cardinality="1..1" policy="dynamic" bind="setTenantRegistryLoader"
- *                unbind="unsetTenantRegistryLoader"
- */
-public class TenantMgtCoreServiceComponent {
-    private static Log log = LogFactory.getLog(TenantMgtCoreServiceComponent.class);
-
-    private static BundleContext bundleContext;
-    private static RealmService realmService;
-    private static RegistryService registryService;
-    private static TenantPersistor tenantPersistor;
-    private static TenantRegistryLoader registryLoader;
-    
-    protected void activate(ComponentContext context) {
-        try {
-            tenantPersistor = new DefaultTenantPersistor();
-            bundleContext = context.getBundleContext();
-            bundleContext.registerService(TenantPersistor.class.getName(), tenantPersistor, null);
-            log.debug("******* Tenant Core bundle is activated ******* ");
-        } catch (Exception e) {
-            log.error("Error occurred while activating tenant.mgt.core bundle. " + e);
-        }
-    }
-    
-    protected void setTenantRegistryLoader(TenantRegistryLoader tenantRegLoader) {
-        TenantMgtCoreServiceComponent.registryLoader = tenantRegLoader;
-    }
-
-    protected void unsetTenantRegistryLoader(TenantRegistryLoader tenantRegLoader) {
-        TenantMgtCoreServiceComponent.registryLoader = null;
-    }
-
-    protected void deactivate(ComponentContext context) {
-        log.debug("******* Tenant Core bundle is deactivated ******* ");
-    }
-
-    protected void setRegistryService(RegistryService registryService) {
-        TenantMgtCoreServiceComponent.registryService = registryService;
-    }
-
-    protected void unsetRegistryService(RegistryService registryService) {
-        setRegistryService(null);
-    }
-
-    protected void setRealmService(RealmService realmService) {
-        TenantMgtCoreServiceComponent.realmService = realmService;
-    }
-
-    protected void unsetRealmService(RealmService realmService) {
-        setRealmService(null);
-    }
-
-    public static BundleContext getBundleContext() {
-        return bundleContext;
-    }
-
-    public static RegistryService getRegistryService() {
-        return registryService;
-    }
-
-
-    public static RealmService getRealmService() {
-        return realmService;
-    }
-
-    public static TenantManager getTenantManager() {
-        return realmService.getTenantManager();
-    }
-
-    public static RealmConfiguration getBootstrapRealmConfiguration() {
-        return realmService.getBootstrapRealmConfiguration();
-    }
-
-    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
-        return registryService.getGovernanceSystemRegistry(tenantId);
-    }
-
-    public static UserRegistry getConfigSystemRegistry(int tenantId) throws RegistryException {
-        return registryService.getConfigSystemRegistry(tenantId);
-    }
-
-    public static TenantRegistryLoader getRegistryLoader() {
-        return registryLoader;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/util/TenantCoreUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/util/TenantCoreUtil.java b/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/util/TenantCoreUtil.java
deleted file mode 100644
index d2fd2be..0000000
--- a/components/org.apache.stratos.tenant.mgt.core/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/core/util/TenantCoreUtil.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package org.apache.stratos.tenant.mgt.core.util;
-
-import org.apache.stratos.tenant.mgt.core.internal.TenantMgtCoreServiceComponent;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.osgi.framework.BundleContext;
-import org.osgi.util.tracker.ServiceTracker;
-import org.wso2.carbon.registry.core.Resource;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.utils.AuthenticationObserver;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-import org.wso2.carbon.stratos.common.constants.StratosConstants;
-
-
-/**
- * Tenant Core Util class - used by any service that needs to create a tenant.
- */
-public class TenantCoreUtil {
-    
-    private static final Log log = LogFactory.getLog(TenantCoreUtil.class);
-
-    /**
-     * Initializes the registry for the tenant.
-     * 
-     * @param tenantId
-     *            tenant id.
-     */
-    public static void initializeRegistry(int tenantId) {
-        BundleContext bundleContext = TenantMgtCoreServiceComponent.getBundleContext();
-        if (bundleContext != null) {
-            ServiceTracker tracker =
-                                     new ServiceTracker(bundleContext,
-                                                        AuthenticationObserver.class.getName(),
-                                                        null);
-            tracker.open();
-            Object[] services = tracker.getServices();
-            if (services != null) {
-                for (Object service : services) {
-                    ((AuthenticationObserver) service).startedAuthentication(tenantId);
-                }
-            }
-            tracker.close();
-        }
-    }
-
-    /**
-     * Setting the Originated
-     * @param tenantId - tenant Id
-     * @param originatedService - The Service from where the tenant registration was originated.
-     * @throws Exception, Registry Exception, if error in putting the originated Service resource
-     * to the governance registry.
-     */
-    public static void setOriginatedService(int tenantId,
-                                            String originatedService) throws Exception {
-        if (originatedService != null) { 
-            String originatedServicePath =
-                                           StratosConstants.ORIGINATED_SERVICE_PATH +
-                                                   StratosConstants.PATH_SEPARATOR +
-                                                   StratosConstants.ORIGINATED_SERVICE +
-                                                   StratosConstants.PATH_SEPARATOR + tenantId;
-            try {
-                Resource origServiceRes = TenantMgtCoreServiceComponent.
-                        getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID).newResource();
-                origServiceRes.setContent(originatedService);
-                TenantMgtCoreServiceComponent.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID).
-                        put(originatedServicePath, origServiceRes);
-            } catch (RegistryException e) {
-                String msg = "Error in putting the originated service resource " +
-                             "to the governance registry";
-                log.error(msg, e);
-                throw new RegistryException(msg, e);
-            }
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.core/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.core/pom.xml b/components/org.apache.stratos.tenant.mgt.core/pom.xml
new file mode 100644
index 0000000..2bc689a
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt.core/pom.xml
@@ -0,0 +1,80 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.tenant.mgt.core</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Tenant Managment Core</name>
+
+    <build>
+
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Private-Package>
+                            org.apache.stratos.tenant.mgt.core.internal.*;-split-package:=merge-last,
+                        </Private-Package>
+                        <Import-Package>
+                            org.apache.stratos.common.*,
+                            org.wso2.carbon.registry.core.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <Export-Package>
+                            org.apache.stratos.tenant.mgt.core.*,
+                        </Export-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+	    <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.common</artifactId>
+	    <version>${apache.stratos.version}</version>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/DefaultTenantPersistor.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/DefaultTenantPersistor.java b/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/DefaultTenantPersistor.java
new file mode 100644
index 0000000..d4f9b4e
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/DefaultTenantPersistor.java
@@ -0,0 +1,340 @@
+/*
+ * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stratos.tenant.mgt.core;
+
+import org.apache.stratos.tenant.mgt.core.internal.TenantMgtCoreServiceComponent;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.apache.stratos.common.config.CloudServiceConfigParser;
+import org.apache.stratos.common.config.CloudServicesDescConfig;
+import org.apache.stratos.common.constants.StratosConstants;
+import org.apache.stratos.common.util.CloudServicesUtil;
+import org.apache.stratos.common.util.CommonUtil;
+import org.apache.stratos.tenant.mgt.core.util.TenantCoreUtil;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.api.TenantMgtConfiguration;
+import org.wso2.carbon.user.core.AuthorizationManager;
+import org.wso2.carbon.user.core.UserCoreConstants;
+import org.wso2.carbon.user.core.UserRealm;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.UserStoreManager;
+import org.wso2.carbon.user.core.config.multitenancy.MultiTenantRealmConfigBuilder;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.user.mgt.UserMgtConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * TenantPersistenceManager - Methods related to persisting the tenant.
+ */
+public class DefaultTenantPersistor implements TenantPersistor {
+
+    private static final Log log = LogFactory.getLog(DefaultTenantPersistor.class);
+    private static final String ILLEGAL_CHARACTERS_FOR_PATH = ".*[~!#$;%^*()+={}\\[\\]\\|\\\\<>].*";
+
+    private static CloudServicesDescConfig cloudServicesDesc = null;
+        
+
+    /**
+     * Persists the given tenant
+     * @param tenant - tenant to be persisted
+     * @param checkDomainValidation - true, if domain is validated.
+     * @param successKey - successKey
+     * @param originatedService - The Service that the tenant registration was originated.
+     * @return tenant Id - the tenant id
+     * @throws Exception, if persisting tenant failed.
+     */
+    public int persistTenant(Tenant tenant, boolean checkDomainValidation, String successKey,
+                             String originatedService) throws Exception {
+        int tenantId;
+        validateAdminUserName(tenant);
+        String tenantDomain = tenant.getDomain();
+
+        boolean isDomainAvailable = CommonUtil.isDomainNameAvailable(tenantDomain);
+        if (!isDomainAvailable) {
+            throw new Exception("Domain is not available to register");
+        }
+
+        RealmService realmService = TenantMgtCoreServiceComponent.getRealmService();
+        RealmConfiguration realmConfig = realmService.getBootstrapRealmConfiguration();
+        TenantMgtConfiguration tenantMgtConfiguration = realmService.getTenantMgtConfiguration();
+        MultiTenantRealmConfigBuilder builder = TenantMgtCoreServiceComponent.
+                getRealmService().getMultiTenantRealmConfigBuilder();
+        RealmConfiguration realmConfigToPersist =
+                builder.getRealmConfigForTenantToPersist(realmConfig, tenantMgtConfiguration,
+                                                         tenant, -1);
+        tenant.setRealmConfig(realmConfigToPersist);
+        tenantId = addTenant(tenant);
+        tenant.setId(tenantId);
+
+        if (checkDomainValidation) { 
+            if (successKey != null) {
+                if (CommonUtil.validateDomainFromSuccessKey(TenantMgtCoreServiceComponent.
+                        getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID),
+                                                            tenant.getDomain(), successKey)) {
+                    storeDomainValidationFlagToRegistry(tenant);
+                } else {
+                    String msg = "Failed to validate domain";
+                    throw new Exception(msg);
+                }
+            }
+        } else {
+            storeDomainValidationFlagToRegistry(tenant);
+        }
+        
+        try {
+            doPostTenantCreationActions(tenant, originatedService);
+        } catch (Exception e) {
+            String msg = "Error performing post tenant creation actions";
+            throw new Exception(msg, e);
+        }
+
+        return tenantId;
+    }
+
+    private void doPostTenantCreationActions(Tenant tenant,
+                                             String originatedService) throws Exception {
+        RealmService realmService = TenantMgtCoreServiceComponent.getRealmService();
+        UserRealm userRealm;
+        try {
+            userRealm = (UserRealm) realmService.getTenantUserRealm(tenant.getId());
+        } catch (UserStoreException e) {
+            String msg = "Error in creating Realm for tenant: " + tenant.getDomain();
+            throw new Exception(msg, e);
+        }
+
+        updateTenantAdminPassword(userRealm, tenant);
+        TenantMgtCoreServiceComponent.getRegistryLoader().loadTenantRegistry(tenant.getId());
+        copyUIPermissions(tenant.getId());
+
+        TenantCoreUtil.setOriginatedService(tenant.getId(), originatedService);
+        setActivationFlags(tenant.getId(), originatedService);
+
+        TenantCoreUtil.initializeRegistry(tenant.getId());
+
+    }
+
+    /**
+     * Store the domain validation flag in the registry if the domain has been
+     * validated.
+     * 
+     * @param tenant - the tenant
+     * @throws RegistryException, if storing the domain validation flag failed.
+     */
+    private void storeDomainValidationFlagToRegistry(Tenant tenant) throws RegistryException {
+
+        try {
+            String domainValidationPath = StratosConstants.TENANT_DOMAIN_VERIFICATION_FLAG_PATH +
+                                                  RegistryConstants.PATH_SEPARATOR + tenant.getId();
+            UserRegistry superTenantRegistry = TenantMgtCoreServiceComponent.
+                    getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
+            Resource validationFlagR = superTenantRegistry.newResource();
+            validationFlagR.setProperty(tenant.getDomain(), "true");
+            superTenantRegistry.put(domainValidationPath, validationFlagR);
+
+        } catch (RegistryException e) {
+            String msg = "Error in storing the domain validation flag to the registry";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Domain Validation Flag is stored to the registry.");
+        }
+    }
+
+    /**
+     * Adds a tenant to the tenant manager
+     * 
+     * @param tenant - the tenant
+     * @return tenantId - the tenant id
+     * @throws Exception - UserStoreException
+     */
+    private int addTenant(Tenant tenant) throws Exception {
+        int tenantId;
+        TenantManager tenantManager = TenantMgtCoreServiceComponent.getTenantManager();
+        try {
+            tenantId = tenantManager.addTenant(tenant);
+            if (log.isDebugEnabled()) {
+                log.debug("Tenant is successfully added: " + tenant.getDomain());
+            }
+        } catch (UserStoreException e) {
+            String msg = "Error in adding tenant with domain: " + tenant.getDomain();
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        return tenantId;
+    }
+
+    /**
+     * Sets the password for the tenant
+     * 
+     * @param tenant - the tenant
+     * @param userRealm - user realm
+     * @throws Exception - UserStoreException
+     */
+    private void updateTenantAdminPassword(UserRealm userRealm, Tenant tenant) throws Exception {
+        try {
+            UserStoreManager userStoreManager = userRealm.getUserStoreManager();
+            if (!userStoreManager.isReadOnly()) {
+                userStoreManager.updateCredentialByAdmin(tenant.getAdminName(),
+                                                         tenant.getAdminPassword());
+                if (log.isDebugEnabled()) {
+                    log.debug("Successfully set the password for the tenant.");
+                }
+            }
+        } catch (UserStoreException e) {
+            String msg = "Error in changing the tenant admin password for tenant domain: " +
+                                 tenant.getDomain() + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+    }
+
+    /**
+     * Authorize the role
+     *
+     * @param tenantId - tenant id
+     * @throws Exception - UserStoreException
+     */
+    private void copyUIPermissions(int tenantId) throws Exception {
+        try {
+            UserRealm realm = (UserRealm) TenantMgtCoreServiceComponent.
+                    getRealmService().getTenantUserRealm(tenantId);
+            String adminRole = realm.getRealmConfiguration().getAdminRoleName();
+            AuthorizationManager authMan = realm.getAuthorizationManager();
+            // Authorize the admin role, if not authorized yet.
+            if (!authMan.isRoleAuthorized(adminRole,
+                                          CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION,
+                                          UserMgtConstants.EXECUTE_ACTION)) {
+                authMan.authorizeRole(adminRole, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION,
+                                      UserMgtConstants.EXECUTE_ACTION);
+            }
+        } catch (UserStoreException e) {
+            String msg = "Error in authorizing the admin role.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Role has successfully been authorized.");
+        }
+    }
+    
+    private void setActivationFlags(int tenantId, String originalService) throws Exception {
+
+        boolean useDefaultConfig = true;
+        try {
+            
+            if(cloudServicesDesc == null ) { 
+                cloudServicesDesc = CloudServiceConfigParser.loadCloudServicesConfiguration();
+            }
+
+            if (originalService != null &&
+                !originalService.equals(StratosConstants.CLOUD_MANAGER_SERVICE) ) {
+                CloudServicesUtil.activateOriginalAndCompulsoryServices(cloudServicesDesc,
+                                                                        originalService, tenantId);
+                useDefaultConfig = false;
+            }
+
+            if (useDefaultConfig) {
+                CloudServicesUtil.activateAllServices(cloudServicesDesc, tenantId);
+            }
+        } catch (Exception e) {
+            log.error("Error registering the originated service", e);
+            throw e;
+        }
+        
+    }
+
+    /**
+     * Validates that the chosen AdminUserName is valid.
+     * 
+     * @param tenant
+     *            tenant information
+     * @throws Exception
+     *             UserStoreException
+     */
+    private void validateAdminUserName(Tenant tenant) throws Exception {
+        UserRealm superTenantUserRealm =
+                                        TenantMgtCoreServiceComponent.getRealmService().
+                                                                      getBootstrapRealm();
+        RealmConfiguration realmConfig = TenantMgtCoreServiceComponent.
+                getBootstrapRealmConfiguration();
+        String uniqueAcrossTenants = realmConfig.getUserStoreProperty(
+                UserCoreConstants.RealmConfig.PROPERTY_USERNAME_UNIQUE);
+        if ("true".equals(uniqueAcrossTenants)) {
+            try {
+                if (superTenantUserRealm.getUserStoreManager().isExistingUser(
+                        tenant.getAdminName())) {
+                    throw new Exception("User name : " + tenant.getAdminName() +
+                                        " exists in the system. " +
+                                        "Please pick another user name for tenant Administrator.");
+                }
+            } catch (UserStoreException e) {
+                String msg = "Error in checking whether the user already exists in the system";
+                log.error(msg, e);
+                throw new Exception(msg, e);
+            }
+        }
+        if (tenant.getAdminName().matches(DefaultTenantPersistor.ILLEGAL_CHARACTERS_FOR_PATH)) {
+            String msg = "The tenant admin ' " + tenant.getAdminName() +
+                                 " ' contains one or more illegal characters" +
+                                 " (~!@#$;%^*()+={}[]|\\<>)";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Admin User Name has been validated.");
+        }
+    }
+
+    /**
+     * Persists the given tenant
+     * @param tenant - tenant to be persisted
+     * @return tenant Id
+     * @throws Exception, if persisting tenant failed.
+     */
+    public int persistTenant(Tenant tenant) throws Exception {
+        String tenantDomain = tenant.getDomain();
+        int tenantId;
+        validateAdminUserName(tenant);
+        boolean isDomainAvailable = CommonUtil.isDomainNameAvailable(tenantDomain);
+        if (!isDomainAvailable) {
+            throw new Exception("Domain is not available to register");
+        }
+
+        tenantId = addTenant(tenant);
+        tenant.setId(tenantId);
+
+        try {
+            doPostTenantCreationActions(tenant, null);
+        } catch (Exception e) {
+            String msg = "Error performing post tenant creation actions";
+            if(log.isDebugEnabled()) {
+                log.debug(msg, e);
+            }
+            throw new Exception(msg);
+        }
+        return tenantId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/internal/TenantMgtCoreServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/internal/TenantMgtCoreServiceComponent.java b/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/internal/TenantMgtCoreServiceComponent.java
new file mode 100644
index 0000000..6b1dab9
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/internal/TenantMgtCoreServiceComponent.java
@@ -0,0 +1,129 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.stratos.tenant.mgt.core.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.core.multitenancy.persistence.TenantPersistor;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.apache.stratos.tenant.mgt.core.DefaultTenantPersistor;
+
+/**
+ * @scr.component name="org.wso2.carbon.tenant.mgt.core" immediate="true"
+ * @scr.reference name="registry.service"
+ *                interface="org.wso2.carbon.registry.core.service.RegistryService"
+ *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
+ *                unbind="unsetRegistryService"
+ * @scr.reference name="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1" policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ * @scr.reference name="tenant.registryloader"
+ *                interface="org.wso2.carbon.registry.core.service.TenantRegistryLoader"
+ *                cardinality="1..1" policy="dynamic" bind="setTenantRegistryLoader"
+ *                unbind="unsetTenantRegistryLoader"
+ */
+public class TenantMgtCoreServiceComponent {
+    private static Log log = LogFactory.getLog(TenantMgtCoreServiceComponent.class);
+
+    private static BundleContext bundleContext;
+    private static RealmService realmService;
+    private static RegistryService registryService;
+    private static TenantPersistor tenantPersistor;
+    private static TenantRegistryLoader registryLoader;
+    
+    protected void activate(ComponentContext context) {
+        try {
+            tenantPersistor = new DefaultTenantPersistor();
+            bundleContext = context.getBundleContext();
+            bundleContext.registerService(TenantPersistor.class.getName(), tenantPersistor, null);
+            log.debug("******* Tenant Core bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("Error occurred while activating tenant.mgt.core bundle. " + e);
+        }
+    }
+    
+    protected void setTenantRegistryLoader(TenantRegistryLoader tenantRegLoader) {
+        TenantMgtCoreServiceComponent.registryLoader = tenantRegLoader;
+    }
+
+    protected void unsetTenantRegistryLoader(TenantRegistryLoader tenantRegLoader) {
+        TenantMgtCoreServiceComponent.registryLoader = null;
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Tenant Core bundle is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        TenantMgtCoreServiceComponent.registryService = registryService;
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        TenantMgtCoreServiceComponent.realmService = realmService;
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        setRealmService(null);
+    }
+
+    public static BundleContext getBundleContext() {
+        return bundleContext;
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static TenantManager getTenantManager() {
+        return realmService.getTenantManager();
+    }
+
+    public static RealmConfiguration getBootstrapRealmConfiguration() {
+        return realmService.getBootstrapRealmConfiguration();
+    }
+
+    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getGovernanceSystemRegistry(tenantId);
+    }
+
+    public static UserRegistry getConfigSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getConfigSystemRegistry(tenantId);
+    }
+
+    public static TenantRegistryLoader getRegistryLoader() {
+        return registryLoader;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/util/TenantCoreUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/util/TenantCoreUtil.java b/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/util/TenantCoreUtil.java
new file mode 100644
index 0000000..625004e
--- /dev/null
+++ b/components/org.apache.stratos.tenant.mgt.core/src/main/java/org/apache/stratos/tenant/mgt/core/util/TenantCoreUtil.java
@@ -0,0 +1,76 @@
+package org.apache.stratos.tenant.mgt.core.util;
+
+import org.apache.stratos.tenant.mgt.core.internal.TenantMgtCoreServiceComponent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.util.tracker.ServiceTracker;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.utils.AuthenticationObserver;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.apache.stratos.common.constants.StratosConstants;
+
+
+/**
+ * Tenant Core Util class - used by any service that needs to create a tenant.
+ */
+public class TenantCoreUtil {
+    
+    private static final Log log = LogFactory.getLog(TenantCoreUtil.class);
+
+    /**
+     * Initializes the registry for the tenant.
+     * 
+     * @param tenantId
+     *            tenant id.
+     */
+    public static void initializeRegistry(int tenantId) {
+        BundleContext bundleContext = TenantMgtCoreServiceComponent.getBundleContext();
+        if (bundleContext != null) {
+            ServiceTracker tracker =
+                                     new ServiceTracker(bundleContext,
+                                                        AuthenticationObserver.class.getName(),
+                                                        null);
+            tracker.open();
+            Object[] services = tracker.getServices();
+            if (services != null) {
+                for (Object service : services) {
+                    ((AuthenticationObserver) service).startedAuthentication(tenantId);
+                }
+            }
+            tracker.close();
+        }
+    }
+
+    /**
+     * Setting the Originated
+     * @param tenantId - tenant Id
+     * @param originatedService - The Service from where the tenant registration was originated.
+     * @throws Exception, Registry Exception, if error in putting the originated Service resource
+     * to the governance registry.
+     */
+    public static void setOriginatedService(int tenantId,
+                                            String originatedService) throws Exception {
+        if (originatedService != null) { 
+            String originatedServicePath =
+                                           StratosConstants.ORIGINATED_SERVICE_PATH +
+                                                   StratosConstants.PATH_SEPARATOR +
+                                                   StratosConstants.ORIGINATED_SERVICE +
+                                                   StratosConstants.PATH_SEPARATOR + tenantId;
+            try {
+                Resource origServiceRes = TenantMgtCoreServiceComponent.
+                        getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID).newResource();
+                origServiceRes.setContent(originatedService);
+                TenantMgtCoreServiceComponent.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID).
+                        put(originatedServicePath, origServiceRes);
+            } catch (RegistryException e) {
+                String msg = "Error in putting the originated service resource " +
+                             "to the governance registry";
+                log.error(msg, e);
+                throw new RegistryException(msg, e);
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/pom.xml b/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/pom.xml
deleted file mode 100644
index b775337..0000000
--- a/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/pom.xml
+++ /dev/null
@@ -1,103 +0,0 @@
-<!--
-# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-  -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>stratos-components-parent</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-<relativePath>../../pom.xml</relativePath>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.tenant.mgt.email.sender</artifactId>
-    <packaging>bundle</packaging>
-    <name>Apache Stratos - Tenant Management Email Sender Component</name>
-
-    <build>
-
-        <plugins>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-scr-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.felix</groupId>
-                <artifactId>maven-bundle-plugin</artifactId>
-                
-                <extensions>true</extensions>
-                <configuration>
-                    <instructions>
-                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
-                        <Bundle-Name>${project.artifactId}</Bundle-Name>
-                        <Private-Package>
-                            org.apache.stratos.tenant.mgt.email.sender.internal.*,
-                            org.apache.stratos.tenant.mgt.email.sender.util.*,
-                        </Private-Package>
-                        <Export-Package>
-                            org.apache.stratos.tenant.mgt.email.sender.listener.*
-                        </Export-Package>
-                        <Import-Package>
-                            !javax.xml.namespace,
-                            javax.xml.namespace; version=0.0.0,
-                            org.wso2.carbon.email.sender.api,
-                            *;resolution:=optional
-                        </Import-Package>
-                    </instructions>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.apache.axis2.wso2</groupId>
-            <artifactId>axis2</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>log4j</groupId>
-            <artifactId>log4j</artifactId>
-	    <version>1.2.13</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.stratos.common</artifactId>
-	    <version>2.1.0</version>
-        </dependency>
-        <dependency>
-           <groupId>org.wso2.carbon</groupId>
-           <artifactId>org.wso2.carbon.email.verification</artifactId>
-	   <version>4.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.registry.core</artifactId>
-	    <version>4.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>commons-logging</groupId>
-            <artifactId>commons-logging</artifactId>
-	    <version>1.1.1</version>
-        </dependency>
-        <dependency>
-            <groupId>org.wso2.carbon</groupId>
-            <artifactId>org.wso2.carbon.email.sender</artifactId>
-            <version>2.1.0</version>
-        </dependency>
-    </dependencies>
-
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/DataHolder.java b/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/DataHolder.java
deleted file mode 100644
index 99710c9..0000000
--- a/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/DataHolder.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.stratos.tenant.mgt.email.sender.internal;
-
-import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.user.api.RealmConfiguration;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.user.core.tenant.TenantManager;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-import org.apache.axis2.context.ConfigurationContext;
-
-import org.osgi.framework.BundleContext;
-
-/**
- * Utility methods for the email sender component
- */
-public class DataHolder {
-
-    private static RegistryService registryService;
-    private static RealmService realmService;
-    private static ConfigurationContextService configurationContextService;
-    private static EmailVerifcationSubscriber emailVerificationService;
-    private static BundleContext bundleContext;
-
-    public static BundleContext getBundleContext() {
-        return bundleContext;
-    }
-
-    public static void setBundleContext(BundleContext bundleContext) {
-        DataHolder.bundleContext = bundleContext;
-    }
-
-    public static ConfigurationContextService getConfigurationContextService() {
-        return configurationContextService;
-    }
-
-    public static void setConfigurationContextService(
-            ConfigurationContextService configurationContextService) {
-        DataHolder.configurationContextService = configurationContextService;
-    }
-
-    public static ConfigurationContext getConfigurationContext() {
-        return configurationContextService.getServerConfigContext();
-    }
-
-    public static synchronized void setRegistryService(RegistryService service) {
-        if ((registryService == null) || (service == null)) {
-            registryService = service;
-        }
-    }
-
-    public static RegistryService getRegistryService() {
-        return registryService;
-    }
-
-    public static synchronized void setRealmService(RealmService service) {
-        if ((realmService == null) || (service == null)){
-            realmService = service;
-        }
-    }
-
-    public static RealmService getRealmService() {
-        return realmService;
-    }
-
-    public static TenantManager getTenantManager() {
-        return realmService.getTenantManager();
-    }
-
-    public static RealmConfiguration getBootstrapRealmConfiguration() {
-        return realmService.getBootstrapRealmConfiguration();
-    }
-
-    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
-        return registryService.getGovernanceSystemRegistry(tenantId);
-    }
-    
-    public static void setEmailVerificationService(EmailVerifcationSubscriber emailService) {
-        if ((emailVerificationService == null) || (emailService == null)){
-            emailVerificationService = emailService;
-        }
-    }
-    
-    public static EmailVerifcationSubscriber getEmailVerificationService() {
-        return emailVerificationService;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/TenantMgtEmailSenderServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/TenantMgtEmailSenderServiceComponent.java b/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/TenantMgtEmailSenderServiceComponent.java
deleted file mode 100644
index e51a22f..0000000
--- a/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/internal/TenantMgtEmailSenderServiceComponent.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
-*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-*  WSO2 Inc. licenses this file to you under the Apache License,
-*  Version 2.0 (the "License"); you may not use this file except
-*  in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*    http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied.  See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/
-package org.apache.stratos.tenant.mgt.email.sender.internal;
-
-import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.stratos.common.util.CommonUtil;
-import org.apache.stratos.tenant.mgt.email.sender.listener.EmailSenderListener;
-import org.apache.stratos.tenant.mgt.email.sender.util.TenantMgtEmailSenderUtil;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.utils.ConfigurationContextService;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.osgi.service.component.ComponentContext;
-
-/**
- * @scr.component name="org.wso2.carbon.tenant.mgt.email.sender"
- * immediate="true"
- * @scr.reference name="registry.service"
- * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="1..1"
- * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
- * @scr.reference name="user.realmservice.default" 
- * interface="org.wso2.carbon.user.core.service.RealmService" cardinality="1..1" 
- * policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
- * @scr.reference name="configuration.context.service"
- * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
- * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
- * @scr.reference name="emailverification.service" 
- * interface= "org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber"
- * cardinality="1..1" policy="dynamic"
- * bind="setEmailVerificationService" unbind="unsetEmailVerificationService"
- */
-public class TenantMgtEmailSenderServiceComponent {
-    private static Log log = LogFactory.getLog(TenantMgtEmailSenderServiceComponent.class);
-
-    protected void activate(ComponentContext context) {
-        try {
-            DataHolder.setBundleContext(context.getBundleContext());
-            if (!CommonUtil.isTenantManagementEmailsDisabled()) {
-                TenantMgtEmailSenderUtil.init();
-                EmailSenderListener emailSenderListener = new EmailSenderListener();
-                context.getBundleContext().registerService(
-                        org.wso2.carbon.stratos.common.listeners.TenantMgtListener.class.getName(),
-                        emailSenderListener, null);
-                log.debug("******* Tenant Management Emails are enabled ******* ");
-            }
-            log.debug("******* Tenant Registration Email Sender bundle is activated ******* ");
-        } catch (Throwable e) {
-            log.error("******* Tenant Registration Email Sender bundle failed activating ****", e);
-        }
-    }
-
-    protected void deactivate(ComponentContext context) {
-        log.debug("******* Email Sender bundle is deactivated ******* ");
-    }
-
-    protected void setRegistryService(RegistryService registryService) {
-        DataHolder.setRegistryService(registryService);
-    }
-
-    protected void unsetRegistryService(RegistryService registryService) {
-        DataHolder.setRegistryService(null);
-    }
-
-    protected void setRealmService(RealmService realmService) {
-        DataHolder.setRealmService(realmService);
-    }
-
-    protected void unsetRealmService(RealmService realmService) {
-        DataHolder.setRealmService(null);
-    }
-
-    protected void setConfigurationContextService(ConfigurationContextService service) {
-        DataHolder.setConfigurationContextService(service);
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService service) {
-        DataHolder.setConfigurationContextService(null);
-    }
-
-    protected void setEmailVerificationService(EmailVerifcationSubscriber emailService) {
-        DataHolder.setEmailVerificationService(emailService);
-    }
-
-    protected void unsetEmailVerificationService(EmailVerifcationSubscriber emailService) {
-        DataHolder.setEmailVerificationService(null);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/listener/EmailSenderListener.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/listener/EmailSenderListener.java b/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/listener/EmailSenderListener.java
deleted file mode 100644
index b3fdb03..0000000
--- a/components/org.apache.stratos.tenant.mgt.email.sender/2.1.0/src/main/java/org/apache/stratos/tenant/mgt/email/sender/listener/EmailSenderListener.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package org.apache.stratos.tenant.mgt.email.sender.listener;
-
-import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
-import org.wso2.carbon.stratos.common.exception.StratosException;
-import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
-import org.apache.stratos.tenant.mgt.email.sender.util.TenantMgtEmailSenderUtil;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class EmailSenderListener implements TenantMgtListener {
-    
-    private static final int EXEC_ORDER = 20;
-    private static final Log log = LogFactory.getLog(EmailSenderListener.class);
-
-    public void onTenantCreate(TenantInfoBean tenantInfoBean) throws StratosException {
-        try {
-            TenantMgtEmailSenderUtil.sendTenantCreationVerification(tenantInfoBean);
-        } catch (Exception e) {
-            String message = "Error sending tenant creation Mail to tenant domain " 
-                + tenantInfoBean.getTenantDomain();
-            log.error(message, e);
-            throw new StratosException(message, e);
-        }
-        TenantMgtEmailSenderUtil.notifyTenantCreationToSuperAdmin(tenantInfoBean);
-    }
-
-    public int getListenerOrder() {
-        return EXEC_ORDER;
-    }
-
-    public void onTenantRename(int tenantId, String oldDomainName, 
-                             String newDomainName) throws StratosException {
-        // Do nothing. 
-
-    }
-
-    public void onTenantUpdate(TenantInfoBean tenantInfoBean) throws StratosException {
-        if ((tenantInfoBean.getAdminPassword() != null) && 
-                (!tenantInfoBean.getAdminPassword().equals(""))) {
-            try {
-                TenantMgtEmailSenderUtil.notifyResetPassword(tenantInfoBean);
-            } catch (Exception e) {
-                String message = "Error sending tenant update Mail to tenant domain " 
-                    + tenantInfoBean.getTenantDomain();
-                log.error(message, e);
-                throw new StratosException(message, e);
-            }
-        }
-    }
-
-    public void onTenantInitialActivation(int tenantId) throws StratosException {
-     // send the notification message to the tenant admin
-        TenantMgtEmailSenderUtil.notifyTenantInitialActivation(tenantId);
-    }
-
-    public void onTenantActivation(int tenantId) throws StratosException {
-        // Do nothing. 
-    }
-
-    public void onTenantDeactivation(int tenantId) throws StratosException {
-        // Do nothing. 
-    }
-
-    public void onSubscriptionPlanChange(int tenentId, String oldPlan, 
-                                         String newPlan) throws StratosException {
-        // Do nothing. 
-    }
-
-}


[28/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/HostingConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/HostingConstants.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/HostingConstants.java
new file mode 100644
index 0000000..9259ea6
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/HostingConstants.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.internal;
+
+/**
+ * Web Application Constants
+ */
+public final class HostingConstants {
+	public static final String WEBAPP_PREFIX = "webapps";
+	public static final String WEBAPP_DEPLOYMENT_FOLDER = "webapps";
+	public static final String WEBAPP_EXTENSION = "war";
+
+	public static final class WebappState {
+		public static final String STARTED = "started";
+		public static final String STOPPED = "stopped";
+
+		private WebappState() {
+		}
+	}
+
+	private HostingConstants() {
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/HostingManagementActivator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/HostingManagementActivator.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/HostingManagementActivator.java
new file mode 100644
index 0000000..2e61894
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/internal/HostingManagementActivator.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * Activator for the Webapp Management Bundle
+ */
+public class HostingManagementActivator implements BundleActivator {
+	private static final Log log = LogFactory.getLog(HostingManagementActivator.class);
+
+	@Override
+	public void start(final BundleContext bundleContext) {
+
+		// If Carbon is running as a webapp within some other servlet container,
+		// then we should
+		// uninstall this component
+		if (!CarbonUtils.isRunningInStandaloneMode()) {
+			Thread th = new Thread() {
+				@Override
+				public void run() {
+					try {
+						bundleContext.getBundle().uninstall();
+					} catch (Throwable e) {
+						log.warn("Error occurred while uninstalling hosting.mgt UI bundle", e);
+					}
+				}
+			};
+			try {
+				th.join();
+			} catch (InterruptedException ignored) {
+			}
+			th.start();
+		}
+	}
+
+	@Override
+	public void stop(BundleContext bundleContext) {
+		// No implementation required for this method
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/ApplicationManagementService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/ApplicationManagementService.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/ApplicationManagementService.java
new file mode 100644
index 0000000..c977bc4
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/ApplicationManagementService.java
@@ -0,0 +1,620 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.service;
+
+import org.apache.axis2.AxisFault;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.custom.domain.RegistryManager;
+import org.apache.stratos.adc.mgt.dao.CartridgeSubscription;
+import org.apache.stratos.adc.mgt.dns.DNSManager;
+import org.apache.stratos.adc.mgt.dto.Cartridge;
+import org.apache.stratos.adc.mgt.dto.CartridgeWrapper;
+import org.apache.stratos.adc.mgt.dto.PolicyDefinition;
+import org.apache.stratos.adc.mgt.dto.RepositoryInformation;
+import org.apache.stratos.adc.mgt.dto.SubscriptionInfo;
+import org.apache.stratos.adc.mgt.exception.*;
+import org.apache.stratos.adc.mgt.internal.DataHolder;
+import org.apache.stratos.adc.mgt.utils.*;
+import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.apache.stratos.cloud.controller.util.xsd.CartridgeInfo;
+import org.wso2.carbon.utils.DataPaginator;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.regex.Pattern;
+
+/**
+ *
+ *
+ *
+ */
+public class ApplicationManagementService extends AbstractAdmin {
+
+
+    private static final Log log = LogFactory.getLog(ApplicationManagementService.class);
+    RegistryManager registryManager = new RegistryManager();
+
+    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+    String tenantDomain = carbonContext.getTenantDomain();
+    
+    /*
+     * Instantiate RepoNotificationService. Since this service is in the same 
+     * component (org.apache.stratos.adc.mgt), a new object is created.
+     * TODO: Is there a better way to get this service?
+     */
+    private RepoNotificationService repoNotificationService = new RepoNotificationService();
+
+	/**
+	 * Get Available Cartridges
+	 * 
+	 * @return Available Cartridges
+	 */
+	public Cartridge[] getAvailableCartridges(boolean multiTenant) throws ADCException {
+		List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant);
+		// Following is very important when working with axis2
+		return cartridges.isEmpty() ? new Cartridge[0] : cartridges.toArray(new Cartridge[cartridges.size()]);
+	}
+
+	/**
+	 * Get Subscribed Cartridges
+	 * 
+	 * @return Subscribed Cartridges
+	 */
+	public Cartridge[] getSubscribedCartridges() throws ADCException {
+		checkSuperTenant();
+		List<Cartridge> cartridgeList = getSubscribedCartridges(null);
+		// Following is very important when working with axis2
+		return cartridgeList.isEmpty() ? new Cartridge[0] : cartridgeList.toArray(new Cartridge[cartridgeList.size()]);
+	}
+
+	/**
+	 * Get available cartridges
+	 */
+	public CartridgeWrapper getPagedAvailableCartridges(String cartridgeSearchString, int pageNumber, boolean multiTenant)
+			throws ADCException {
+		checkSuperTenant();
+		CartridgeWrapper cartridgeWrapper = new CartridgeWrapper();
+		List<Cartridge> cartridges = getAvailableCartridges(cartridgeSearchString, multiTenant);
+    	
+		// TODO Improve pagination
+		if (!cartridges.isEmpty()) {
+			// Paginate only if cartridges are there.
+			DataPaginator.doPaging(pageNumber, cartridges, cartridgeWrapper);
+		} else {
+			// Must set this value as axis2 stub client will return an array
+			// with length = 1 and null element if cartridges[] is null
+			cartridgeWrapper.set(cartridges);
+		}
+		return cartridgeWrapper;
+	}
+
+	private List<Cartridge> getAvailableCartridges(String cartridgeSearchString, Boolean multiTenant) throws ADCException {
+		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 = ApplicationManagementUtil.getServiceClient().getRegisteredCartridges();
+
+			if (availableCartridges != null) {
+				for (String cartridgeType : availableCartridges) {
+					CartridgeInfo cartridgeInfo = null;
+					try {
+						cartridgeInfo = ApplicationManagementUtil.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 (!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.setStatus(CartridgeConstants.NOT_SUBSCRIBED);
+					cartridge.setCartridgeAlias("-");
+					cartridge.setActiveInstances(0);
+					cartridges.add(cartridge);
+					
+					if (cartridgeInfo.getMultiTenant() && !allowMultipleSubscription) {
+						// If the cartridge is multi-tenant. We should not let users
+						// subscribe twice.
+						if (PersistenceManager.isAlreadySubscribed(cartridgeType,
+								ApplicationManagementUtil.getTenantId(getConfigContext()))) {
+							if (log.isDebugEnabled()) {
+								log.debug("Already subscribed to " + cartridgeType
+										+ ". This multi-tenant cartridge will not be available to subscribe");
+							}
+							cartridge.setStatus(CartridgeConstants.SUBSCRIBED);
+						}
+					}
+				}
+			} else {
+				if (log.isDebugEnabled()) {
+					log.debug("There are no available cartridges");
+				}
+			}
+		} catch (Exception e) {
+			String msg = "Error when getting available cartridges. " + e.getMessage();
+			log.error(msg, e);
+			throw new ADCException("An error occurred getting available cartridges ", e);
+		}
+
+		Collections.sort(cartridges);
+
+		if (log.isDebugEnabled()) {
+			log.debug("Returning available cartridges " + cartridges.size());
+		}
+
+		return cartridges;
+	}
+
+	/**
+	 * Get subscribed cartridges
+	 */
+	public CartridgeWrapper getPagedSubscribedCartridges(String cartridgeSearchString, int pageNumber)
+			throws ADCException {
+		checkSuperTenant();
+		CartridgeWrapper cartridgeWrapper = new CartridgeWrapper();
+		List<Cartridge> cartridges = getSubscribedCartridges(cartridgeSearchString);
+
+		// TODO Improve pagination
+		if (!cartridges.isEmpty()) {
+			// Paginate only if cartridges are there.
+			DataPaginator.doPaging(pageNumber, cartridges, cartridgeWrapper);
+		} else {
+			cartridgeWrapper.set(cartridges);
+		}
+		return cartridgeWrapper;
+	}
+
+	private List<Cartridge> getSubscribedCartridges(String cartridgeSearchString) throws ADCException {
+		List<Cartridge> cartridges = new ArrayList<Cartridge>();
+		
+		if (log.isDebugEnabled()) {
+			log.debug("Getting subscribed cartridges. Search String: " + cartridgeSearchString);
+		}
+
+		try {
+			Pattern searchPattern = getSearchStringPattern(cartridgeSearchString);
+
+			List<CartridgeSubscription> subscriptionList = PersistenceManager
+					.retrieveSubscribedCartridges(ApplicationManagementUtil.getTenantId(getConfigContext()));
+
+			if (subscriptionList != null && !subscriptionList.isEmpty()) {
+				for (CartridgeSubscription subscription : subscriptionList) {
+					CartridgeInfo cartridgeInfo = null;
+					try {
+						cartridgeInfo = ApplicationManagementUtil.getServiceClient().getCartridgeInfo(
+								subscription.getCartridge());
+					} catch (Exception e) {
+						if (log.isWarnEnabled()) {
+							log.warn("Error when calling getCartridgeInfo for " + subscription.getCartridge()
+									+ ", Error: " + e.getMessage());
+						}
+					}
+					if (cartridgeInfo == null) {
+						// This cannot happen. But continue
+						if (log.isDebugEnabled()) {
+							log.debug("Cartridge Info not found: " + subscription.getCartridge());
+						}
+						continue;
+					}
+					if (!cartridgeMatches(cartridgeInfo, subscription, searchPattern)) {
+						continue;
+					}
+					TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
+					String[] ips = topologyMgtService.getActiveIPs(subscription.getCartridge(),
+							subscription.getClusterDomain(), subscription.getClusterSubdomain());
+					Cartridge cartridge = ApplicationManagementUtil.populateCartridgeInfo(cartridgeInfo, subscription, ips, tenantDomain);
+					cartridges.add(cartridge);
+				}
+			} else {
+				if (log.isDebugEnabled()) {
+					log.debug("There are no subscribed cartridges");
+				}
+			}
+		} catch (Exception e) {
+			String msg = "Error when getting subscribed cartridges. " + e.getMessage();
+			log.error(msg, e);
+			throw new ADCException("An Error occurred when getting subscribed cartridges.", e);
+		}
+
+		Collections.sort(cartridges);
+
+		if (log.isDebugEnabled()) {
+			log.debug("Returning subscribed cartridges " + cartridges.size());
+		}
+
+		return cartridges;
+	}
+
+    private 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;
+    }
+
+    // TODO: Improve search method
+    private 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 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.getCartridge() != null) {
+                matches = pattern.matcher(cartridgeSubscription.getCartridge().toLowerCase()).find();
+            }
+            if (!matches && cartridgeSubscription.getAlias() != null) {
+                matches = pattern.matcher(cartridgeSubscription.getAlias().toLowerCase()).find();
+            }
+            return matches;
+        }
+        return true;
+    }
+    
+    public Cartridge getCartridgeInfo(String alias) throws ADCException, NotSubscribedException {
+    	checkSuperTenant();
+    	return ApplicationManagementUtil.getCartridgeInfo(alias, getTenantDomain());
+    }
+
+    public String[] getSubscribedCartridgeAliases() throws AxisFault {
+        try {
+            List<CartridgeSubscription> subscriptionList = PersistenceManager
+                    .retrieveSubscribedCartridges(ApplicationManagementUtil.getTenantId(getConfigContext()));
+            List<String> subscribedAliases = new ArrayList<String>();
+            for (CartridgeSubscription cartridgeSubscription : subscriptionList) {
+
+                if(cartridgeSubscription.getProvider().equalsIgnoreCase(CartridgeConstants.PROVIDER_NAME_WSO2) &&
+                        getCartridgeInfo(cartridgeSubscription.getAlias()).isMultiTenant()) {
+
+                    subscribedAliases.add(cartridgeSubscription.getCartridge());
+                } else {
+                    subscribedAliases.add(cartridgeSubscription.getAlias());
+                }
+            }
+            if(subscribedAliases.size() == 0) {
+                return new String[]{""};
+            } else {
+                return subscribedAliases.toArray(new String[subscribedAliases.size()]);
+            }
+
+        } catch (Exception e) {
+            String msg = "Exception in getting subscribed cartridge aliases :" + e.getMessage();
+            log.error(msg, e);
+            throw new AxisFault("An error occurred while getting subscribed cartridge aliases", e);
+        }
+    }
+    
+	public PolicyDefinition[] getPolicyDefinitions() {
+		List<PolicyDefinition> policyDefinitions = PolicyHolder.getInstance().getPolicyDefinitions();
+		return policyDefinitions == null || policyDefinitions.isEmpty() ? new PolicyDefinition[0] : policyDefinitions
+				.toArray(new PolicyDefinition[policyDefinitions.size()]);
+	}
+
+	/**
+	 * Subscribe to a cartridge
+	 */
+	public SubscriptionInfo subscribe(String cartridgeType, String alias, String policy, String repoURL,
+			boolean privateRepo, String repoUsername, String repoPassword, String dataCartridgeType,
+			String dataCartridgeAlias) throws ADCException, PolicyException, UnregisteredCartridgeException,
+            InvalidCartridgeAliasException, DuplicateCartridgeAliasException, RepositoryRequiredException,
+            AlreadySubscribedException, RepositoryCredentialsRequiredException, InvalidRepositoryException,
+            RepositoryTransportException {
+
+		checkSuperTenant();
+
+		return ApplicationManagementUtil.doSubscribe(cartridgeType, alias, policy, repoURL, privateRepo, repoUsername,
+				repoPassword, dataCartridgeType, dataCartridgeAlias, getUsername(),
+				ApplicationManagementUtil.getTenantId(getConfigContext()), getTenantDomain());
+
+	}
+
+
+    /**
+     * Unsubscribing the cartridge
+     *
+     * @param alias name of the cartridge to be unsubscribed
+     */
+    public void unsubscribe(String alias) throws ADCException, NotSubscribedException {
+    	checkSuperTenant();
+        CartridgeSubscription subscription = null;
+        
+        try {
+			subscription = PersistenceManager.getSubscription(tenantDomain, alias);
+		} catch (Exception e) {
+			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + alias;
+            log.error(msg, e);
+			throw new ADCException(msg, e);
+		}
+
+        if (subscription == null) {
+            String msg = "Tenant " + tenantDomain + " is not subscribed for " + alias;
+            log.error(msg);
+            throw new NotSubscribedException("You have not subscribed for " + alias, alias);
+        }
+        
+        try {
+            String clusterDomain = subscription.getClusterDomain();
+            String clusterSubDomain = subscription.getClusterSubdomain();
+
+            if (log.isDebugEnabled()) {
+                log.debug("Finding cartridge information for " + subscription.getCartridge());
+            }
+            CartridgeInfo cartridgeInfo = ApplicationManagementUtil.getServiceClient().getCartridgeInfo(subscription.getCartridge());
+            if (log.isDebugEnabled()) {
+                log.debug("Found " + cartridgeInfo.getDisplayName() + " for " + subscription.getCartridge());
+            }
+            if (!cartridgeInfo.getMultiTenant()) {
+                log.info("Terminating all instances of " + clusterDomain + " " + clusterSubDomain);
+                ApplicationManagementUtil.getServiceClient().terminateAllInstances(clusterDomain, clusterSubDomain);
+                log.info("All instances terminated.");
+                log.info("Unregistering services...");
+                ApplicationManagementUtil.getServiceClient().unregisterService(clusterDomain, clusterSubDomain);
+                log.info("Successfully terminated instances ..");
+            } else {
+                if (log.isInfoEnabled()) {
+                    log.info("Cartridge "
+                            + subscription.getCartridge()
+                            + " is a multi-tenant cartridge and therefore will not terminate all instances and unregister services");
+                }
+            }
+
+            new RepositoryFactory().destroyRepository(alias, tenantDomain, getUsername());
+            log.info("Repo is destroyed successfully.. ");
+
+            PersistenceManager.updateSubscriptionState(subscription.getSubscriptionId(), "UNSUBSCRIBED");
+            new DNSManager().removeSubDomain(subscription.getHostName());
+            registryManager.removeDomainMappingFromRegistry(subscription.getHostName());
+            TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
+			
+            String[] ips = topologyMgtService.getActiveIPs(subscription.getCartridge(),
+					subscription.getClusterDomain(), subscription.getClusterSubdomain());
+            PersistenceManager.updateInstanceState("INACTIVE", ips, subscription.getClusterDomain(), subscription.getClusterSubdomain(), subscription.getCartridge());
+
+        } catch (ADCException e) {
+        	log.error(e.getMessage(), e);
+        	throw e;
+        } catch (Exception e1) {
+            String msg1 = "Exception occurred :" + e1.getMessage();
+            log.error(msg1);
+            throw new ADCException("Unsubscribe failed for cartridge " + alias, e1);
+        }
+    }
+
+
+    public String addDomainMapping(String mappedDomain, String cartridgeAlias) throws ADCException, DomainMappingExistsException, NotSubscribedException {
+    	checkSuperTenant();
+    	// TODO Following was in CLI. Fix this
+		//		if (domain.indexOf('.') == -1) {
+		//			System.out.println("\nOwn domain should include a '.' ");
+		//		}
+
+        CartridgeSubscription subscription = null;
+        String actualHost = null;
+        
+        try {
+			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
+		} catch (Exception e) {
+			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + cartridgeAlias;
+            log.error(msg, e);
+			throw new ADCException(msg, e);
+		}
+        if (subscription == null) {
+        	String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
+            log.error(msg);
+            throw new NotSubscribedException("You have not subscribed for " + cartridgeAlias, cartridgeAlias);
+        }
+
+        try {
+        	actualHost = getActualHost(cartridgeAlias);
+            registryManager.addDomainMappingToRegistry(mappedDomain, actualHost);
+            log.info("Domain mapping is added for " + mappedDomain + " tenant: " + tenantDomain);
+            PersistenceManager.updateDomainMapping(
+                    ApplicationManagementUtil.getTenantId(getConfigContext()), cartridgeAlias, mappedDomain);
+        } catch (RegistryException e) {
+            String msg = "Unable to add the mapping due to registry transaction error";
+            log.error(msg, e);
+            throw new ADCException("Unable to add the mapping due to internal error!", e);
+        } catch (DomainMappingExistsException e) {
+            String msg = "Domain mapping already exists.";
+            log.error(msg, e);
+            throw e;
+        } catch (Exception e) {
+            String msg = "Error occurred. Reason : " + e.getMessage();
+            log.error(msg, e);
+            throw new ADCException(msg, e);
+        }
+        return actualHost;
+    }
+
+	private String getActualHost(String cartridgeName) throws Exception {
+		return PersistenceManager.getHostNameForCartridgeName(
+				ApplicationManagementUtil.getTenantId(getConfigContext()), cartridgeName);
+	}
+
+    public void removeDomainMapping(String cartridgeAlias) throws ADCException, NotSubscribedException {
+    	checkSuperTenant();
+        CartridgeSubscription subscription = null;
+        String actualHost = null;
+        
+        try {
+			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
+		} catch (Exception e) {
+			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + cartridgeAlias;
+            log.error(msg, e);
+			throw new ADCException(msg, e);
+		}
+        if (subscription == null) {
+        	String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
+            log.error(msg);
+            throw new NotSubscribedException("You have not subscribed for " + cartridgeAlias, cartridgeAlias);
+        }
+        
+        try {
+        	actualHost = getActualHost(cartridgeAlias);
+            registryManager.removeDomainMappingFromRegistry(actualHost);
+            log.info("Domain mapping is removed for " + actualHost + " tenant: " + tenantDomain);
+            PersistenceManager.updateDomainMapping(ApplicationManagementUtil.getTenantId(getConfigContext()),
+                    cartridgeAlias, null);
+        } catch (RegistryException e) {
+            String msg = "Unable to remove the mapping due to registry transaction error";
+            log.error(msg, e);
+            throw new ADCException("Unable to remove the mapping due to internal error!", e);
+        } catch (Exception e) {
+            String msg = "Error occurred. Reason : " + e.getMessage();
+            log.error(msg, e);
+            throw new ADCException(msg, e);
+        }
+    }
+
+	public void synchronizeRepository(String cartridgeAlias) throws ADCException, NotSubscribedException {
+		checkSuperTenant();
+        CartridgeSubscription subscription = null;
+        
+        // Validating subscription
+        try {
+			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
+		} catch (Exception e) {
+			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + cartridgeAlias;
+            log.error(msg, e);
+			throw new ADCException(msg, e);
+		}
+        if (subscription == null) {
+        	String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
+            log.error(msg);
+            throw new NotSubscribedException("You have not subscribed for " + cartridgeAlias, cartridgeAlias);
+        }
+		
+		try {
+			repoNotificationService.notifyRepoUpdate(tenantDomain, cartridgeAlias);
+		} catch (Exception e) {
+			throw new ADCException(e.getMessage() != null ? e.getMessage() : "Failed to synchronize repository", e);
+		}
+	}
+
+    /**
+     * Validate authentication.
+     * First call of cli tool in the prompt mode after log in.
+     *
+     * @return The tenant domain
+     */
+	public String getTenantDomain() {
+		if (tenantDomain != null) {
+			// This means, authentication is successful
+			log.info("Tenant " + tenantDomain + " is authorized to access Application Management Service!");
+		}
+		return tenantDomain;
+	}
+    
+	/**
+	 * Allow to check whether features are enabled in the back-end
+	 * 
+	 * @param key
+	 *            The propery key
+	 * @return {@code true} if feature is enabled
+	 */
+	public boolean isFeatureEnabled(String key) {
+		if (key != null && key.startsWith("feature.")) {
+			return new Boolean(System.getProperty(key));
+		}
+		return false;
+	}
+
+	
+	public RepositoryInformation testRepositoryConnection(String repoURL, String repoUsername, String repoPassword, boolean privateRepo)
+			throws RepositoryRequiredException, ADCException, RepositoryCredentialsRequiredException,
+			InvalidRepositoryException, RepositoryTransportException {
+		return ApplicationManagementUtil.validateRepository(repoURL, repoUsername, repoPassword, privateRepo, true);
+	}
+	
+	// TODO Remove following when we support cartridge subscription for Super-tenant
+	private void checkSuperTenant() throws ADCException {
+		if (log.isDebugEnabled()) {
+			log.debug("Checking whether super tenant accesses the service methods. Tenant ID: "
+					+ ApplicationManagementUtil.getTenantId(getConfigContext()) + ", Tenant Domain: " + carbonContext.getTenantDomain());
+		}
+		if (MultitenantConstants.SUPER_TENANT_ID == ApplicationManagementUtil.getTenantId(getConfigContext())) {
+			throw new ADCException("Super Tenant is not allowed to complete requested operation");
+		}
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/InstanceInformationManagementService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/InstanceInformationManagementService.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/InstanceInformationManagementService.java
new file mode 100644
index 0000000..692dafa
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/InstanceInformationManagementService.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.service;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.utils.PersistenceManager;
+
+public class InstanceInformationManagementService {
+
+	
+    private static final Log log = LogFactory.getLog(InstanceInformationManagementService.class);
+
+    /**
+    * Everytime an instance is started up, this operation is invoked
+    *            (by the AgentService)
+    * @param instanceIp
+    * @param tenantId
+    * @param clusterDomain
+    * @param clusterSubDomain
+    * @param cartridge
+    * @param state
+    *
+    */
+    public void updateInstanceState(String instanceIp,
+                                  int tenantId,
+                                  String clusterDomain,
+                                  String clusterSubDomain,
+                                  String cartridge,
+                                  String state) {
+
+      log.info("Message receieved in Instance Info Service.." + instanceIp + tenantId + clusterDomain + clusterSubDomain
+               + cartridge + state);
+
+      try {
+        PersistenceManager.persistCartridgeInstanceInfo(instanceIp, clusterDomain, clusterSubDomain, cartridge, state);
+    } catch (Exception e) {
+       log.error("Exception is occurred in updating instance state. Reason, " + e.getMessage());
+    }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java
new file mode 100644
index 0000000..b26e885
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepoNotificationService.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.service;
+
+import java.io.File;
+import java.util.List;
+import java.util.UUID;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.dao.CartridgeSubscription;
+import org.apache.stratos.adc.mgt.internal.DataHolder;
+import org.apache.stratos.adc.mgt.utils.CartridgeConstants;
+import org.apache.stratos.adc.mgt.utils.PersistenceManager;
+import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.core.deployment.SynchronizeGitRepositoryRequest;
+import org.wso2.carbon.utils.CarbonUtils;
+
+
+public class RepoNotificationService {
+
+	private static final Log log = LogFactory.getLog(RepoNotificationService.class);
+	
+
+	public void notifyRepoUpdate(String tenantDomain, String cartridgeAlias) throws Exception {
+		// FIXME Throwing generic Exception is wrong
+		log.info("Updating repository of tenant : " + tenantDomain + " , cartridge: " +
+				cartridgeAlias);
+
+		CartridgeSubscription subscription = null;
+		try {
+			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
+		} catch (Exception e) {
+			String msg = "Failed to find subscription for " + cartridgeAlias + ". "
+					+ (e.getMessage() != null ? e.getMessage() : "");
+			log.error(msg, e);
+			throw new Exception(msg, e);
+		}
+		
+		if (subscription == null) {
+			String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
+			log.error(msg);
+			throw new Exception("You have not subscribed for " + cartridgeAlias);
+		}
+		
+		try {
+			handleRepoSynch(subscription);
+		} catch (Exception e) {
+			String msg = "Failed to synchronize the repository for " + cartridgeAlias + ". "
+					+ (e.getMessage() != null ? e.getMessage() : "");
+			log.error(msg, e);
+			throw new Exception(msg, e);
+		}
+		
+	}
+
+	public void synchronize(String repositoryURL) throws Exception {
+
+		log.info(" repository URL received : " + repositoryURL);
+		List<CartridgeSubscription> subscription = PersistenceManager.getSubscription(repositoryURL);
+		for (CartridgeSubscription cartridgeSubscription : subscription) {			
+			handleRepoSynch(cartridgeSubscription);   
+        }
+	}
+
+	private void handleRepoSynch(CartridgeSubscription subscription) throws Exception {
+		if (subscription == null) {
+			throw new Exception("Cannot synchronize repository. subscription is null");
+		}
+
+		if (CartridgeConstants.PROVIDER_NAME_WSO2.equals(subscription.getProvider())) {
+			log.info(" wso2 cartridge.. ");
+			createAndSendClusterMessage(subscription.getTenantId(), subscription.getTenantDomain(),
+			                            UUID.randomUUID(), subscription.getClusterDomain(),
+			                            subscription.getClusterSubdomain());
+			//for manager node
+			           /* if (subscription.getMgtClusterSubDomain() != null && !subscription.getMgtClusterSubDomain().isEmpty()) {
+			                createAndSendClusterMessage(subscription.getTenantId(), subscription.getTenantDomain(),
+			                        UUID.randomUUID(), subscription.getMgtClusterDomain(),
+			                        subscription.getMgtClusterSubDomain());
+			            }
+			            else {
+			                if(log.isDebugEnabled())
+			                    log.debug("Manager node cluster information not found, not sending the SynchronizeGitRepositoryRequest");
+			            }*/
+
+		} else {
+
+			// Query DB and get all the IP s for this tenant 
+			// Invoke update-instance script
+			
+			String appPath = subscription.getBaseDirectory();
+			String cartridgePrivateKey = System.getProperty(CartridgeConstants.CARTRIDGE_KEY);
+			
+			File keyFile = new File(cartridgePrivateKey);
+			if (!keyFile.exists()) {
+				log.error("The key file does not exist! " + cartridgePrivateKey);
+			}
+
+			if (subscription != null) {
+				TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
+
+				
+				if (topologyMgtService == null) {
+					String msg = " Topology Management Service is null ";
+					log.error(msg);
+					throw new Exception(msg);
+				}
+
+				String[] activeIpArray =
+				                         topologyMgtService.getActiveIPs(subscription.getCartridge(),
+				                                                         subscription.getClusterDomain(),
+				                                                         subscription.getClusterSubdomain());
+				try {
+
+					for (String instanceIp : activeIpArray) {
+						String command =
+						                 CarbonUtils.getCarbonHome() + File.separator + "bin" +
+						                         File.separator + "update-instance.sh " +
+						                         instanceIp + " " + appPath + " " +
+						                         cartridgePrivateKey + " /";
+						log.info("Update instance command.... " + command);
+						Process proc = Runtime.getRuntime().exec(command);
+						proc.waitFor();
+					}
+
+				} catch (Exception e) {
+					log.error("Exception is occurred in notify update operation. Reason : " +
+					          e.getMessage());
+					throw e;
+				}
+			}
+		}
+	}
+
+	private void createAndSendClusterMessage(int tenantId, String tenantDomain, UUID uuid,
+	                                         String clusterDomain, String clusterSubdomain) {
+
+		SynchronizeGitRepositoryRequest request =
+		                                          new SynchronizeGitRepositoryRequest(tenantId,
+		                                                                              tenantDomain,
+		                                                                              uuid);
+
+		ClusteringAgent clusteringAgent =
+		                                  DataHolder.getServerConfigContext()
+		                                            .getAxisConfiguration().getClusteringAgent();
+		GroupManagementAgent groupMgtAgent =
+		                                     clusteringAgent.getGroupManagementAgent(clusterDomain,
+		                                                                             clusterSubdomain);
+
+		try {
+			log.info("Sending Request to.. " + clusterDomain + " : " + clusterSubdomain);
+			groupMgtAgent.send(request);
+			
+		} catch (ClusteringFault e) {
+			e.printStackTrace();
+		}
+		 
+
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInfoBean.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInfoBean.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInfoBean.java
new file mode 100644
index 0000000..7a6380c
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInfoBean.java
@@ -0,0 +1,78 @@
+/**
+ * 
+ */
+package org.apache.stratos.adc.mgt.service;
+
+import org.apache.stratos.cloud.controller.util.xsd.CartridgeInfo;
+
+/**
+ * @author wso2
+ *
+ */
+public class RepositoryInfoBean {
+
+	private String repoURL;
+	private String cartridgeAlias;
+	private String tenantDomain;
+	private String userName;
+	private String password;
+	private String[] dirArray;
+	private CartridgeInfo cartridgeInfo;	
+	
+	
+	public RepositoryInfoBean(String repoURL, String cartridgeAlias, String tenantDomain,
+                              String userName, String password, String[] dirArray, CartridgeInfo cartridgeInfo) {
+	    this.repoURL = repoURL;
+	    this.cartridgeAlias = cartridgeAlias;
+	    this.tenantDomain = tenantDomain;
+	    this.userName = userName;
+	    this.setPassword(password);
+	    this.dirArray = dirArray;
+	    this.cartridgeInfo = cartridgeInfo;
+    }
+	public String getRepoURL() {
+    	return repoURL;
+    }
+	public void setRepoURL(String repoURL) {
+    	this.repoURL = repoURL;
+    }
+	public String getCartridgeAlias() {
+    	return cartridgeAlias;
+    }
+	public void setCartridgeAlias(String cartridgeAlias) {
+    	this.cartridgeAlias = cartridgeAlias;
+    }
+	public String getTenantDomain() {
+    	return tenantDomain;
+    }
+	public void setTenantDomain(String tenantDomain) {
+    	this.tenantDomain = tenantDomain;
+    }
+	public String getUserName() {
+    	return userName;
+    }
+	public void setUserName(String userName) {
+    	this.userName = userName;
+    }
+	public String[] getDirArray() {
+    	return dirArray;
+    }
+	public void setDirArray(String[] dirArray) {
+    	this.dirArray = dirArray;
+    }
+	public CartridgeInfo getCartridgeInfo() {
+    	return cartridgeInfo;
+    }
+	public void setCartridgeInfo(CartridgeInfo cartridgeInfo) {
+    	this.cartridgeInfo = cartridgeInfo;
+    }
+    public String getPassword() {
+        return password;
+    }
+    public void setPassword(String password) {
+        this.password = password;
+    }
+	
+	
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInformationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInformationService.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInformationService.java
new file mode 100644
index 0000000..ad7db58
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/service/RepositoryInformationService.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.service;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.dao.RepositoryCredentials;
+import org.apache.stratos.adc.mgt.utils.PersistenceManager;
+
+/**
+ * 
+ * Exposes information related to internally created repositories  
+ * 
+ */
+public class RepositoryInformationService {
+
+	private static final Log log = LogFactory.getLog(RepositoryInformationService.class);
+
+	public String getRepositoryUrl(int tenantId, String cartridgeType) throws Exception {
+
+		String repoUrl = null;
+		try {
+			repoUrl = PersistenceManager.getRepoURL(tenantId, cartridgeType);
+		} catch (Exception e) {
+			String msg = "System Exception is occurred when retriving repo URL";
+			log.error(msg + ". Reason :" + e.getMessage());
+			throw new Exception(msg);
+		}
+		if (repoUrl == null) {
+			log.error("Repository URL is not successfully retrieved " + "for tenant [" + tenantId +
+			          "] and cartridge [" + cartridgeType + "] ");
+		}
+		return repoUrl;
+	}
+
+    public RepositoryCredentials getRepositoryCredentials(int tenantId, String cartridgeType, String alias) throws Exception {
+
+    	RepositoryCredentials repoCredentials = null;
+        try {
+        	repoCredentials = PersistenceManager.getRepoCredentials(tenantId,cartridgeType, alias);
+        } catch (Exception e) {
+            String msg = "System Exception is occurred when retrieving user credentials";
+            log.error(msg + ". Reason :" + e.getMessage());
+            throw new Exception(msg);
+        }
+        if (repoCredentials == null) {
+            log.error("Repository credentials are not successfully retrieved " + "for tenant [" + tenantId +
+                    "] and cartridge [" + cartridgeType + "] ");
+        }
+        return repoCredentials;
+    }
+}


[27/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java
new file mode 100644
index 0000000..a83a5c9
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/ApplicationManagementUtil.java
@@ -0,0 +1,1095 @@
+package org.apache.stratos.adc.mgt.utils;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.rmi.RemoteException;
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import javax.activation.DataHandler;
+import javax.activation.FileDataSource;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.adc.mgt.client.CloudControllerServiceClient;
+import org.apache.stratos.adc.mgt.dao.CartridgeSubscription;
+import org.apache.stratos.adc.mgt.dao.DataCartridge;
+import org.apache.stratos.adc.mgt.dao.PortMapping;
+import org.apache.stratos.adc.mgt.dao.Repository;
+import org.apache.stratos.adc.mgt.dns.DNSManager;
+import org.apache.stratos.adc.mgt.dto.Cartridge;
+import org.apache.stratos.adc.mgt.dto.Policy;
+import org.apache.stratos.adc.mgt.dto.RepositoryInformation;
+import org.apache.stratos.adc.mgt.dto.SubscriptionInfo;
+import org.apache.stratos.adc.mgt.exception.ADCException;
+import org.apache.stratos.adc.mgt.exception.AlreadySubscribedException;
+import org.apache.stratos.adc.mgt.exception.DuplicateCartridgeAliasException;
+import org.apache.stratos.adc.mgt.exception.InvalidCartridgeAliasException;
+import org.apache.stratos.adc.mgt.exception.InvalidRepositoryException;
+import org.apache.stratos.adc.mgt.exception.NotSubscribedException;
+import org.apache.stratos.adc.mgt.exception.PolicyException;
+import org.apache.stratos.adc.mgt.exception.RepositoryCredentialsRequiredException;
+import org.apache.stratos.adc.mgt.exception.RepositoryRequiredException;
+import org.apache.stratos.adc.mgt.exception.RepositoryTransportException;
+import org.apache.stratos.adc.mgt.exception.UnregisteredCartridgeException;
+import org.apache.stratos.adc.mgt.internal.DataHolder;
+import org.apache.stratos.adc.mgt.service.RepositoryInfoBean;
+import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.api.LsRemoteCommand;
+import org.eclipse.jgit.api.errors.GitAPIException;
+import org.eclipse.jgit.api.errors.InvalidRemoteException;
+import org.eclipse.jgit.api.errors.TransportException;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.storage.file.FileRepository;
+import org.eclipse.jgit.transport.CredentialsProvider;
+import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
+import org.apache.stratos.adc.topology.mgt.service.TopologyManagementService;
+import org.apache.stratos.adc.topology.mgt.serviceobjects.DomainContext;
+import org.apache.stratos.cloud.controller.stub.CloudControllerServiceUnregisteredCartridgeExceptionException;
+import org.apache.stratos.cloud.controller.util.xsd.CartridgeInfo;
+import org.apache.stratos.cloud.controller.util.xsd.Properties;
+import org.apache.stratos.cloud.controller.util.xsd.Property;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+import com.google.gson.Gson;
+
+/**
+ * This class contains utility methods used by ApplicationManagementService.
+ */
+public class ApplicationManagementUtil {
+
+    private static Log log = LogFactory.getLog(ApplicationManagementUtil.class);
+    private static volatile CloudControllerServiceClient serviceClient;
+
+    /**
+     * Method used to subscribe to cartridges.
+     */
+	public static SubscriptionInfo doSubscribe(String cartridgeType, String alias, String policy, String repoURL,
+			boolean privateRepo, String repoUsername, String repoPassword, String dataCartridgeType,
+			String dataCartridgeAlias, String username, int tenantId, String tenantDomain) throws ADCException,
+            PolicyException, UnregisteredCartridgeException, InvalidCartridgeAliasException,
+            DuplicateCartridgeAliasException, RepositoryRequiredException, AlreadySubscribedException,
+            RepositoryCredentialsRequiredException, InvalidRepositoryException, RepositoryTransportException {
+
+		String clusterDomain = "";
+        String clusterSubDomain = CartridgeConstants.DEFAULT_SUBDOMAIN;
+        String mgtClusterDomain = "";
+        String mgtClusterSubDomain = CartridgeConstants.DEFAULT_MGT_SUBDOMAIN;
+        CartridgeSubscription subscription = null;
+        String mysqlPassword = null;
+        Repository repository = null;
+        DataCartridge dataCartridge = null;
+        String cartName = (alias != null && alias.trim().length() > 0) ? alias : cartridgeType;
+        String payloadZipFileName = "/tmp/" + UUID.randomUUID().toString() + ".zip";
+
+		log.info("Subscribing tenant [" + tenantId + "] with username [" + username + "] Cartridge Alias " + alias
+				+ ", Cartridge Type: " + cartridgeType + ", Repo URL: " + repoURL + ", Policy: " + policy);
+		
+		// Assign auto scaling only when necessary.
+		// Muti-tenant cartridge may not need a policy.
+		Policy autoScalingPolicy = null;
+		
+		CartridgeInfo cartridgeInfo;
+		try {
+			cartridgeInfo = getServiceClient().getCartridgeInfo(cartridgeType);
+		} catch (UnregisteredCartridgeException e) {
+			String message = cartridgeType
+					+ " is not a valid cartridge type. Please try again with a valid cartridge type.";
+			log.error(message);
+			throw e;
+		} catch (Exception e) {
+			String message = "Error getting info for " + cartridgeType;
+			log.error(message, e);
+			throw new ADCException(message, e);
+		}
+
+		validateCartridgeAlias(cartName, cartridgeType);
+		
+
+        if (cartridgeType.equals(CartridgeConstants.MYSQL_CARTRIDGE_NAME)) {
+        	
+        	autoScalingPolicy = PolicyHolder.getInstance().getDefaultPolicy();
+        	
+        	if (autoScalingPolicy == null) {
+        		throw new PolicyException("Could not load default auto-scaling policy.");
+        	}
+        	if (log.isDebugEnabled()) {
+    			log.debug("Selected Policy: " + new Gson().toJson(autoScalingPolicy));
+    		}
+        	
+            dataCartridge = new DataCartridge();
+            mysqlPassword = generatePassword();
+            dataCartridge.setPassword(mysqlPassword);
+            dataCartridge.setDataCartridgeType(cartridgeType);
+            dataCartridge.setUserName(CartridgeConstants.MYSQL_DEFAULT_USER);
+            clusterDomain = getDynamicClusterDomain(cartridgeType, cartName, cartridgeInfo);
+
+            registerService(cartridgeType,
+                    clusterDomain,
+                    clusterSubDomain,
+                    createPayload(cartridgeInfo, cartName, autoScalingPolicy, repoURL, mysqlPassword, "localhost", payloadZipFileName, tenantId, tenantDomain),
+                    "*",
+                    cartName + "." + cartridgeInfo.getHostName(),
+                    setRegisterServiceProperties(autoScalingPolicy, tenantId,cartName));
+            deletePayloadFile(payloadZipFileName);
+        } else {
+        	
+			if (!new Boolean(System.getProperty(CartridgeConstants.FEATURE_INTERNAL_REPO_ENABLED))) {
+				if (log.isDebugEnabled()) {
+					log.debug("Internal repo feature is not enabled.");
+				}
+
+				if (repoURL == null || repoURL.trim().length() == 0) {
+					throw new RepositoryRequiredException("External repository required for subscription");
+				}
+			}
+
+			if (repoURL != null && repoURL.trim().length() > 0) {
+				if (log.isDebugEnabled()) {
+					log.debug("Repo URL entered: " + repoURL);
+				}
+				// Validate Remote Repository.
+				validateRepository(repoURL, repoUsername, repoPassword, privateRepo,
+						new Boolean(System.getProperty(CartridgeConstants.FEATURE_EXTERNAL_REPO_VAIDATION_ENABLED)));
+			}
+
+            try {
+                repository = manageRepository(repoURL, repoUsername, repoPassword, cartName, cartridgeInfo, username,
+                        tenantDomain);
+            } catch (Exception e) {
+                log.error(e.getMessage());
+                throw new ADCException(e);
+            }
+        	
+            // TODO: Check logic here
+            if (!cartridgeInfo.getMultiTenant()) {
+            	
+        		if (policy != null && policy.trim().length() > 0) {
+        			autoScalingPolicy = PolicyHolder.getInstance().getPolicy(policy);
+        		} else {
+        			autoScalingPolicy = PolicyHolder.getInstance().getDefaultPolicy();
+        		}
+        		if (autoScalingPolicy == null) {
+        			throw new PolicyException("Could not load auto-scaling policy.");
+        		}
+        		if (log.isDebugEnabled()) {
+        			log.debug("Selected Policy: " + new Gson().toJson(autoScalingPolicy));
+        		}
+
+                if (cartridgeInfo.getProvider().equalsIgnoreCase(CartridgeConstants.PROVIDER_NAME_WSO2)) { //carbon cartridge private jet mode
+
+                    clusterDomain = getDynamicClusterDomain(cartridgeType, cartName, cartridgeInfo);
+                    registerService(cartridgeType,
+                            clusterDomain,
+                            clusterSubDomain,
+                            createCarbonPayload(cartridgeInfo, cartName, alias, payloadZipFileName, tenantDomain, false),
+                            Integer.toString(tenantId),
+                            cartName + "." + cartridgeInfo.getHostName(),
+                            setRegisterServiceProperties(autoScalingPolicy,tenantId,cartName));
+                    deletePayloadFile(payloadZipFileName);
+
+                } else {
+                    clusterDomain = getDynamicClusterDomain(cartridgeType, cartName, cartridgeInfo);
+
+                    String mySQLPassword = null;
+                    String mySQLHostName = null;
+
+                    if (dataCartridgeType != null && dataCartridgeType.trim().length() > 0 && dataCartridgeAlias != null
+                            && dataCartridgeAlias.trim().length() > 0) {
+                        if (log.isInfoEnabled()) {
+                            log.info("Retrieving Data Cartridge info for connect ... Alias : " + dataCartridgeAlias
+                                    + ", Type: " + dataCartridgeType);
+                        }
+
+                        //TODO: Optimize following logic. Same logic is used in MySQLPasswordConfigurer
+                        int maxAttempts = Integer.parseInt(System.getProperty(CartridgeConstants.MAX_ATTEMPTS, "50"));
+                        int i = 0;
+
+                        while (i < maxAttempts) {
+                            i++;
+                            Cartridge c = null;
+                            try {
+                                c = getCartridgeInfo(dataCartridgeAlias, tenantDomain);
+                            } catch (NotSubscribedException e) {
+                                // This cannot happen here.
+                            }
+                            if (c != null) {
+                                if (!c.getStatus().equals("ACTIVE")) {
+                                    try {
+                                        Thread.sleep(3000);
+                                    } catch (InterruptedException ignore) {
+                                    }
+                                } else {
+                                    mySQLPassword = c.getPassword();
+                                    mySQLHostName = c.getIp();
+                                    break;
+                                }
+                            }
+                        }
+                        log.info(" MYSQL Cartridge info retrieved ");
+                    }
+
+                    registerService(cartridgeType,
+                            clusterDomain,
+                            clusterSubDomain,
+                            createPayload(cartridgeInfo, cartName, autoScalingPolicy, repoURL, mySQLPassword,
+                                    mySQLHostName, payloadZipFileName, tenantId, tenantDomain), "*",
+                            cartName + "." + cartridgeInfo.getHostName(),
+                            setRegisterServiceProperties(autoScalingPolicy,tenantId,cartName));
+                    deletePayloadFile(payloadZipFileName);
+                }
+
+            } else {
+            	
+            	boolean allowMultipleSubscription = new Boolean(
+						System.getProperty(CartridgeConstants.FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED));
+
+				if (!allowMultipleSubscription) {
+					// If the cartridge is multi-tenant. We should not let users
+					// subscribe twice.
+					boolean subscribed;
+					try {
+						subscribed = PersistenceManager.isAlreadySubscribed(cartridgeType, tenantId);
+					} catch (Exception e) {
+						String msg = "Error checking whether the cartridge type " + cartridgeType
+								+ " is already subscribed";
+						log.error(msg, e);
+						throw new ADCException(msg, e);
+					}
+					
+					if (subscribed) {
+						String msg = "Already subscribed to " + cartridgeType
+								+ ". This multi-tenant cartridge will not be available to subscribe";
+						if (log.isDebugEnabled()) {
+							log.debug(msg);
+						}
+						throw new AlreadySubscribedException(msg, cartridgeType);
+					}
+				}
+
+                TopologyManagementService topologyService = DataHolder.getTopologyMgtService();
+                DomainContext[] domainContexts = topologyService.getDomainsAndSubdomains(cartridgeType, tenantId);
+                log.info("Retrieved " + domainContexts.length + " domain and corresponding subdomain pairs");
+
+                if (domainContexts.length > 0) {
+                	                        if(domainContexts.length > 2) {
+                	                            if(log.isDebugEnabled())
+                	                                log.debug("Too many domain sub domain pairs");
+                	                       }
+                	
+                	                        for (int i = 0 ; i < domainContexts.length ; i++) {
+                	                            if(domainContexts[i].getSubDomain().equalsIgnoreCase("mgt")) {
+                	                                mgtClusterDomain = domainContexts[i].getDomain();
+                	                                mgtClusterSubDomain = domainContexts[i].getSubDomain();
+                	                            }
+                	                          else
+                	                          {
+                	                              clusterDomain = domainContexts[i].getDomain();
+                	                              clusterSubDomain = domainContexts[i].getSubDomain();
+                	                          }
+                	                      }
+                } else {
+                	String msg = "Domain contexts not found for " + cartridgeType + " and tenant id " + tenantId;
+                    log.warn(msg);
+                    throw new ADCException(msg);
+                }
+            }
+        }
+
+        subscription =
+                createCartridgeSubscription(cartridgeInfo, autoScalingPolicy,
+                        cartridgeType, cartName, tenantId, tenantDomain,
+                        repository, clusterDomain, clusterSubDomain,
+                        mgtClusterDomain, mgtClusterSubDomain, dataCartridge);
+
+        try {
+			PersistenceManager.persistSubscription(subscription);
+		} catch (Exception e) {
+			throw new ADCException("Error Saving Subscription", e);
+		}
+        addDNSEntry(alias, cartridgeType);
+        return createSubscriptionResponse(subscription, repository);
+
+    }
+    
+    private static File getPayload(CartridgeInfo cartridgeInfo, String cartridgeName, Policy policy, String repoURL,
+                                   String mySQLPassword, String mySQLHost, String payloadZipFileName,
+                                   int tenantId, String tenantDomain) throws Exception {
+        String payloadString = "";
+
+        payloadString += "TENANT_RANGE=" + "*";
+        payloadString += ",TENANT_ID=" + tenantId;
+        payloadString +=
+            ",REPO_INFO_EPR=" +
+                    System.getProperty(CartridgeConstants.REPO_INFO_EPR);
+        payloadString +=
+                ",CARTRIDGE_AGENT_EPR=" +
+                        System.getProperty(CartridgeConstants.CARTRIDGE_AGENT_EPR);
+        payloadString += createPortMappingPayloadString(cartridgeInfo);
+        payloadString += ",HOST_NAME=" + cartridgeName + "." + cartridgeInfo.getHostName();
+        payloadString += ",MIN=" + policy.getMinAppInstances();
+        payloadString += ",MAX=" + policy.getMaxAppInstances();
+        payloadString += ",SERVICE=" + cartridgeInfo.getType();
+        payloadString += ",TENANT_CONTEXT=" + tenantDomain;
+        payloadString += ",CARTRIDGE_ALIAS=" + cartridgeName;
+
+        String gitRepoURL = null;
+        if (repoURL != null) {
+            gitRepoURL = repoURL;
+        } else {
+            gitRepoURL = "git@" + System.getProperty(CartridgeConstants.GIT_HOST_IP) + ":" + tenantDomain
+                    + System.getProperty("file.separator") + cartridgeName + ".git";
+        }
+        payloadString += ",GIT_REPO=" + gitRepoURL;
+        payloadString += ",APP_PATH=" + cartridgeInfo.getBaseDir();
+        payloadString += ",BAM_IP=" + System.getProperty(CartridgeConstants.BAM_IP);
+        payloadString += ",BAM_PORT=" + System.getProperty(CartridgeConstants.BAM_PORT);
+
+        // MYSQL params
+        payloadString += ",MYSQL_HOST=" + mySQLHost;
+        payloadString += ",MYSQL_USER=" + "root";
+        payloadString += ",MYSQL_PASSWORD=" + mySQLPassword;
+        
+        DecimalFormat df = new DecimalFormat("##.##");
+        df.setParseBigDecimal(true);
+
+        // Autoscaling params
+        payloadString += ",ALARMING_LOWER_RATE=" + df.format(policy.getAlarmingLowerRate());
+        payloadString += ",ALARMING_UPPER_RATE=" + df.format(policy.getAlarmingUpperRate());
+        payloadString += ",MAX_REQUESTS_PER_SEC=" + policy.getMaxRequestsPerSecond();
+        payloadString += ",ROUNDS_TO_AVERAGE=" + policy.getRoundsToAverage();
+        payloadString += ",SCALE_DOWN_FACTOR=" + df.format(policy.getScaleDownFactor());
+
+        log.info("** Payload ** " + payloadString);
+        
+        String payloadStringTempFile = "launch-params";
+
+        FileWriter fstream = new FileWriter(payloadStringTempFile);
+        BufferedWriter out = new BufferedWriter(fstream);
+        out.write(payloadString);
+        out.close();
+
+        FileOutputStream fos = new FileOutputStream(payloadZipFileName);
+        ZipOutputStream zos = new ZipOutputStream(fos);
+
+		addToZipFile(System.getProperty("user.dir"), payloadStringTempFile, zos);
+
+		File folder = new File(CarbonUtils.getCarbonHome()+
+				File.separator + "repository"
+				+ File.separator + "resources" + File.separator + "user-data");
+		for (File fileEntry : folder.listFiles()) {
+			if (!fileEntry.isDirectory()) {
+				addToZipFile(folder.getPath(), fileEntry.getName(), zos);
+			}
+		}
+
+        zos.close();
+        fos.close();
+
+        return new File(payloadZipFileName);
+    }
+
+    private static File getCarbonPayload (CartridgeInfo cartridgeInfo, String cartridgeName, String cartridgeAlias,
+                                          String payloadZipFileName, String tenantDomain, boolean isMultitenant) throws Exception {
+
+        String payloadString = "";
+        payloadString += "DEPLOYMENT=" + "default";  //TODO: Currently hard coded but can be either manager, worker or default.
+        //payloadString += ",DOMAIN=" + "s2.wso2.com";
+        payloadString += ",SERVICE=" + cartridgeInfo.getType();
+        //payloadString += ",TENANT_ID=" + tenantId;
+        payloadString += ",SC_IP=" + System.getProperty(CartridgeConstants.SC_IP);
+        payloadString += ",CARTRIDGE_ALIAS=" + cartridgeAlias;
+        payloadString += ",MULTITENANT=" + "false";
+
+        if(isMultitenant) { //not used at the moment
+            payloadString += ",DOMAIN=" + "wso2." + cartridgeInfo.getType() + ".domain";
+            payloadString += ",HOSTNAME=" + cartridgeInfo.getType() + ".s2.wso2.com";
+
+        } else {
+            payloadString += ",DOMAIN=" + cartridgeName + "." + cartridgeInfo.getHostName() + "." + cartridgeInfo.getType() +
+                    ".domain";
+            payloadString += ",HOSTNAME=" + cartridgeName + "." + cartridgeInfo.getHostName();
+        }
+
+        log.info("** Payload ** " + payloadString);
+
+        String payloadStringTempFile = "launch-params";
+
+        FileWriter fstream = new FileWriter(payloadStringTempFile);
+        BufferedWriter out = new BufferedWriter(fstream);
+        out.write(payloadString);
+        out.close();
+
+        FileOutputStream fos = new FileOutputStream(payloadZipFileName);
+        ZipOutputStream zos = new ZipOutputStream(fos);
+
+        addToZipFile(System.getProperty("user.dir"), payloadStringTempFile, zos);
+
+        zos.close();
+        fos.close();
+
+        return new File(payloadZipFileName);
+    }
+
+    private static String createPortMappingPayloadString(CartridgeInfo cartridgeInfo) {
+        // port mappings
+        StringBuilder portMapBuilder = new StringBuilder();
+        org.apache.stratos.cloud.controller.util.xsd.PortMapping[] portMappings = cartridgeInfo.getPortMappings();
+        for (org.apache.stratos.cloud.controller.util.xsd.PortMapping portMapping : portMappings) {
+            String port = portMapping.getPort();
+            String protocol = portMapping.getProtocol();
+            String proxyPort = portMapping.getProxyPort();
+            portMapBuilder.append(protocol).append(":").append(port).append(":").append(proxyPort).append("|");
+        }
+
+        // remove last "|" character
+        String portMappingString = portMapBuilder.toString();
+        String portMappingPayloadString = null;
+        if (portMappingString.charAt(portMappingString.length() - 1) == '|') {
+            portMappingPayloadString = portMappingString.substring(0, portMappingString.length() - 1);
+        } else {
+            portMappingPayloadString = portMappingString;
+        }
+
+        return ",PORTS=" + portMappingPayloadString;
+    }
+
+    private static void addToZipFile(String dir, String fileName, ZipOutputStream zos) throws FileNotFoundException,
+            IOException {
+
+        log.info("Writing '" + fileName + "' to zip file");
+
+        File file = new File(dir+File.separator+fileName);
+        FileInputStream fis = new FileInputStream(file);
+        ZipEntry zipEntry = new ZipEntry(fileName);
+        zos.putNextEntry(zipEntry);
+
+        byte[] bytes = new byte[1024];
+        int length;
+        while ((length = fis.read(bytes)) >= 0) {
+            zos.write(bytes, 0, length);
+        }
+
+        zos.closeEntry();
+        fis.close();
+    }
+
+    private static DataHandler createPayload(CartridgeInfo cartridgeInfo, String cartridgeName, Policy policy, String repoURL, String mySQLPwd, String mySQLHost,
+                                             String payloadZipFileName, int tenantId,
+                                             String tenantDomain)
+            throws ADCException {
+
+        FileDataSource dataSource = null;
+        File payloadFile = null;
+        try {
+            payloadFile = getPayload(cartridgeInfo, cartridgeName,
+            		policy, repoURL,
+                    mySQLPwd, mySQLHost, payloadZipFileName, tenantId, tenantDomain);
+            dataSource = new FileDataSource(payloadFile);
+        } catch (Exception e) {
+            String msg = "Exception : " + e.getMessage();
+            log.error(msg, e);
+            throw new ADCException("Subscribe failed ", e);
+        }
+        return new DataHandler(dataSource);
+    }
+
+    private static DataHandler createCarbonPayload (CartridgeInfo cartridgeInfo, String cartridgeName, String cartridgeAlias, String payloadZipFileName,
+                                                    String tenantDomain, boolean isMultitenant) throws ADCException {
+
+        FileDataSource dataSource = null;
+        File payloadFile = null;
+        try {
+            payloadFile = getCarbonPayload(cartridgeInfo, cartridgeName, cartridgeAlias, payloadZipFileName,
+                    tenantDomain, isMultitenant);
+            dataSource = new FileDataSource(payloadFile);
+
+        } catch (Exception e) {
+            String msg = "Exception : " + e.getMessage();
+            log.error(msg, e);
+            throw new ADCException("Subscribe failed ", e);
+        }
+
+        return new DataHandler(dataSource);
+    }
+
+    protected static String getAppDeploymentDirPath(String cartridge, AxisConfiguration axisConfig) {
+        return axisConfig.getRepository().getPath() + File.separator + cartridge;
+    }
+
+    private static CartridgeSubscription createCartridgeSubscription(CartridgeInfo cartridgeInfo,
+                                                                     Policy policy,
+                                                                     String cartridgeType,
+                                                                     String cartridgeName,
+                                                                     int tenantId,
+                                                                     String tenantDomain,
+                                                                     Repository repository,
+                                                                     String clusterDomain,
+                                                                     String clusterSubDomain,
+                                                                     String mgtClusterDomain,
+                                                                     String mgtClusterSubDomain,
+                                                                     DataCartridge dataCartridge) {
+
+        CartridgeSubscription cartridgeSubscription = new CartridgeSubscription();
+        cartridgeSubscription.setCartridge(cartridgeType);
+        cartridgeSubscription.setAlias(cartridgeName);
+        cartridgeSubscription.setClusterDomain(clusterDomain);
+        cartridgeSubscription.setClusterSubdomain(clusterSubDomain);
+               cartridgeSubscription.setMgtClusterDomain(mgtClusterDomain);
+                cartridgeSubscription.setMgtClusterSubDomain(mgtClusterSubDomain);
+        String hostName = null;
+        if (cartridgeInfo.getMultiTenant()) {
+            hostName = cartridgeInfo.getHostName();
+        } else {
+            hostName = cartridgeName + "." + cartridgeInfo.getHostName();
+        }
+        cartridgeSubscription.setHostName(hostName);
+        if (policy != null) {
+        	// Policy can be null for multi-tenant cartridge
+        	cartridgeSubscription.setPolicy(policy.getName());
+        }
+        cartridgeSubscription.setRepository(repository);
+        cartridgeSubscription.setPortMappings(createPortMappings(cartridgeInfo));
+        cartridgeSubscription.setProvider(cartridgeInfo.getProvider());
+        cartridgeSubscription.setDataCartridge(dataCartridge);
+        cartridgeSubscription.setTenantId(tenantId);
+        cartridgeSubscription.setTenantDomain(tenantDomain);
+        cartridgeSubscription.setBaseDirectory(cartridgeInfo.getBaseDir());
+        cartridgeSubscription.setState("PENDING");
+        return cartridgeSubscription;
+    }
+
+
+    private static List<PortMapping> createPortMappings(CartridgeInfo cartridgeInfo) {
+        List<PortMapping> portMappings = new ArrayList<PortMapping>();
+
+        if (cartridgeInfo.getPortMappings() != null) {
+            for (org.apache.stratos.cloud.controller.util.xsd.PortMapping portMapping : cartridgeInfo.getPortMappings()) {
+                PortMapping portMap = new PortMapping();
+                portMap.setPrimaryPort(portMapping.getPort());
+                portMap.setProxyPort(portMapping.getProxyPort());
+                portMap.setType(portMapping.getProtocol());
+                portMappings.add(portMap);
+            }
+        }
+        return portMappings;
+    }
+
+    public static CloudControllerServiceClient getServiceClient() throws AxisFault {
+        if (serviceClient == null) {
+            synchronized (CloudControllerServiceClient.class) {
+                if (serviceClient == null) {
+                    serviceClient = new CloudControllerServiceClient(
+                            System.getProperty(CartridgeConstants.AUTOSCALER_SERVICE_URL));
+                }
+            }
+        }
+        return serviceClient;
+    }
+
+    public static int getTenantId(ConfigurationContext configurationContext) {
+        int tenantId = MultitenantUtils.getTenantId(configurationContext);
+        if(log.isDebugEnabled()) {
+            log.debug("Returning tenant ID : " + tenantId);
+        }
+        return tenantId;
+    }
+
+	private static void validateCartridgeAlias(String alias, String cartridgeType) throws InvalidCartridgeAliasException, DuplicateCartridgeAliasException, ADCException {
+		// Do not use quotes in messages, current UI JavaScript does not work if there are quotes
+		// TODO: Fix message display in UI
+		String patternString = "([a-z0-9]+([-][a-z0-9])*)+";
+        Pattern pattern = Pattern.compile(patternString);
+        
+        if (!pattern.matcher(alias).matches()) {
+        	String msg = "The alias " + alias + " can contain only alpha-numeric lowercase characters. Please enter a valid alias.";
+			log.error(msg);
+			throw new InvalidCartridgeAliasException(msg, cartridgeType, alias);
+        }
+		
+		boolean isAliasTaken = false;
+		try {			
+			isAliasTaken = PersistenceManager.isAliasAlreadyTaken(alias, cartridgeType);			
+		} catch (Exception e) {
+			String msg = "Exception : " + e.getMessage();
+			log.error(msg, e);
+			throw new ADCException("Error when checking alias is already taken", e);
+		}
+		
+		if (isAliasTaken) {
+			String msg = "The alias " + alias + " is already taken. Please try again with a different alias.";
+			log.error(msg);
+			throw new DuplicateCartridgeAliasException(msg, cartridgeType, alias);
+		}
+	}
+	
+	public static RepositoryInformation validateRepository(String repoURL, String repoUsername, String repoPassword,
+			boolean privateRepo, boolean testConnection) throws RepositoryRequiredException, ADCException,
+			RepositoryCredentialsRequiredException, InvalidRepositoryException, RepositoryTransportException {
+		RepositoryInformation repositoryInformation = new RepositoryInformation();
+		repositoryInformation.setRepoURL(repoURL);
+		if (log.isDebugEnabled()) {
+			log.debug("Validating Git Repository");
+		}
+
+		if (repoURL != null && repoURL.trim().length() > 0 && privateRepo) {
+			if (log.isDebugEnabled()) {
+				log.debug("External repo validation is a private repo: " + repoURL);
+			}
+			if (repoUsername == null || repoUsername.trim().length() == 0 || repoPassword == null
+					|| repoPassword.trim().length() == 0) {
+				throw new RepositoryCredentialsRequiredException(
+						"Username and Password are required for private repository");
+			}
+		}
+
+		if (!testConnection) {
+			if (log.isDebugEnabled()) {
+				log.debug("External repo validation is not enabled");
+			}
+			return repositoryInformation;
+		}
+
+		if (repoURL == null || repoURL.trim().length() == 0) {
+			// This means, no repo to validate.
+			return repositoryInformation;
+		}
+		
+		if (log.isDebugEnabled()) {
+			log.debug("External repo validation enabled");
+		}
+
+		// This assumes running on Linux.
+		String parentDirName = "/tmp/" + UUID.randomUUID().toString();
+		CredentialsProvider credentialsProvider = null;
+		if (repoUsername != null && repoUsername.trim().length() > 0 && repoPassword != null
+				&& repoPassword.trim().length() > 0) {
+			if (log.isDebugEnabled()) {
+				log.debug("External repo credentails are passed: " + repoUsername);
+			}
+			credentialsProvider = new UsernamePasswordCredentialsProvider(repoUsername, repoPassword.toCharArray());
+		}
+
+		// Initialize temp local file repo
+		FileRepository localRepo = null;
+		try {
+			File f = new File(parentDirName + "/.git");
+			localRepo = new FileRepository(f);
+			if (log.isDebugEnabled()) {
+				log.debug("Local File Repo: " + f.getAbsoluteFile());
+			}
+		} catch (IOException e) {
+			throw new ADCException("Error creating local file repo", e);
+		}
+
+		Git git = new Git(localRepo);
+		LsRemoteCommand cmd = git.lsRemote().setRemote(repoURL);
+		if (credentialsProvider != null) {
+			cmd.setCredentialsProvider(credentialsProvider);
+		}
+		try {
+			Collection<Ref> collection = cmd.call();
+			List<String> refNames = new ArrayList<String>();
+			if (collection != null) {
+				for (Ref ref : collection) {
+					if (log.isDebugEnabled()) {
+						log.debug(repoURL + ": " + ref.getName());
+					}
+					refNames.add(ref.getName());
+				}
+			}
+			repositoryInformation.setRefName(refNames.toArray(new String[refNames.size()]));
+		} catch (InvalidRemoteException e) {
+			throw new InvalidRepositoryException("Provided repository url is not valid", e);
+		} catch (TransportException e) {
+			throw new RepositoryTransportException("Transport error when checking remote repository", e);
+		} catch (GitAPIException e) {
+			throw new ADCException("Git API error when checking remote repository", e);
+		}
+		return repositoryInformation;
+	}
+
+    private static String generatePassword() {
+
+        final int PASSWORD_LENGTH = 8;
+        StringBuffer sb = new StringBuffer();
+        for (int x = 0; x < PASSWORD_LENGTH; x++) {
+            sb.append((char) ((int) (Math.random() * 26) + 97));
+        }
+        return sb.toString();
+
+    }
+
+    private static void deletePayloadFile(String payloadZipFileName) {
+        File payloadFile = new File(payloadZipFileName);
+        payloadFile.delete();
+        log.info(" Payload file is deleted. ");
+    }
+
+    private static Properties setRegisterServiceProperties(Policy policy, int tenantId, String alias) {
+    	
+    	DecimalFormat df = new DecimalFormat("##.##");
+        df.setParseBigDecimal(true);
+
+        Properties properties = new Properties();
+        List<Property> allProperties = new ArrayList<Property>();
+        // min_app_instances
+        Property property = new Property();
+        property.setName("min_app_instances");
+        property.setValue(df.format(policy.getMinAppInstances()));
+        allProperties.add(property);
+        
+        
+     // max_app_instances
+        property = new Property();
+        property.setName("max_app_instances");
+        property.setValue(df.format(policy.getMaxAppInstances()));
+        allProperties.add(property);
+        
+        // max_requests_per_second
+        property = new Property();
+        property.setName("max_requests_per_second");
+        property.setValue(df.format(policy.getMaxRequestsPerSecond()));
+        allProperties.add(property);
+        
+        // alarming_upper_rate
+        property = new Property();
+        property.setName("alarming_upper_rate");
+        property.setValue(df.format(policy.getAlarmingUpperRate()));
+        allProperties.add(property);
+        
+     // alarming_lower_rate
+        property = new Property();
+        property.setName("alarming_lower_rate");
+        property.setValue(df.format(policy.getAlarmingLowerRate()));
+        allProperties.add(property);
+        
+        // scale_down_factor
+        property = new Property();
+        property.setName("scale_down_factor");
+        property.setValue(df.format(policy.getScaleDownFactor()));
+        allProperties.add(property);
+        
+     // rounds_to_average
+        property = new Property();
+        property.setName("rounds_to_average");
+        property.setValue(df.format(policy.getRoundsToAverage()));
+        allProperties.add(property);
+        
+       // tenant id
+        property = new Property();
+        property.setName("tenant_id");
+        property.setValue(String.valueOf(tenantId));
+        allProperties.add(property);
+        
+        // alias
+        property = new Property();
+        property.setName("alias");
+        property.setValue(String.valueOf(alias));
+        allProperties.add(property);
+        
+        properties.setProperties(allProperties.toArray(new Property[allProperties.size()]));
+        return properties;
+    }
+
+    private static String convertRepoURL(String gitURL) {
+        String convertedHttpURL = null;
+        if (gitURL != null && gitURL.startsWith("git@")) {
+            StringBuilder httpRepoUrl = new StringBuilder();
+            httpRepoUrl.append("http://");
+            String[] urls = gitURL.split(":");
+            String[] hostNameArray = urls[0].split("@");
+            String hostName = hostNameArray[1];
+            httpRepoUrl.append(hostName).append("/").append(urls[1]);
+            convertedHttpURL = httpRepoUrl.toString();
+        } else if (gitURL != null && gitURL.startsWith("http")) {
+            convertedHttpURL = gitURL;
+        }
+        return convertedHttpURL;
+    }
+
+    private static void addDNSEntry(String alias, String cartridgeType) {
+        new DNSManager().addNewSubDomain(alias + "." + cartridgeType, System.getProperty(CartridgeConstants.ELB_IP));
+    }
+
+    private static SubscriptionInfo createSubscriptionResponse(CartridgeSubscription cartridgeSubscription, Repository repository) {
+    	SubscriptionInfo subscriptionInfo = new SubscriptionInfo();
+    	
+        if (repository != null && repository.getRepoName() != null) {
+        	subscriptionInfo.setRepositoryURL(convertRepoURL(repository.getRepoName()));
+        }
+        
+        subscriptionInfo.setHostname(cartridgeSubscription.getHostName());
+        
+        return subscriptionInfo;
+    }
+
+    private static String getDynamicClusterDomain(String cartridgeType, String cartName,
+                                                  CartridgeInfo cartridgeInfo) {
+        return cartName + "." + cartridgeInfo.getHostName() + "." + cartridgeType +
+                ".domain";
+    }
+
+    private static Repository manageRepository(String repoURL, String repoUserName, String repoUserPassword,
+                                               String cartName, CartridgeInfo cartridgeInfo, String username,
+                                               String tenantDomain)
+            throws Exception {
+
+        Repository repository = new Repository();
+        if (repoURL != null && repoURL.trim().length() > 0) {
+            log.info("External REPO URL is provided as [" + repoURL +
+                    "]. Therefore not creating a new repo.");
+            //repository.setRepoName(repoURL.substring(0, repoURL.length()-4)); // remove .git part
+            repository.setRepoName(repoURL);
+            repository.setRepoUserName(repoUserName);
+            repository.setRepoUserPassword(repoUserPassword);
+        } else {
+
+            //log.info("External REPO URL is not provided. Therefore creating a new repo. Adding to Executor");
+            log.info("External git repo url not provided for tenant "
+                    + tenantDomain + ", creating an git internal repository");
+
+            // for internal repos  internal git server username and password is used.
+            repository.setRepoUserName(System.getProperty(CartridgeConstants.INTERNAL_GIT_USERNAME));
+            repository.setRepoUserPassword(System.getProperty(CartridgeConstants.INTERNAL_GIT_PASSWORD));
+            /*repoCreationExecutor.execute(new RepositoryCreator(new RepositoryInfoBean(repoURL,
+                    cartName,
+                    tenantDomain,
+                    repository.getRepoUserName(),
+                    repository.getRepoUserPassword(),
+                    cartridgeInfo.getDeploymentDirs(),
+                    cartridgeInfo)));*/
+            new RepositoryCreator(new RepositoryInfoBean(repoURL,
+                    cartName,
+                    tenantDomain,
+                    repository.getRepoUserName(),
+                    repository.getRepoUserPassword(),
+                    cartridgeInfo.getDeploymentDirs(),
+                    cartridgeInfo)).createInternalRepository();
+            String repoName = tenantDomain + "/" + cartName;
+            repository.setRepoName("https://" + System.getProperty(CartridgeConstants.GIT_HOST_NAME) + ":8443/git/" + repoName);
+
+        }
+        return repository;
+    }
+
+    public static Cartridge getCartridgeInfo(String alias, String tenantDomain) throws ADCException, NotSubscribedException {
+        log.info("Alias: " + alias);
+        if (alias == null) {
+            String msg = "Provided alias is empty";
+            log.error(msg);
+            throw new ADCException("Alias you provided is empty.");
+        }
+
+        CartridgeSubscription sub;
+        try {
+            sub = PersistenceManager.getSubscription(tenantDomain, alias);
+        } catch (Exception e) {
+            String message = "Cannot get subscription info for " + tenantDomain + " and alias " + alias;
+            log.error(message, e);
+            throw new ADCException(message, e);
+        }
+        if (sub == null) {
+            String msg = "Info request for not subscribed cartridge";
+            log.error(msg);
+            throw new NotSubscribedException("You have not subscribed for " + alias, alias);
+        }
+
+        log.info("Cluster domain : " + sub.getClusterDomain() + " cartridge: " + sub.getCartridge());
+        
+        CartridgeInfo cartridgeInfo = null;
+        try {
+            cartridgeInfo = getServiceClient().getCartridgeInfo(sub.getCartridge());
+        } catch (Exception e) {
+            throw new ADCException("Cannot get cartridge info: " + sub.getCartridge(), e);
+        }
+
+        TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
+
+        String[] ips =
+                topologyMgtService.getActiveIPs(sub.getCartridge(),
+                        sub.getClusterDomain(),
+                        sub.getClusterSubdomain());
+        return populateCartridgeInfo(cartridgeInfo, sub, ips, tenantDomain);
+    }
+
+    private static void registerService(String cartridgeType, String domain, String subDomain,
+                                        DataHandler payload, String tenantRange, String hostName, Properties properties)
+            throws ADCException, UnregisteredCartridgeException {
+        log.info("Register service..");
+        try {
+            getServiceClient().register(domain, subDomain, cartridgeType, payload, tenantRange,
+                    hostName, properties);
+        } catch (CloudControllerServiceUnregisteredCartridgeExceptionException e) {
+            String msg = "Exception is occurred in register service operation. Reason :" + e.getMessage();
+            log.error(msg, e);
+            throw new UnregisteredCartridgeException("Not a registered cartridge " + cartridgeType, cartridgeType, e);
+        } catch (RemoteException e) {
+        	log.error("Remote Error", e);
+        	throw new ADCException("An error occurred in subscribing process");
+        }
+    }
+
+    public static Cartridge populateCartridgeInfo(CartridgeInfo cartridgeInfo, CartridgeSubscription sub, String[] ips, String tenantDomain) throws ADCException {
+    	Cartridge cartridge = new Cartridge();
+        if (ips != null && ips.length > 0) {
+			if (log.isDebugEnabled()) {
+				log.debug("Found IPs: " + Arrays.toString(ips) + " for " + cartridgeInfo.getType() + ", "
+						+ sub.getAlias());
+			}
+			if (CartridgeConstants.DATA_CARTRIDGE_PROVIDER.equals(sub.getProvider())) {
+				// FIXME Temporary fix for SPI-301
+				cartridge.setIp(ips[ips.length - 1]);
+				if (sub.getDataCartridge() != null) {
+					if (log.isDebugEnabled()) {
+						log.debug("Data Cartridge Info: " + sub.getDataCartridge().getUserName());
+					}
+					cartridge.setPassword(sub.getDataCartridge().getPassword());
+					cartridge.setDbUserName(sub.getDataCartridge().getUserName());
+				}
+			}
+			if (cartridgeInfo.getMultiTenant()) { // TODO refactor logic for carbon cartridges.
+				cartridge.setStatus(CartridgeConstants.ACTIVE);
+				cartridge.setActiveInstances(ips.length);
+			} else {
+				Map<String, String> instanceIpMap;
+				try {
+					instanceIpMap = PersistenceManager.getCartridgeInstanceInfo(ips, sub.getClusterDomain(),
+							sub.getClusterSubdomain());
+					cartridge.setActiveInstances(Collections.frequency(instanceIpMap.values(),
+							CartridgeConstants.ACTIVE));
+					cartridge.setStatus(checkCartridgeStatus(instanceIpMap));
+				} catch (Exception e) {
+					throw new ADCException("Error checking cartridge status");
+				}
+
+                if(cartridgeInfo.getProvider().equalsIgnoreCase(CartridgeConstants.PROVIDER_NAME_WSO2)) {
+
+                    List<Member> members = getMemberInstances(sub.getClusterDomain(), sub.getClusterSubdomain());
+                    if(members != null) {
+                        int activeInstancesCount = 0;
+                        for (Member member : members) {
+                            if (member != null && member.isActive() && member.getDomain().equals(sub.getClusterDomain())) {
+                                cartridge.setStatus(CartridgeConstants.ACTIVE);
+                                activeInstancesCount ++;
+                            }
+                        }
+                        cartridge.setActiveInstances(activeInstancesCount);
+                    }
+                }
+			}
+        } else {
+            log.warn("IPs have not returned through Topology Management for " + sub.getAlias());
+            cartridge.setStatus(CartridgeConstants.SUBSCRIBED);
+        }
+        cartridge.setDisplayName(cartridgeInfo.getDisplayName());
+        cartridge.setDescription(cartridgeInfo.getDescription());
+        cartridge.setVersion(cartridgeInfo.getVersion());
+        cartridge.setMultiTenant(cartridgeInfo.getMultiTenant());
+
+        List<String> accessURLs = new ArrayList<String>();
+
+        if (cartridgeInfo.getPortMappings() != null) {
+            for (org.apache.stratos.cloud.controller.util.xsd.PortMapping portMapping : cartridgeInfo
+                    .getPortMappings()) {
+                if (portMapping != null) {
+					try {
+						int port = Integer.parseInt(portMapping.getProxyPort());
+	                	String protocol = portMapping.getProtocol();
+
+	                	if ("http".equals(protocol) && port == 80) {
+	                	    port = -1;
+	                	} else if ("https".equals(protocol) && port == 443) {
+	                	    port = -1;
+	                	}
+	                	
+	                	String file = "";
+	                	if (CartridgeConstants.PROVIDER_NAME_WSO2.equals(cartridgeInfo.getProvider()) && !cartridgeInfo.getMultiTenant()) {
+	                		// Carbon Private Jet Cartridges
+	                		file = "/t/" + tenantDomain;
+	                	}
+	                	
+	                	URL serverURL = new URL(protocol, sub.getHostName(), port, file);
+						accessURLs.add(serverURL.toExternalForm());
+					} catch (MalformedURLException e) {
+						if (log.isErrorEnabled()) {
+							log.error("Error getting access URL for " + cartridgeInfo.getType(), e);
+						}
+					} catch (NumberFormatException e) {
+						if (log.isErrorEnabled()) {
+							log.error("Error getting port of access URL for " + cartridgeInfo.getType(), e);
+						}
+					}
+                }
+            }
+        }
+
+        cartridge.setAccessURLs(accessURLs.toArray(new String[accessURLs.size()]));
+
+        cartridge.setCartridgeAlias(sub.getAlias());
+        cartridge.setCartridgeType(sub.getCartridge());
+        cartridge.setHostName(sub.getHostName());
+        cartridge.setPolicy(sub.getPolicy());
+        Policy policy = PolicyHolder.getInstance().getPolicy(sub.getPolicy());
+        if (policy != null) {
+        	cartridge.setPolicyDescription(policy.getDescription());
+        }
+        cartridge.setProvider(sub.getProvider());
+        cartridge.setMappedDomain(sub.getMappedDomain());
+
+        if (sub.getRepository() != null) {
+            cartridge.setRepoURL(convertRepoURL(sub.getRepository().getRepoName()));
+        }
+        return cartridge;
+    }
+
+    private static List<Member> getMemberInstances(String domain, String subDomain) {
+
+        ClusteringAgent clusteringAgent = DataHolder.getServerConfigContext()
+                .getAxisConfiguration().getClusteringAgent();
+        GroupManagementAgent groupMgtAgent = clusteringAgent.getGroupManagementAgent(domain, subDomain);
+
+        if (groupMgtAgent == null) {
+            log.warn("Group Management Agent not found for domain : " + domain +
+                    ", sub domain : " + subDomain);
+            return null;
+        }
+
+        List<Member> members = groupMgtAgent.getMembers();
+        if (members == null || members.isEmpty()) {
+            return null;
+        }
+
+        return members;
+    }
+
+    private static String checkCartridgeStatus(Map<String, String> instanceIpMap) {
+        if (instanceIpMap.values().contains(CartridgeConstants.ACTIVE)) {
+            return CartridgeConstants.ACTIVE;
+        } else
+            return CartridgeConstants.NOT_READY;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeAppType.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeAppType.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeAppType.java
new file mode 100644
index 0000000..1c23c08
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeAppType.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.utils;
+
+/**
+ *
+ */
+public class CartridgeAppType {
+	private String appType;
+	private boolean appSpecificMapping;
+
+	public String getAppType() {
+		return appType;
+	}
+
+	public void setAppType(String appType) {
+		this.appType = appType;
+	}
+
+	public boolean isAppSpecificMapping() {
+		return appSpecificMapping;
+	}
+
+	public void setAppSpecificMapping(boolean appSpecificMapping) {
+		this.appSpecificMapping = appSpecificMapping;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConfigFileReader.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConfigFileReader.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConfigFileReader.java
new file mode 100644
index 0000000..9d28d4a
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConfigFileReader.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.utils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.utils.CarbonUtils;
+
+public class CartridgeConfigFileReader {
+
+	private static String carbonHome = CarbonUtils.getCarbonHome();
+
+	private static final Log log = LogFactory.getLog(CartridgeConfigFileReader.class);
+
+	/**
+	 * 
+	 * Reads cartridge-config.properties file and assign properties to system
+	 * properties
+	 * 
+	 */
+	public static void readProperties() {
+
+		Properties properties = new Properties();
+		try {
+			properties.load(new FileInputStream(carbonHome + File.separator + "repository" +
+			                                    File.separator + "conf" + File.separator +
+			                                    "cartridge-config.properties"));
+		} catch (Exception e) {
+			log.error("Exception is occurred in reading properties file. Reason:" + e.getMessage());
+		}
+		if (log.isInfoEnabled()) {
+			log.info("Setting config properties into System properties");
+		}
+
+		for (String name : properties.stringPropertyNames()) {
+			String value = properties.getProperty(name);
+			System.setProperty(name, value);
+		}
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConstants.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConstants.java
new file mode 100644
index 0000000..0340e61
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeConstants.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.utils;
+
+public class CartridgeConstants {
+    public static final String SC_IP = "sc.ip";
+	public static final String AUTOSCALER_SERVICE_URL = "autoscalerService.url";
+    public static final String ALIAS_NAMESPACE ="http://org.wso2.securevault/configuration";
+    public static final String ALIAS_LOCALPART ="secretAlias";
+    public static final String ALIAS_PREFIX ="svns";
+	public static final String CARTRIDGE_AGENT_EPR = "cartridge.agent.epr";
+	public static final String GIT_HOST_NAME = "git.host.name";
+	public static final String GIT_HOST_IP = "git.host.ip";
+	public static final String SUBSCRIPTION_ACTIVE = "SUBSCRIPTION_ACTIVE";
+	public static final String SUBSCRIPTION_INACTIVE = "SUBSCRIPTION_INACTIVE";
+	public static final String REPO_NOTIFICATION_URL = "git.repo.notification.url";
+	public static final String ACTIVE = "ACTIVE";
+	public static final String NOT_READY = "NOT-READY";
+	public static final String SUBSCRIBED = "SUBSCRIBED";
+
+	public static final String DB_DATASOURCE = "adc.datasource";
+	public static final String DB_URL = "adc.jdbc.url";
+	public static final String DB_DRIVER = "adc.jdbc.driver";
+	public static final String DB_USERNAME = "adc.jdbc.username";
+	public static final String DB_PASSWORD = "adc.jdbc.password";
+	public static final String BAM_IP = "bam.ip";
+	public static final String BAM_PORT = "bam.port";
+	public static final String SUDO_SH = "sudo sh";
+	public static final String APPEND_SCRIPT = "append.script";
+	public static final String REMOVE_SCRIPT = "remove.script";
+	public static final String BIND_FILE_PATH = "bind.file.path";
+	public static final String ELB_IP = "elb.ip";
+	public static final String REPO_KEY_PATH = "repo.key.path";
+	public static final String REPO_KEY = "repo.key";
+	public static final String MAX_ATTEMPTS = "max.attempts";
+	public static final String CARTRIDGE_KEY = "cartridge.key";
+	
+	public static final String FEATURE_EXTERNAL_REPO_VAIDATION_ENABLED = "feature.externalrepo.validation.enabled";
+	public static final String FEATURE_INTERNAL_REPO_ENABLED = "feature.internalrepo.enabled";
+	public static final String FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED = "feature.multitenant.multiplesubscription.enabled";
+	
+	public static final String MYSQL_CARTRIDGE_NAME = "mysql";
+	public static final String DEFAULT_SUBDOMAIN = "__$default";
+	public static final String DEFAULT_MGT_SUBDOMAIN = "mgt";
+	public static final String MYSQL_DEFAULT_USER = "root";
+	public static final String PROVIDER_NAME_WSO2 = "wso2";
+	public static final String NOT_SUBSCRIBED = "NOT-SUBSCRIBED";
+    public static final String SECURITY_KEY_FILE = "gitRepoKey.xml";
+    public static final String SECURITY_KEY = "securityKey";
+    public static final String DEFAULT_SECURITY_KEY = "tvnw63ufg9gh5111";
+    public static final String DATA_CARTRIDGE_PROVIDER = "data";
+	public static final String REPO_INFO_EPR = "repository.info.epr";
+	public static final String INTERNAL_GIT_USERNAME = "internal.repo.username";
+	public static final String INTERNAL_GIT_PASSWORD = "internal.repo.password";
+
+    public static final class DomainMappingInfo {
+		public static final String ACTUAL_HOST = "actual.host";
+		public static final String HOSTINFO = "hostinfo/";
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeDomain.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeDomain.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeDomain.java
new file mode 100644
index 0000000..2207b43
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/CartridgeDomain.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.utils;
+
+/**
+ *
+ */
+public class CartridgeDomain {
+
+	private String primaryPort;
+	private String proxyPort;
+	private String type;
+	private String tenantId;
+	private int min;
+	private int max;
+	private String cartridgeType;
+	private boolean volume;
+	private String tenantDomain;
+	private String clusterDomain;
+	private String clusterSubDomain;
+
+	private String hostName;
+	private boolean started;
+
+	public String getPrimaryPort() {
+		return primaryPort;
+	}
+
+	public String getProxyPort() {
+		return proxyPort;
+	}
+
+	public String getType() {
+		return type;
+	}
+
+	public String getTenantId() {
+		return tenantId;
+	}
+
+	public int getMin() {
+		return min;
+	}
+
+	public int getMax() {
+		return max;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+
+	public boolean getVolume() {
+		return volume;
+	}
+
+	public String getTenantDomain() {
+		return tenantDomain;
+	}
+
+	public void setPrimaryPort(String primaryPort) {
+		this.primaryPort = primaryPort;
+	}
+
+	public void setProxyPort(String proxyPort) {
+		this.proxyPort = proxyPort;
+	}
+
+	public void setType(String type) {
+		this.type = type;
+	}
+
+	public void setTenantId(String tenantId) {
+		this.tenantId = tenantId;
+	}
+
+	public void setMin(int min) {
+		this.min = min;
+	}
+
+	public void setMax(int max) {
+		this.max = max;
+	}
+
+	public void setCartridgeType(String cartridgeType) {
+		this.cartridgeType = cartridgeType;
+	}
+
+	public void setVolume(boolean volume) {
+		this.volume = volume;
+	}
+
+	public void setTenantDomain(String tenantDomain) {
+		this.tenantDomain = tenantDomain;
+	}
+
+	public void setStarted(boolean started) {
+		this.started = started;
+	}
+
+	public boolean isStarted() {
+		return started;
+	}
+
+	public String getHostName() {
+		return hostName;
+	}
+
+	public void setHostName(String hostName) {
+		this.hostName = hostName;
+	}
+
+	public String getClusterDomain() {
+		return clusterDomain;
+	}
+
+	public void setClusterDomain(String clusterDomain) {
+		this.clusterDomain = clusterDomain;
+	}
+
+	public String getClusterSubDomain() {
+		return clusterSubDomain;
+	}
+
+	public void setClusterSubDomain(String clusterSubDomain) {
+		this.clusterSubDomain = clusterSubDomain;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/DomainInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/DomainInfo.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/DomainInfo.java
new file mode 100644
index 0000000..53fed09
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/adc/mgt/utils/DomainInfo.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.stratos.adc.mgt.utils;
+
+public class DomainInfo {
+
+	String domain;
+	String subDomain;
+
+	public String getDomain() {
+		return domain;
+	}
+
+	public void setDomain(String domain) {
+		this.domain = domain;
+	}
+
+	public String getSubDomain() {
+		return subDomain;
+	}
+
+	public void setSubDomain(String subDomain) {
+		this.subDomain = subDomain;
+	}
+
+}


[12/45] fixing component version issues and adding currently refactored components to the parent pom

Posted by is...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java
new file mode 100644
index 0000000..5d26a2c
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/replication/RequestTokenReplicationCommand.java
@@ -0,0 +1,73 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.replication;
+
+import org.apache.axis2.clustering.ClusteringCommand;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.clustering.ClusteringMessage;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.util.Map;
+
+/**
+ * This is the notification message a primary load balancer will send to all other load balancers
+ * in the cluster, to replicate its state. When the other load balancers received this message, 
+ * they will set their states to the state of primary load balancer.
+ */
+public class RequestTokenReplicationCommand extends ClusteringMessage {
+
+    private static final long serialVersionUID = -7897961078018830555L;
+    private static final Log log = LogFactory.getLog(RequestTokenReplicationCommand.class);
+    private Map<String, Map<String, ?>> appDomainContexts;
+
+    public Map<String, Map<String, ?>> getAppDomainContexts() {
+        return appDomainContexts;
+    }
+
+    public void setAppDomainContexts(Map<String, Map<String, ?>> appDomainContexts) {
+        this.appDomainContexts = appDomainContexts;
+    }
+
+    public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
+        // set the appDomainContexts map
+        configurationContext.setNonReplicableProperty("autoscale.app.domain.contexts",
+                                          getAppDomainContexts());
+        
+        log.info("Request Tokens Replicated! ");
+    }
+
+    public String toString() {
+        return "Replication message sent!";
+    }
+
+    @Override
+    public ClusteringCommand getResponse() {
+        return new ClusteringCommand() {
+            
+            private static final long serialVersionUID = -8271265673996681347L;
+
+            @Override
+            public void execute(ConfigurationContext arg0) throws ClusteringFault {
+                // do nothing
+            }
+        };
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java
new file mode 100644
index 0000000..5958ad9
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/LoadBalancerConfigurationService.java
@@ -0,0 +1,79 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.service;
+
+import org.apache.stratos.lb.common.conf.util.HostContext;
+
+import java.util.Map;
+
+/**
+ * This service provides a way to consume details in loadbalancer.conf file.
+ * Also to update the runtime object model of loadbalancer conf.
+ */
+public interface LoadBalancerConfigurationService {
+
+    /**
+     * Provides a reference to the runtime object model of loadbalancer.conf
+     * @return {@link Object} which is an instance of {@link org.apache.stratos.lb.common.conf.LoadBalancerConfiguration}
+     */
+    public Object getLoadBalancerConfig();
+    
+//    /**
+//     * Return a {@link Map} of {@link HostContext} objects, built using the given config.
+//     * @param config service configuration.
+//     * @return {@link Map} {@link Object}
+//     */
+//    public Object getHostContext(String config);
+    
+    /**
+     * Return a {@link Map} of {@link HostContext} objects, built using the given configuration.
+     * @param config service configuration diff. This can be in following format.
+     * 
+     * <p/>
+     * appserver {
+     * hosts                   appserver.cloud-test.wso2.com;
+     * domains   {
+     * 		wso2.as1.domain {
+     * 			tenant_range    1-100;
+     * 		}
+     *		wso2.as2.domain {
+     * 			tenant_range    101-200;
+     * 		}
+     * 		wso2.as3.domain {
+     *	 		tenant_range    *;
+     * 		}
+     * 	}
+     * } 
+     * <p/>
+     * esb {
+     * hosts                   esb.cloud-test.wso2.com;
+     * domains   {
+     * 		wso2.esb.domain {
+     *	 		tenant_range    *;
+     * 		}
+     * 	}
+     * }
+     * <p/>
+     * @return a {@link Map} of {@link HostContext} objects.
+     * key - host name
+     * Value - {@link HostContext}
+     */
+    public Object getHostContexts(String config) ;
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
new file mode 100644
index 0000000..99c2ced
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
@@ -0,0 +1,60 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.service.impl;
+
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.structure.Node;
+import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
+import org.apache.stratos.lb.common.conf.util.Constants;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
+
+import java.util.Map;
+
+public class LoadBalancerConfigurationServiceImpl implements LoadBalancerConfigurationService {
+
+    @Override
+    public Object getLoadBalancerConfig() {
+        return LoadBalancerConfiguration.getInstance();
+    }
+
+	@Override
+    public Object getHostContexts(String config) {
+
+		// build a Node object for whole loadbalancer.conf
+        Node rootNode = new Node();
+        rootNode.setName(Constants.SERVICES_ELEMENT);
+        rootNode = NodeBuilder.buildNode(rootNode, config);
+		
+        Map<String, HostContext> oldMap = LoadBalancerConfiguration.getInstance().getHostContextMap();
+        LoadBalancerConfiguration.getInstance().createServicesConfig(rootNode);
+        
+//        MapDifference<String, HostContext> diff = Maps.difference(LoadBalancerConfiguration.getInstance().getHostContextMap(),
+//                                                             oldMap );
+//		
+//		return diff.entriesOnlyOnLeft();
+        return LoadBalancerConfiguration.getInstance().getHostContextMap();
+    }
+
+//	@Override
+//    public Object getHostContext(String config) {
+//	    return null;
+//    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java
new file mode 100644
index 0000000..7355833
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/DomainMapping.java
@@ -0,0 +1,40 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.util;
+
+/**
+ *
+ */
+public class DomainMapping {
+    private String mapping;
+    private String actualHost;
+
+    public DomainMapping(String mapping) {
+        this.mapping = mapping;
+    }
+
+    public String getActualHost() {
+        return actualHost;
+    }
+
+    public void setActualHost(String actualHost) {
+        this.actualHost = actualHost;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..6d1f398
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml
@@ -0,0 +1,9 @@
+<serviceGroup>
+    <service name="LoadBalancerConfigurationService" scope="application">
+        <parameter name="ServiceClass">org.wso2.stratos.lb.common.service.impl.LoadBalancerConfigurationServiceImpll</parameter>
+        <messageReceivers>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
+    </messageReceivers>
+    </service>
+</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java b/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java
new file mode 100644
index 0000000..4efbbd2
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigurationTest.java
@@ -0,0 +1,169 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.test;
+
+import java.io.File;
+
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+
+import junit.framework.TestCase;
+
+public class LoadBalancerConfigurationTest extends TestCase {
+    
+    private LoadBalancerConfiguration lbConfig ;
+    private LoadBalancerConfiguration lbConfig1;
+    
+    
+    @Override
+    protected void setUp() throws Exception {
+
+        LoadBalancerConfiguration.setInstance(null);
+        File f = new File("src/test/resources/loadbalancer.conf");
+        System.setProperty("loadbalancer.conf", f.getAbsolutePath());
+        lbConfig = LoadBalancerConfiguration.getInstance();
+    }
+    
+    public final void testCreateLoadBalancerConfig() {
+
+        LoadBalancerConfiguration.LBConfiguration loadBalancerConfig =
+            lbConfig.getLoadBalancerConfig();
+        
+        assertEquals(1, loadBalancerConfig.getInstances());
+        assertEquals(5000, loadBalancerConfig.getAutoscalerTaskInterval());
+        assertEquals(15000, loadBalancerConfig.getServerStartupDelay());
+    }
+
+    public final void testCreateServicesConfig() {
+
+        /* Tests relavant to loadbalancer.conf file */
+        
+        ServiceConfiguration asServiceConfig =
+                                               lbConfig.getServiceConfig("wso2.as1.domain",
+                                                                         "worker");
+
+        assertEquals(1, asServiceConfig.getInstancesPerScaleUp());
+        assertEquals(5, asServiceConfig.getMaxAppInstances());
+        assertEquals(0, asServiceConfig.getMinAppInstances());
+        assertEquals(60000, asServiceConfig.getMessageExpiryTime());
+        assertEquals(400, asServiceConfig.getMaxRequestsPerSecond());
+        assertEquals(0.65, asServiceConfig.getAlarmingUpperRate());
+        assertEquals(10, asServiceConfig.getRoundsToAverage());
+        assertEquals("worker", asServiceConfig.getSubDomain());
+
+        asServiceConfig = lbConfig.getServiceConfig("wso2.as2.domain", "worker1");
+        assertEquals("worker1", asServiceConfig.getSubDomain());
+
+        asServiceConfig = lbConfig.getServiceConfig("wso2.esb.domain", "mgt");
+        assertEquals("mgt", asServiceConfig.getSubDomain());
+
+        assertEquals(2, lbConfig.getHostNamesTracker().keySet().size());
+        assertEquals(3, lbConfig.getHostNamesTracker().get("appserver").size());
+        assertEquals(2, lbConfig.getHostNamesTracker().get("esb").size());
+
+        for (HostContext ctx : lbConfig.getHostContextMap().values()) {
+
+            if (ctx.getHostName().equals("appserver.cloud-test.wso2.com")) {
+
+                assertEquals("nirmal", ctx.getSubDomainFromTenantId(30));
+                assertEquals(18, ctx.getTenantDomainContexts().size());
+            } else if (ctx.getHostName().equals("as2.cloud-test.wso2.com")) {
+                assertEquals("worker", ctx.getSubDomainFromTenantId(2));
+            } else if (ctx.getHostName().equals("esb.cloud-test.wso2.com")) {
+                assertEquals("mgt", ctx.getSubDomainFromTenantId(5));
+            }
+        }
+        
+        /* tests relevant to loadbalancer1.conf file */
+        
+        File f = new File("src/test/resources/loadbalancer2.conf");
+        System.setProperty("loadbalancer.conf", f.getAbsolutePath());
+        
+        LoadBalancerConfiguration.setInstance(null);
+        lbConfig1 = LoadBalancerConfiguration.getInstance();
+        
+        for (HostContext ctx : lbConfig1.getHostContextMap().values()) {
+
+            if (ctx.getHostName().equals("appserver.cloud-test.wso2.com")) {
+
+                assertEquals("nirmal", ctx.getSubDomainFromTenantId(30));
+                assertEquals("wso2.as1.domain", ctx.getDomainFromTenantId(5));
+                assertEquals("wso2.as.domain", ctx.getDomainFromTenantId(8));
+                assertEquals("wso2.as.domain", ctx.getDomainFromTenantId(2));
+                assertEquals(4, ctx.getTenantDomainContexts().size());
+                
+            } else if (ctx.getHostName().equals("esb.cloud-test.wso2.com")) {
+                
+                assertEquals("mgt", ctx.getSubDomainFromTenantId(5));
+            }
+        }
+
+    }
+
+    public final void testGetServiceDomains() throws Exception {
+
+        setUp();
+        String[] serviceDomains = lbConfig.getServiceDomains();
+        assertEquals(4, serviceDomains.length);
+        
+        assertTrue("wso2.as1.domain".equals(serviceDomains[0]) ||
+            "wso2.as1.domain".equals(serviceDomains[1]) ||
+            "wso2.as1.domain".equals(serviceDomains[2]) ||
+            "wso2.as1.domain".equals(serviceDomains[3]));
+        
+        assertTrue("wso2.as2.domain".equals(serviceDomains[0]) ||
+            "wso2.as2.domain".equals(serviceDomains[1]) ||
+            "wso2.as2.domain".equals(serviceDomains[2]) ||
+            "wso2.as2.domain".equals(serviceDomains[3]));
+        
+        assertTrue("wso2.as3.domain".equals(serviceDomains[0]) ||
+            "wso2.as3.domain".equals(serviceDomains[1]) ||
+            "wso2.as3.domain".equals(serviceDomains[2]) ||
+            "wso2.as3.domain".equals(serviceDomains[3]));
+        
+        assertTrue("wso2.esb.domain".equals(serviceDomains[0]) ||
+                   "wso2.esb.domain".equals(serviceDomains[1]) ||
+                   "wso2.esb.domain".equals(serviceDomains[2]) ||
+                   "wso2.esb.domain".equals(serviceDomains[3]));
+        
+    }
+    
+    public final void testGetServiceSubDomains() throws Exception {
+
+        setUp();
+        String[] serviceSubDomains = lbConfig.getServiceSubDomains("wso2.as3.domain");
+        assertEquals(2, serviceSubDomains.length);
+        
+        assertTrue("nirmal".equals(serviceSubDomains[0]) ||
+            "nirmal".equals(serviceSubDomains[1]));
+        
+        assertTrue("nirmal2".equals(serviceSubDomains[0]) ||
+            "nirmal2".equals(serviceSubDomains[1]));
+        
+        serviceSubDomains = lbConfig.getServiceSubDomains("wso2.esb.domain");
+        assertEquals(2, serviceSubDomains.length);
+        
+        serviceSubDomains = lbConfig.getServiceSubDomains("wso2.as1.domain");
+        assertEquals(1, serviceSubDomains.length);
+        
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java b/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java
new file mode 100644
index 0000000..e3b2f5e
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/NodeBuilderTest.java
@@ -0,0 +1,124 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.common.test;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.apache.stratos.lb.common.conf.structure.Node;
+import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
+
+public class NodeBuilderTest extends TestCase {
+
+    String content;
+
+    public void setUp() throws Exception {
+    }
+
+    public final void testBuildNode() {
+
+        // Testing a node only has properties
+        Node a = new Node();
+        a.setName("loadbalancer");
+
+        content =
+            "securityGroups      stratos-appserver-lb;\ninstanceType        m1.large;\n"
+                + "instances           1;\nelasticIP           ${ELASTIC_IP};\n"
+                + "availabilityZone    us-east-1c;\npayload             /mnt/payload.zip;";
+
+        a = NodeBuilder.buildNode(a, content);
+
+        Assert.assertEquals("loadbalancer", a.getName());
+        Assert.assertEquals("stratos-appserver-lb", a.getProperty("securityGroups"));
+        Assert.assertEquals("${ELASTIC_IP}", a.getProperty("elasticIP"));
+        Assert.assertEquals("/mnt/payload.zip", a.getProperty("payload"));
+        Assert.assertNull(a.getProperty("payloader"));
+
+        // Testing a node has sub nodes and properties
+        a = new Node();
+        a.setName("appserver");
+
+        content =
+            "hosts                   appserver.cloud-test.wso2.com,as.cloud-test.wso2.com;\n"
+                + "domains   {\n" + "wso2.as1.domain {\n" + "tenant_range    1-100;\n" + "}\n"
+                + "wso2.as2.domain {\n" + "tenant_range    101-200;\n" + "}\n"
+                + "wso2.as3.domain { # domain\n" + "tenant_range    *;\n" + "}\n" + "}\n"
+                + "# line comment \n"
+                + "payload                 resources/cluster_node.zip;# payload\n"
+                + "availability_zone       us-east-1c;\n";
+
+        a = NodeBuilder.buildNode(a, content);
+
+        Assert.assertEquals("appserver", a.getName());
+        Assert.assertEquals(1, a.getChildNodes().size());
+        Assert.assertEquals("domains", a.getChildNodes().get(0).getName());
+        Assert.assertEquals("appserver.cloud-test.wso2.com,as.cloud-test.wso2.com",
+                            a.getProperty("hosts"));
+        Assert.assertEquals("resources/cluster_node.zip", a.getProperty("payload"));
+        Assert.assertEquals(null, a.getProperty("payloader"));
+
+        Node b = a.getChildNodes().get(0);
+
+        Assert.assertEquals(3, b.getChildNodes().size());
+        Assert.assertEquals(null, b.getProperty("payload"));
+
+        Node c = b.getChildNodes().get(0);
+
+        Assert.assertEquals(0, c.getChildNodes().size());
+        Assert.assertEquals("1-100", c.getProperty("tenant_range"));
+
+        c = b.getChildNodes().get(2);
+
+        Assert.assertEquals(0, c.getChildNodes().size());
+        Assert.assertEquals("*", c.getProperty("tenant_range"));
+        
+        String nodeStr = "appserver {\n" +
+                "\thosts\tappserver.cloud-test.wso2.com,as.cloud-test.wso2.com;\n" +
+                "\tpayload\tresources/cluster_node.zip;\n" +
+        		"\tavailability_zone\tus-east-1c;\n" +
+        		"\tdomains {\n" +
+        		"\t\twso2.as1.domain {\n" +
+        		"\t\t\ttenant_range\t1-100;\n" +
+        		"\t\t}\n" +
+        		"\t\twso2.as2.domain {\n" +
+        		"\t\t\ttenant_range\t101-200;\n" +
+        		"\t\t}\n" +
+        		"\t\twso2.as3.domain {\n" +
+        		"\t\t\ttenant_range\t*;\n" +
+        		"\t\t}\n" +
+        		"\t}\n" +
+        		"}";
+        
+        assertEquals(nodeStr, a.toString());
+        
+        // test equals method
+        assertEquals(true, a.equals(a));
+        assertEquals(false, a.equals(b));
+        assertEquals(false, c.equals(b));
+        
+        // test buildNode(String)
+        c = NodeBuilder.buildNode(nodeStr);
+        
+        assertEquals(c.getName(), "appserver");
+        assertEquals(c.getChildNodes().size(), 1);
+        assertEquals(c.getProperty("availability_zone"), "us-east-1c");
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf
new file mode 100644
index 0000000..b2fd44f
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf
@@ -0,0 +1,64 @@
+loadbalancer {
+    instances	1;
+    enable_autoscaler	true;
+    # interval between two task executions in milliseconds
+    autoscaler_task_interval	5000;
+    # after an instance booted up, task will wait till this much of time and let the server started up
+    server_startup_delay		15000; #default will be 60000ms
+}
+
+services {
+    defaults {
+        min_app_instances 1;
+        max_app_instances       5;
+        max_requests_per_second   400;
+        alarming_upper_rate 0.65;
+        alarming_lower_rate 0.2;
+        scale_down_factor 0.25;
+        rounds_to_average       10;
+        instances_per_scale_up  1;
+        message_expiry_time     60000;
+    }
+
+    appserver {
+        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+        sub_domain      worker1;
+        domains   {
+            wso2.as1.domain {
+            	hosts as2.cloud-test.wso2.com;
+            	  min_app_instances   0;
+            	  sub_domain      worker;
+                tenant_range    1-5;
+            }
+            wso2.as2.domain {
+                tenant_range    7;
+            }
+            wso2.as3.domain {
+                sub_domain nirmal;
+                tenant_range    10-20;
+            }
+            
+            wso2.as3.domain {
+                sub_domain nirmal2;
+                tenant_range    21-25;
+            }
+            
+            wso2.esb.domain {
+            	sub_domain nirmal;
+                tenant_range    *;
+            }
+        }
+    }
+    
+    esb {
+        hosts                   esb.cloud-test.wso2.com,mgt.as.cloud-test.wso2.com;
+        domains   {
+            wso2.esb.domain {
+                sub_domain      mgt;
+                tenant_range    *;
+            }
+        }
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf
new file mode 100644
index 0000000..8b87a32
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf
@@ -0,0 +1,39 @@
+loadbalancer {
+    instances	1;
+    enable_autoscaler	true;
+    # interval between two task executions in milliseconds
+    autoscaler_task_interval	5000;
+    # after an instance booted up, task will wait till this much of time and let the server started up
+    server_startup_delay		15000; #default will be 60000ms
+}
+
+services {
+
+    appserver {
+        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+        sub_domain      worker1;
+        domains   {
+            
+            wso2.as.domain {
+            	sub_domain nirmal;
+                tenant_range    *;
+            }
+            wso2.as1.domain {
+            	sub_domain nirmal;
+                tenant_range    5-7;
+            }
+        }
+    }
+    
+    esb {
+        hosts                   esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
+        domains   {
+            wso2.esb.domain {
+                sub_domain      mgt;
+                tenant_range    *;
+            }
+        }
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf
new file mode 100644
index 0000000..718d881
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf
@@ -0,0 +1,30 @@
+services {
+
+    appserver {
+        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+        sub_domain      worker1;
+        domains   {
+            
+            wso2.as.domain {
+            	sub_domain nirmal;
+                tenant_range    *;
+            }
+            wso2.as1.domain {
+            	sub_domain nirmal;
+                tenant_range    5-7;
+            }
+        }
+    }
+    
+    esb {
+        hosts                   esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
+        domains   {
+            wso2.esb.domain {
+                sub_domain      mgt;
+                tenant_range    *;
+            }
+        }
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.common/src/test/resources/testng.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/testng.xml b/components/org.apache.stratos.lb.common/src/test/resources/testng.xml
new file mode 100644
index 0000000..44b9822
--- /dev/null
+++ b/components/org.apache.stratos.lb.common/src/test/resources/testng.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
+<suite name="Default suite">
+  <test verbose="2" name="Default test">
+    <classes>
+      <!--class name="org.wso2.carbon.lb.common.test.AgentPersistenceManagerTest">
+          <methods>
+            <include name="addZone" />
+              <include name="addHostMachine" />
+              <include name="deleteHostMachine" />
+          </methods>
+      </class-->
+    </classes>
+  </test>
+</suite>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/pom.xml b/components/org.apache.stratos.lb.endpoint/pom.xml
new file mode 100644
index 0000000..35da614
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/pom.xml
@@ -0,0 +1,114 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     ~  Licensed to the Apache Software Foundation (ASF) under one
+     ~  or more contributor license agreements.  See the NOTICE file
+     ~  distributed with this work for additional information
+     ~  regarding copyright ownership.  The ASF licenses this file
+     ~  to you under the Apache License, Version 2.0 (the
+     ~  "License"); you may not use this file except in compliance
+     ~  with the License.  You may obtain a copy of the License at
+     ~
+     ~    http://www.apache.org/licenses/LICENSE-2.0
+     ~
+     ~  Unless required by applicable law or agreed to in writing,
+     ~  software distributed under the License is distributed on an
+     ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+     ~  KIND, either express or implied.  See the License for the
+     ~  specific language governing permissions and limitations
+     ~  under the License.
+     ~
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>stratos-components-parent</artifactId>
+        <version>3.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.apache.stratos</groupId>
+    <artifactId>org.apache.stratos.lb.endpoint</artifactId>
+    <packaging>bundle</packaging>
+    <name>Apache Stratos - Tenant Aware LoadBalance Endpoint</name>
+    <url>http://apache.org</url>
+    
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.mediation.initializer</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.mediation.dependency.mgt</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-core</artifactId>
+            <version>${synapse.core.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.logging</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.stratos</groupId>
+            <artifactId>org.apache.stratos.lb.common</artifactId>
+            <version>${apache.stratos.version}</version>
+        </dependency>
+	<dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+            <version>${axis2.wso2.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2</groupId>
+            <artifactId>axis2-kernel</artifactId>
+            <version>1.6.1-wso2v9</version>
+        </dependency>
+        <dependency>
+           <groupId>org.apache.stratos</groupId>
+           <artifactId>org.apache.stratos.cartridge.messages</artifactId>
+           <version>${apache.stratos.version}</version>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.apache.stratos.lb.endpoint.endpoint,
+                            org.apache.stratos.lb.endpoint,
+                            org.apache.stratos.lb.endpoint.util,
+                        </Export-Package>
+                        <Import-Package>
+                            !org.apache.stratos.lb.endpoint.endpoint,
+                            !org.apache.stratos.lb.endpoint,
+                            org.apache.stratos.lb.common.*; version=${project.version},
+                            org.apache.stratos.registry.core.service; version=1.0.1,
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java
new file mode 100644
index 0000000..60efed5
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointConstants.java
@@ -0,0 +1,31 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.lb.endpoint;
+
+/**
+ * The <code>EndpointConstants</code> class defined the endpoint constants.
+ */
+public class EndpointConstants {
+
+    public static final String ADDRESS_ENDPOINT = "Address Endpoint";
+    public static final String WSDL_ENDPOINT = "WSDL Endpoint";
+    public static final String FAILOVER_ENDPOINT = "Failover Group";
+    public static final String LOADBALANCE_ENDPOINT = "Loadbalance Endpoint";
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java
new file mode 100644
index 0000000..e4274f5
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/EndpointDeployer.java
@@ -0,0 +1,71 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+package org.apache.stratos.lb.endpoint;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.context.ConfigurationContext;
+import org.wso2.carbon.mediation.initializer.ServiceBusConstants;
+import org.wso2.carbon.mediation.initializer.ServiceBusUtils;
+import org.wso2.carbon.mediation.initializer.persistence.MediationPersistenceManager;
+
+import java.util.Properties;
+
+/**
+ * Responsible for deploying Synapse artifacts.
+ */
+public class EndpointDeployer extends org.apache.synapse.deployers.EndpointDeployer {
+
+    MediationPersistenceManager mpm;
+
+    @Override
+    public void init(ConfigurationContext configCtx) {
+        super.init(configCtx);
+        this.mpm = ServiceBusUtils.getMediationPersistenceManager(configCtx.getAxisConfiguration());
+    }
+
+    @Override
+    public String deploySynapseArtifact(OMElement artifactConfig, String fileName,
+                                        Properties properties) {
+        String epName = super.deploySynapseArtifact(artifactConfig, fileName, properties);
+        mpm.saveItemToRegistry(epName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+        return epName;
+    }
+
+    @Override
+    public String updateSynapseArtifact(OMElement artifactConfig, String fileName,
+                                        String existingArtifactName, Properties properties) {
+        String epName = super.updateSynapseArtifact(
+                artifactConfig, fileName, existingArtifactName, properties);
+        mpm.saveItemToRegistry(epName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+        return epName;
+    }
+
+    @Override
+    public void undeploySynapseArtifact(String artifactName) {
+        super.undeploySynapseArtifact(artifactName);
+        mpm.deleteItemFromRegistry(artifactName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+    }
+
+    @Override
+    public void restoreSynapseArtifact(String artifactName) {
+        super.restoreSynapseArtifact(artifactName);
+        mpm.saveItemToRegistry(artifactName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
new file mode 100644
index 0000000..ac78fdd
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
@@ -0,0 +1,39 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint;
+
+/**
+ * Exception to be thrown from this component.
+ */
+public class TenantAwareLoadBalanceEndpointException extends RuntimeException {
+
+    private static final long serialVersionUID = -663839410798538370L;
+
+    public TenantAwareLoadBalanceEndpointException(String msg) {
+        super(msg);
+    }
+
+    public TenantAwareLoadBalanceEndpointException(String msg, Throwable cause) {
+        super(msg, cause);
+    }
+
+    public TenantAwareLoadBalanceEndpointException(Throwable cause) {
+        super(cause);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java
new file mode 100644
index 0000000..07208cb
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/TenantLoadBalanceMembershipHandler.java
@@ -0,0 +1,208 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint;
+
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.core.LoadBalanceMembershipHandler;
+import org.apache.synapse.endpoints.algorithms.AlgorithmContext;
+import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.wso2.carbon.user.api.UserStoreException;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * Bridge between Axis2 membership notification and Synapse load balancing
+ */
+public class TenantLoadBalanceMembershipHandler implements LoadBalanceMembershipHandler {
+    private static final Log log = LogFactory.getLog(TenantLoadBalanceMembershipHandler.class);
+
+    private ConfigurationContext configCtx;
+
+    private LoadbalanceAlgorithm lbAlgo;
+    
+    /**
+     * Key - Host, Value - HostContext
+     */
+    private static Map<String, HostContext> hostContextsMap =
+            new HashMap<String, HostContext>();
+    
+    private ClusteringAgent clusteringAgent;
+    
+    private boolean isClusteringEnabled;
+    private String endpointName;
+
+    public TenantLoadBalanceMembershipHandler(Map<String, HostContext> hostContexts,
+                                              LoadbalanceAlgorithm algorithm,
+                                              ConfigurationContext configCtx,
+                                              boolean isClusteringEnabled,
+                                              String endpointName) {
+
+        lbAlgo = algorithm;
+        this.isClusteringEnabled = isClusteringEnabled;
+        this.endpointName = endpointName;
+        this.configCtx = configCtx;
+        
+        for (HostContext host : hostContexts.values()) {
+            
+            addHostContext(host);
+
+        }
+    }
+    
+    /**
+     * This will be used to add new {@link HostContext}s.
+     * @param host {@link HostContext}
+     */
+    public void addHostContext(HostContext host){
+        
+        String hostName = host.getHostName();
+
+        AlgorithmContext algorithmContext =
+                                            new AlgorithmContext(isClusteringEnabled,
+                                                                 configCtx, endpointName + "." +
+                                                                            hostName);
+
+        host.setAlgorithm(lbAlgo.clone());
+        host.setAlgorithmContext(algorithmContext);
+
+        hostContextsMap.put(hostName, host);
+        
+    }
+    
+    /**
+     * This will be used to remove an existing {@link HostContext}s.
+     * @param host {@link HostContext}
+     */
+    public void removeHostContext(String host){
+
+        hostContextsMap.remove(host);
+        
+    }
+
+    public void init(Properties props, LoadbalanceAlgorithm algorithm) {
+        // Nothing to do
+    }
+
+    public void setConfigurationContext(ConfigurationContext configCtx) {
+        this.configCtx = configCtx;
+
+        // The following code does the bridging between Axis2 and Synapse load balancing
+        clusteringAgent = configCtx.getAxisConfiguration().getClusteringAgent();
+        if (clusteringAgent == null) {
+            String msg = "In order to enable load balancing across an Axis2 cluster, " +
+                         "the cluster entry should be enabled in the axis2.xml file";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+    }
+
+    public ConfigurationContext getConfigurationContext() {
+        return configCtx;
+    }
+
+    /**
+     * Getting the next member to which the request has to be sent in a round-robin fashion
+     *
+     * @param context The AlgorithmContext
+     * @return The current member
+     * @deprecated Use {@link #getNextApplicationMember(String, int)}
+     */
+    public Member getNextApplicationMember(AlgorithmContext context) {
+        throw new UnsupportedOperationException("This operation is invalid. " +
+                                                "Call getNextApplicationMember(String host)");
+    }
+
+    public boolean isAValidHostName(String host){
+        if(getHostContext(host) != null){
+            return true;
+        }
+        return false;
+    }
+
+    public Member getNextApplicationMember(String host, int tenantId) {
+        HostContext hostContext = getHostContext(host);
+
+        if(hostContext == null){
+            String msg = "Invalid host name : " + host;
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        // here we have to pass tenant id to get domain from hostContext
+        String domain = hostContext.getDomainFromTenantId(tenantId);
+        String subDomain = hostContext.getSubDomainFromTenantId(tenantId);
+
+        LoadbalanceAlgorithm algorithm = hostContext.getAlgorithm();
+        GroupManagementAgent groupMgtAgent = clusteringAgent.getGroupManagementAgent(domain, subDomain);
+        
+        if (groupMgtAgent == null) {
+        	String tenantDomain;
+            try {
+	            tenantDomain = ConfigHolder.getInstance().getRealmService().getTenantManager().getDomain(tenantId);
+            } catch (UserStoreException ignore) {
+            	tenantDomain = ""+tenantId;
+            }
+        	
+            String msg =
+                    "No Group Management Agent found for the domain: " + domain + ", subDomain: "
+                    		+ subDomain + ", host: " + host+ " and for tenant: "
+                    		+  tenantDomain;
+            log.error(msg); 
+            throw new SynapseException(msg);
+        }
+        algorithm.setApplicationMembers(groupMgtAgent.getMembers());
+        AlgorithmContext context = hostContext.getAlgorithmContext();
+        return algorithm.getNextApplicationMember(context);
+    }
+
+    public HostContext getHostContext(String host) {
+        HostContext hostContext = hostContextsMap.get(host);
+        if (hostContext == null) {
+            int indexOfDot;
+            if ((indexOfDot = host.indexOf(".")) != -1) {
+                hostContext = getHostContext(host.substring(indexOfDot + 1));
+            } 
+        }
+        return hostContext;
+    }
+
+    public LoadbalanceAlgorithm getLoadbalanceAlgorithm() {
+        return lbAlgo;
+    }
+
+    public Properties getProperties() {
+        return null;
+    }
+    
+    public ClusteringAgent getClusteringAgent() {
+        return clusteringAgent;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java
new file mode 100644
index 0000000..478790e
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/builder/TopologySyncher.java
@@ -0,0 +1,159 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint.builder;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.lb.common.conf.structure.Node;
+import org.apache.stratos.lb.common.conf.structure.NodeBuilder;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
+import org.apache.stratos.lb.endpoint.TenantLoadBalanceMembershipHandler;
+import org.apache.stratos.lb.endpoint.group.mgt.GroupMgtAgentBuilder;
+
+/**
+ * A Thread, which is responsible for making a sense out of a message received for
+ * ELB via topology synchronization.
+ */
+public class TopologySyncher implements Runnable {
+
+    private static final Log log = LogFactory.getLog(TopologySyncher.class);
+
+    /*
+     * This is a reference to sharedTopologyQueue ConfigHolder.
+     */
+    private BlockingQueue<String> sharedQueue;
+
+    public TopologySyncher(BlockingQueue<String> queue) {
+
+        sharedQueue = queue;
+
+    }
+
+    @Override
+    public void run() {
+        // grab the lb configuration instance
+        LoadBalancerConfiguration lbconfig = LoadBalancerConfiguration.getInstance();
+
+        // FIXME Currently there has to be at least one dummy cluster defined in the loadbalancer
+        // conf
+        // in order to proper initialization of TribesClusteringAgent.
+        generateGroupMgtAgents(lbconfig);
+
+        // this thread should run for ever, untill terminated.
+        while (true) {
+            try {
+
+                // grabs a message or waits till the queue is non-empty
+                String message = sharedQueue.take();
+//                ConfigHolder data = ConfigHolder.getInstance();
+
+                // this message needs attention only if it's not same as the previous message and
+                // not null of course.
+//                if (data.getPreviousMsg() == null || !data.getPreviousMsg().equals(message)) {
+
+                    // reset the previous message
+//                    data.setPreviousMsg(message);
+
+                    // build the nginx format of this message, and get the Node object
+                    Node topologyNode = NodeBuilder.buildNode(message);
+
+                    // reset service configurations
+//                    lbconfig.resetData();
+                    // create new service configurations
+                    List<ServiceConfiguration> currentServiceConfigs = lbconfig.createServicesConfig(topologyNode);
+                    
+                    generateGroupMgtAgents(lbconfig);
+                    
+                    removeGroupMgtAgents(lbconfig, currentServiceConfigs);
+
+//                }
+
+            } catch (InterruptedException ignore) {
+            }
+        }
+
+    }
+
+    private void removeGroupMgtAgents(LoadBalancerConfiguration lbConfig, List<ServiceConfiguration> currentServiceConfigs) {
+
+        for (Iterator iterator = lbConfig.getServiceConfigurations().values().iterator(); iterator.hasNext();) {
+            Map<String, ServiceConfiguration> valuesMap = (Map<String, ServiceConfiguration>) iterator.next();
+            
+            for (Iterator iterator2 = valuesMap.values().iterator(); iterator2.hasNext();) {
+                ServiceConfiguration oldServiceConfig = (ServiceConfiguration) iterator2.next();
+                
+                if(!currentServiceConfigs.contains(oldServiceConfig)){
+                    // if the ServiceConfiguration is not there any more in the latest topology
+                    lbConfig.removeServiceConfiguration(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
+                    GroupMgtAgentBuilder.resetGroupMgtAgent(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
+                }
+            }
+        }
+    }
+
+    /**
+     * @param lbconfig
+     */
+    private void generateGroupMgtAgents(LoadBalancerConfiguration lbconfig) {
+        TenantLoadBalanceMembershipHandler handler =
+            ConfigHolder.getInstance()
+                .getTenantLoadBalanceMembershipHandler();
+
+        if (handler == null) {
+            String msg =
+                "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        Map<String, HostContext> hostContexts = lbconfig.getHostContextMap();
+
+        // Add the Axis2 GroupManagement agents
+        if (hostContexts != null) {
+            // iterate through each host context
+            for (HostContext hostCtxt : hostContexts.values()) {
+                // each host can has multiple Tenant Contexts, iterate through them
+                for (TenantDomainContext tenantCtxt : hostCtxt
+                    .getTenantDomainContexts()) {
+
+                    String domain = tenantCtxt.getDomain();
+                    String subDomain = tenantCtxt.getSubDomain();
+
+                    // creates the group management agent
+                    GroupMgtAgentBuilder.createGroupMgtAgent(domain,
+                        subDomain);
+                }
+
+                // add to the handler
+                handler.addHostContext(hostCtxt);
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ac065d73/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
new file mode 100644
index 0000000..a0e1022
--- /dev/null
+++ b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
@@ -0,0 +1,228 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.lb.endpoint.cluster.manager;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.stratos.lb.endpoint.util.ConfigHolder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.stratos.cartridge.messages.ClusterDomainManager;
+import org.apache.stratos.cartridge.messages.ClusterDomain;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
+import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.apache.stratos.lb.common.conf.util.Constants;
+import org.apache.stratos.lb.common.conf.util.HostContext;
+import org.apache.stratos.lb.common.conf.util.TenantDomainContext;
+import org.apache.stratos.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
+import org.apache.stratos.lb.endpoint.TenantLoadBalanceMembershipHandler;
+
+/**
+ * Bridge between the ELB and the Stratos2 Agent.
+ */
+public class ClusterDomainManagerImpl implements ClusterDomainManager {
+
+    private static final Log log = LogFactory.getLog(ClusterDomainManagerImpl.class);
+
+    @Override
+    public void addClusterDomain(ClusterDomain cluster) {
+
+        // create group management agent, if one doesn't exist already.
+        HostContext hostCtxt = createGroupMgtAgentIfNotExists(cluster);
+
+        // we should only update if the above step is successful.
+        if (hostCtxt != null) {
+            // create / update Service Configuration
+            createOrUpdateServiceConfig(cluster, hostCtxt);
+        }
+        
+    }
+
+    @Override
+	public void removeClusterDomain(String domain, String subDomain, String hostName) {
+
+		TenantLoadBalanceMembershipHandler handler =
+		                                             ConfigHolder.getInstance()
+		                                                         .getTenantLoadBalanceMembershipHandler();
+
+		if (handler == null) {
+			String msg = "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
+			log.error(msg);
+			throw new SynapseException(msg);
+		}
+
+		handler.removeHostContext(hostName);
+		
+		LoadBalancerConfiguration lbConfig = ConfigHolder.getInstance().getLbConfig();
+		
+		lbConfig.removeServiceConfiguration(domain, subDomain);
+		
+	}
+    
+    private void createOrUpdateServiceConfig(ClusterDomain cluster, HostContext ctxt) {
+        LoadBalancerConfiguration lbConfig = ConfigHolder.getInstance().getLbConfig();
+        
+        String domain = cluster.getDomain();
+        String subDomain = cluster.getSubDomain();
+        
+        if (subDomain == null || subDomain.isEmpty()) {
+            // uses default sub domain
+            subDomain = Constants.DEFAULT_SUB_DOMAIN;
+        }
+        
+        String hostName = cluster.getHostName();
+        String tenantRange = cluster.getTenantRange();
+        int minInstances = cluster.getMinInstances();
+        int maxInstances = cluster.getMaxInstances();
+        String service = cluster.getServiceName();
+        int maxRequestsPerSecond = cluster.getMaxRequestsPerSecond();
+    	int roundsToAverage = cluster.getRoundsToAverage(); 
+    	double alarmingUpperRate = cluster.getAlarmingUpperRate();
+    	double alarmingLowerRate = cluster.getAlarmingLowerRate();
+    	double scaleDownFactor = cluster.getScaleDownFactor();
+        
+        ServiceConfiguration serviceConfig ;
+        
+        if((serviceConfig = lbConfig.getServiceConfig(domain, subDomain)) == null){
+            serviceConfig = lbConfig.new ServiceConfiguration();
+        }
+        
+        // we simply override the attributes with new values
+        serviceConfig.setDomain(domain);
+        serviceConfig.setSub_domain(subDomain);
+        serviceConfig.setTenant_range(tenantRange);
+        serviceConfig.setHosts(hostName);
+        serviceConfig.setMin_app_instances(minInstances);
+        serviceConfig.setMax_app_instances(maxInstances);
+        serviceConfig.setMax_requests_per_second(maxRequestsPerSecond);
+        serviceConfig.setRounds_to_average(roundsToAverage);
+        serviceConfig.setAlarming_upper_rate(alarmingUpperRate);
+        serviceConfig.setAlarming_lower_rate(alarmingLowerRate);
+        serviceConfig.setScale_down_factor(scaleDownFactor);
+        
+        // add to host name tracker
+        lbConfig.addToHostNameTrackerMap(service, serviceConfig.getHosts());
+        
+        // add to host contexts
+        lbConfig.addToHostContextMap(hostName, ctxt);
+        
+        // finally add this service config
+        lbConfig.addServiceConfiguration(serviceConfig);
+    }
+
+    protected HostContext createGroupMgtAgentIfNotExists(ClusterDomain cluster) {
+        
+        String domain = cluster.getDomain();
+        String subDomain = cluster.getSubDomain();
+        String hostName = cluster.getHostName();
+        String tenantRange = cluster.getTenantRange();
+
+        // sub domain can be null, but others can't
+        if (domain == null || hostName == null || tenantRange == null) {
+            String msg =
+                         "Invalid value/s detected - domain: " + domain + "\n host name: " +
+                                 hostName + "\n tenant range: " + tenantRange;
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        if (subDomain == null || subDomain.isEmpty()) {
+            // uses default sub domain
+            subDomain = Constants.DEFAULT_SUB_DOMAIN;
+        }
+
+        ClusteringAgent clusteringAgent = null;
+
+        try {
+            clusteringAgent =
+                              ConfigHolder.getInstance().getAxisConfiguration()
+                                          .getClusteringAgent();
+
+        } catch (Exception e) {
+            String msg = "Failed to retrieve Clustering Agent.";
+            log.error(msg, e);
+            throw new SynapseException(msg, e);
+
+        }
+
+        if (clusteringAgent == null) {
+            String msg = "Clustering Agent is null.";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        /*
+         * Add Group Management Agent if one is not already present for this domain and sub
+         * domain
+         */
+
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+            clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(subDomain),
+                                                    domain, subDomain,-1);
+
+            if (log.isDebugEnabled()) {
+                log.debug("Group management agent added to cluster domain: " + domain +
+                          " and sub domain: " + subDomain);
+            }
+
+        } else {
+            if (log.isDebugEnabled()) {
+                log.debug("Group management agent is already available for cluster domain: " +
+                          domain + " and sub domain: " + subDomain);
+            }
+        }
+
+        TenantLoadBalanceMembershipHandler handler =
+                                                     ConfigHolder.getInstance()
+                                                                 .getTenantLoadBalanceMembershipHandler();
+
+        if (handler == null) {
+            String msg = "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        HostContext hostCtxt;
+
+        // if there's an already registered HostContext use it
+        if((hostCtxt = handler.getHostContext(hostName)) == null){
+            hostCtxt = new HostContext(hostName);
+        }
+        
+        List<TenantDomainContext> ctxts;
+        ctxts = new ArrayList<TenantDomainContext>(hostCtxt.getTenantDomainContexts());
+
+        // default value is super tenant mode - which is defined by tenant id 0, in this context
+        int tenantId = 0;
+        if(!"*".equals(tenantRange)){
+        	tenantId = Integer.parseInt(tenantRange);
+        }
+                
+        ctxts.add(new TenantDomainContext(tenantId, domain, subDomain));
+
+        hostCtxt.addTenantDomainContexts(ctxts);
+
+        handler.addHostContext(hostCtxt);
+
+        return hostCtxt;
+    }
+
+}