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 2014/01/08 06:51:13 UTC

[02/46] renamed adc.mgt to manager

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9f74f29c/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/PersistenceManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/PersistenceManager.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/PersistenceManager.java
new file mode 100644
index 0000000..6941d63
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/PersistenceManager.java
@@ -0,0 +1,892 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one 
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
+ * KIND, either express or implied.  See the License for the 
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.manager.utils;
+
+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.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.manager.dao.CartridgeSubscriptionInfo;
+import org.apache.stratos.manager.dao.DataCartridge;
+import org.apache.stratos.manager.dao.PortMapping;
+import org.apache.stratos.manager.dao.RepositoryCredentials;
+import org.apache.stratos.manager.service.Service;
+import org.apache.stratos.manager.repository.Repository;
+
+/**
+ * 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<CartridgeSubscriptionInfo> retrieveSubscribedCartridges(int tenantId) throws Exception {
+
+		List<CartridgeSubscriptionInfo> subscribedCartridgeList = new ArrayList<CartridgeSubscriptionInfo>();
+		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()) {
+				CartridgeSubscriptionInfo cartridge = new CartridgeSubscriptionInfo();
+				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.setUrl(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(RepoPasswordMgtUtil.decryptPassword(resultSet.getString("REPO_USER_PASSWORD"),null)); // TODO this is no longer supported
+			}
+		} 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(CartridgeSubscriptionInfo cartridgeSubscriptionInfo) 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 (cartridgeSubscriptionInfo.getRepository() != null) {
+				String encryptedRepoUserPassword = RepoPasswordMgtUtil.encryptPassword(cartridgeSubscriptionInfo.getRepository()
+						.getPassword(),cartridgeSubscriptionInfo.getSubscriptionKey());
+				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, cartridgeSubscriptionInfo.getRepository().getUrl());
+				insertRepoStmt.setString(2, "ACTIVE");
+				insertRepoStmt.setString(3, cartridgeSubscriptionInfo.getRepository().getUserName());
+				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 (cartridgeSubscriptionInfo.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, cartridgeSubscriptionInfo.getDataCartridge().getDataCartridgeType());
+				insertDataCartStmt.setString(2, cartridgeSubscriptionInfo.getDataCartridge().getUserName());
+				insertDataCartStmt.setString(3, cartridgeSubscriptionInfo.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);
+			}
+
+			// TODO - Mapped domain is not used. Is it not used anymore?
+			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, SUBSCRIPTION_KEY)"
+					+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+
+			insertSubscriptionStmt = con.prepareStatement(insertSubscription, Statement.RETURN_GENERATED_KEYS);
+			insertSubscriptionStmt.setInt(1, cartridgeSubscriptionInfo.getTenantId());
+			insertSubscriptionStmt.setString(2, cartridgeSubscriptionInfo.getCartridge());
+			insertSubscriptionStmt.setString(3, cartridgeSubscriptionInfo.getProvider());
+			insertSubscriptionStmt.setString(4, cartridgeSubscriptionInfo.getHostName());
+			insertSubscriptionStmt.setString(5, cartridgeSubscriptionInfo.getPolicy());
+			insertSubscriptionStmt.setString(6, cartridgeSubscriptionInfo.getClusterDomain());
+			insertSubscriptionStmt.setString(7, cartridgeSubscriptionInfo.getClusterSubdomain());
+			insertSubscriptionStmt.setString(8, cartridgeSubscriptionInfo.getMgtClusterDomain());
+			insertSubscriptionStmt.setString(9, cartridgeSubscriptionInfo.getMgtClusterSubDomain());
+			insertSubscriptionStmt.setString(10, cartridgeSubscriptionInfo.getState());
+			insertSubscriptionStmt.setString(11, cartridgeSubscriptionInfo.getAlias());
+			insertSubscriptionStmt.setString(12, cartridgeSubscriptionInfo.getTenantDomain());
+			insertSubscriptionStmt.setString(13, cartridgeSubscriptionInfo.getBaseDirectory());
+			insertSubscriptionStmt.setInt(14, repoId);
+			insertSubscriptionStmt.setInt(15, dataCartridgeId);
+			insertSubscriptionStmt.setString(16, cartridgeSubscriptionInfo.getSubscriptionKey());
+			if (log.isDebugEnabled()) {
+				log.debug("Executing insert: " + insertSubscription);
+			}
+			insertSubscriptionStmt.executeUpdate();
+			res = insertSubscriptionStmt.getGeneratedKeys();
+			if (res.next()) {
+				cartridgeSubscriptionId = res.getInt(1);
+			}
+
+			List<PortMapping> portMapping = cartridgeSubscriptionInfo.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 CartridgeSubscriptionInfo getSubscription(String tenantDomain, String alias) throws Exception {
+
+		CartridgeSubscriptionInfo cartridgeSubscriptionInfo = 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()) {
+				cartridgeSubscriptionInfo = new CartridgeSubscriptionInfo();
+				populateSubscription(cartridgeSubscriptionInfo, 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 cartridgeSubscriptionInfo;
+	}
+
+	private static void populateSubscription(CartridgeSubscriptionInfo cartridgeSubscriptionInfo, ResultSet resultSet)
+			throws Exception {
+		String repoName = resultSet.getString("REPO_NAME");
+		String repoUserName = resultSet.getString("REPO_USER_NAME");
+		String repoPassword = resultSet.getString("REPO_USER_PASSWORD");
+		if (repoName != null) {
+			Repository repo = new Repository();
+			repo.setUrl(repoName);
+			repo.setUserName(repoUserName);
+			repo.setPassword(repoPassword);
+			cartridgeSubscriptionInfo.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"));
+			cartridgeSubscriptionInfo.setDataCartridge(dataCartridge);
+		}
+		cartridgeSubscriptionInfo.setPortMappings(getPortMappings(resultSet.getInt("SUBSCRIPTION_ID")));
+		cartridgeSubscriptionInfo.setTenantId(resultSet.getInt("TENANT_ID"));
+		cartridgeSubscriptionInfo.setState(resultSet.getString("STATE"));
+		cartridgeSubscriptionInfo.setPolicy(resultSet.getString("POLICY"));
+		cartridgeSubscriptionInfo.setCartridge(resultSet.getString("CARTRIDGE"));
+		cartridgeSubscriptionInfo.setAlias(resultSet.getString("ALIAS"));
+		cartridgeSubscriptionInfo.setClusterDomain(resultSet.getString("CLUSTER_DOMAIN"));
+		cartridgeSubscriptionInfo.setClusterSubdomain(resultSet.getString("CLUSTER_SUBDOMAIN"));
+		cartridgeSubscriptionInfo.setMgtClusterDomain(resultSet.getString("MGT_DOMAIN"));
+		cartridgeSubscriptionInfo.setMgtClusterSubDomain(resultSet.getString("MGT_SUBDOMAIN"));
+		cartridgeSubscriptionInfo.setProvider(resultSet.getString("PROVIDER"));
+		cartridgeSubscriptionInfo.setHostName(resultSet.getString("HOSTNAME"));
+		cartridgeSubscriptionInfo.setTenantDomain(resultSet.getString("TENANT_DOMAIN"));
+		cartridgeSubscriptionInfo.setBaseDirectory(resultSet.getString("BASE_DIR"));
+		cartridgeSubscriptionInfo.setSubscriptionId(resultSet.getInt("SUBSCRIPTION_ID"));
+		cartridgeSubscriptionInfo.setMappedDomain(resultSet.getString("MAPPED_DOMAIN"));
+		cartridgeSubscriptionInfo.setSubscriptionKey(resultSet.getString("SUBSCRIPTION_KEY"));
+	}
+
+	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<CartridgeSubscriptionInfo> getSubscription(String repositoryURL) throws Exception {
+
+		List<CartridgeSubscriptionInfo> subscriptionList = new ArrayList<CartridgeSubscriptionInfo>();
+		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()) {
+				CartridgeSubscriptionInfo cartridgeSubscriptionInfo = new CartridgeSubscriptionInfo();
+				populateSubscription(cartridgeSubscriptionInfo, resultSet);
+				subscriptionList.add(cartridgeSubscriptionInfo);
+			}
+		} 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 List<CartridgeSubscriptionInfo> getSubscriptionsForTenant (int tenantId) throws Exception {
+
+        List<CartridgeSubscriptionInfo> cartridgeSubscriptionInfos = 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 TENANT_ID=? AND C.STATE != 'UNSUBSCRIBED'";
+            statement = con.prepareStatement(sql);
+            statement.setInt(1, tenantId);
+            if (log.isDebugEnabled()) {
+                log.debug("Executing query: " + sql);
+            }
+
+            resultSet = statement.executeQuery();
+            cartridgeSubscriptionInfos = new ArrayList<CartridgeSubscriptionInfo>();
+            if (resultSet.next()) {
+                CartridgeSubscriptionInfo cartridgeSubscriptionInfo = new CartridgeSubscriptionInfo();
+                populateSubscription(cartridgeSubscriptionInfo, resultSet);
+                cartridgeSubscriptionInfos.add(cartridgeSubscriptionInfo);
+            }
+        } catch (Exception s) {
+            String msg = "Error while sql connection :" + s.getMessage();
+            log.error(msg, s);
+            throw s;
+
+        } finally {
+            StratosDBUtils.closeAllConnections(con, statement, resultSet);
+        }
+
+        return cartridgeSubscriptionInfos;
+    }
+
+
+    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 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);
+			}
+		}
+
+	}
+	
+	
+	public static CartridgeSubscriptionInfo getSubscriptionFromClusterId(String clusterId) throws Exception {
+
+		CartridgeSubscriptionInfo cartridgeSubscriptionInfo = 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 C.CLUSTER_DOMAIN=? AND C.STATE != 'UNSUBSCRIBED'";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, clusterId);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				cartridgeSubscriptionInfo = new CartridgeSubscriptionInfo();
+				populateSubscription(cartridgeSubscriptionInfo, 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 cartridgeSubscriptionInfo;
+	}
+	
+	
+	public static void persistService(Service service) throws Exception {
+
+		Connection con = null;
+		PreparedStatement insertServiceStmt = null;
+
+		String insertServiceSQL = "INSERT INTO SERVICE (TYPE, AUTOSCALING_POLICY,DEPLOYMENT_POLICY,TENANT_RANGE,"
+				+ "CLUSTER_ID,HOST_NAME,SUBSCRIPTION_KEY)"
+				+ " VALUES (?,?,?,?,?,?,?)";
+
+		try {
+
+			con = StratosDBUtils.getConnection();
+			insertServiceStmt = con.prepareStatement(insertServiceSQL);
+			insertServiceStmt.setString(1, service.getType());
+			insertServiceStmt.setString(2, service.getAutoscalingPolicyName());
+			insertServiceStmt.setString(3, service.getDeploymentPolicyName());
+			insertServiceStmt.setString(4, service.getTenantRange());
+			insertServiceStmt.setString(5, service.getClusterId());
+			insertServiceStmt.setString(6, service.getHostName());
+			insertServiceStmt.setString(7, service.getSubscriptionKey());
+			insertServiceStmt.executeUpdate();
+			con.commit();
+			if (log.isDebugEnabled()) {
+				log.debug(" Service " + service.getType() + " is inserted into DB");
+			}
+		} catch (Exception e) {
+			String msg = "Error while sql connection :" + e.getMessage();
+			log.error(msg, e);
+			throw e;
+		} finally {
+			StratosDBUtils.closeStatement(insertServiceStmt);
+		}
+
+	} 
+	
+	
+	public static Service getServiceFromCartridgeType(String cartridgeType) {
+		return null;
+	}
+
+	
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9f74f29c/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/PolicyHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/PolicyHolder.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/PolicyHolder.java
new file mode 100644
index 0000000..98ddd3d
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/PolicyHolder.java
@@ -0,0 +1,292 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one 
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
+ * KIND, either express or implied.  See the License for the 
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.manager.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.manager.dto.Policy;
+import org.apache.stratos.manager.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 subscription.
+		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 subscription 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/9f74f29c/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepoPasswordMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepoPasswordMgtUtil.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepoPasswordMgtUtil.java
new file mode 100644
index 0000000..3e266f9
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepoPasswordMgtUtil.java
@@ -0,0 +1,108 @@
+/**
+ * 
+ */
+package org.apache.stratos.manager.utils;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * @author wso2
+ *
+ */
+public class RepoPasswordMgtUtil {
+
+	private static final Log log = LogFactory.getLog(RepoPasswordMgtUtil.class);
+	
+	public static String getSecurityKey() {
+		// TODO : a proper testing on the secure vault protected
+		// user defined encryption key
+		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);
+						
+					}
+				}
+			}
+		}
+        else {
+            log.error(String.format("File does not exist: %s", xmlFile.getPath()));
+		}*/
+		return securityKey;
+	}
+	
+	public static String encryptPassword(String repoUserPassword, String secKey) {
+		String encryptPassword = "";
+		String secret = secKey; // 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;
+	}
+	
+	public static String encryptPassword(String repoUserPassword) {
+		return encryptPassword(repoUserPassword,getSecurityKey());
+	}
+
+	public static String decryptPassword(String repoUserPassword, String secKey) {
+		
+		String decryptPassword = "";
+		String secret = secKey; // 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;
+	}
+	
+	public static String decryptPassword(String repoUserPassword) {		
+		return decryptPassword(repoUserPassword,getSecurityKey());
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9f74f29c/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepositoryCreator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepositoryCreator.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepositoryCreator.java
new file mode 100644
index 0000000..da5c27d
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepositoryCreator.java
@@ -0,0 +1,286 @@
+package org.apache.stratos.manager.utils;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT 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 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.manager.repository.Repository;
+import org.apache.stratos.manager.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 createSubscription()
+    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/9f74f29c/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepositoryFactory.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepositoryFactory.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepositoryFactory.java
new file mode 100644
index 0000000..d4cb14d
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/RepositoryFactory.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one 
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
+ * KIND, either express or implied.  See the License for the 
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.manager.utils;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.manager.service.ApplicationManagementService;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+
+/**
+ * @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/9f74f29c/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/Serializer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/Serializer.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/Serializer.java
new file mode 100644
index 0000000..ba96240
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/Serializer.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.manager.utils;
+
+import org.apache.stratos.manager.service.Service;
+import org.apache.stratos.manager.lookup.ClusterIdToSubscription;
+import org.apache.stratos.manager.subscription.CartridgeSubscription;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+
+public class Serializer {
+
+    /**
+     * Serialize a SubscriptionContext instance to a byte array.
+     * @param cartridgeSubscription
+     * @return byte[]
+     * @throws java.io.IOException
+     */
+    public static byte[] serializeSubscriptionSontextToByteArray(CartridgeSubscription cartridgeSubscription)
+            throws IOException {
+
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        ObjectOutput out = null;
+        try {
+            out = new ObjectOutputStream(bos);
+            out.writeObject(cartridgeSubscription);
+
+            return bos.toByteArray();
+
+        } finally {
+            if (out != null) {
+                out.close();
+            }
+            bos.close();
+        }
+
+    }
+
+    /**
+     * Serialize a ClusterIdToSubscription instance to a byte array.
+     * @param clusterIdToSubscription
+     * @return byte[]
+     * @throws java.io.IOException
+     */
+    public static byte[] serializeClusterIdToSubscriptionToByteArray(ClusterIdToSubscription clusterIdToSubscription)
+            throws IOException {
+
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        ObjectOutput out = null;
+        try {
+            out = new ObjectOutputStream(bos);
+            out.writeObject(clusterIdToSubscription);
+
+            return bos.toByteArray();
+
+        } finally {
+            if (out != null) {
+                out.close();
+            }
+            bos.close();
+        }
+
+    }
+
+    public static byte[] serializeServiceToByteArray(Service service)
+            throws IOException {
+
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        ObjectOutput out = null;
+        try {
+            out = new ObjectOutputStream(bos);
+            out.writeObject(service);
+
+            return bos.toByteArray();
+
+        } finally {
+            if (out != null) {
+                out.close();
+            }
+            bos.close();
+        }
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9f74f29c/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/StratosDBUtils.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/StratosDBUtils.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/StratosDBUtils.java
new file mode 100644
index 0000000..c884014
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/StratosDBUtils.java
@@ -0,0 +1,213 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one 
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
+ * KIND, either express or implied.  See the License for the 
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.manager.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/9f74f29c/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/SynchronizeRepositoryRequest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/SynchronizeRepositoryRequest.java b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/SynchronizeRepositoryRequest.java
new file mode 100644
index 0000000..4c9f4e8
--- /dev/null
+++ b/components/org.apache.stratos.adc.mgt/src/main/java/org/apache/stratos/manager/utils/SynchronizeRepositoryRequest.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.manager.utils;
+
+import org.apache.axis2.clustering.ClusteringCommand;
+import org.apache.axis2.clustering.ClusteringFault;
+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.wso2.carbon.core.CarbonAxisConfigurator;
+import org.wso2.carbon.core.multitenancy.TenantAxisConfigurator;
+import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+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/9f74f29c/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
index 9a36dd9..d317f85 100644
--- 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
@@ -24,7 +24,7 @@
 		<description>
 			Admin service for ADC activities
 		</description>
-		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.ApplicationManagementService
+		<parameter name="ServiceClass">org.apache.stratos.manager.service.ApplicationManagementService
         </parameter>
 		<parameter name="enableMTOM">true</parameter>
 		<parameter name="adminService" locked="true">true</parameter>
@@ -43,8 +43,8 @@
 		<description>
 			Admin service for receiving git repo update notifications
 		</description>
-		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.RepoNotificationService
-		</parameter>
+		<parameter name="ServiceClass">org.apache.stratos.manager.service.RepoNotificationService
+        </parameter>
 		<parameter name="enableMTOM">true</parameter>
 		<parameter name="adminService" locked="true">false</parameter>
 		<parameter name="hiddenService" locked="true">false</parameter>
@@ -64,7 +64,7 @@
 			Exposes information related to internally created
 			repositories
         </description>
-		<parameter name="ServiceClass">org.apache.stratos.adc.mgt.service.InstanceInformationManagementService</parameter>
+		<parameter name="ServiceClass">org.apache.stratos.manager.service.InstanceInformationManagementService</parameter>
 		<parameter name="enableMTOM">true</parameter>
 		<parameter name="adminService" locked="true">false</parameter>
 		<parameter name="hiddenService" locked="true">false</parameter>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9f74f29c/components/org.apache.stratos.adc.mgt/src/test/java/org/apache/stratos/adc/mgt/test/CartridgeSubscriptionTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.mgt/src/test/java/org/apache/stratos/adc/mgt/test/CartridgeSubscriptionTest.java b/components/org.apache.stratos.adc.mgt/src/test/java/org/apache/stratos/adc/mgt/test/CartridgeSubscriptionTest.java
deleted file mode 100644
index 2446b23..0000000
--- a/components/org.apache.stratos.adc.mgt/src/test/java/org/apache/stratos/adc/mgt/test/CartridgeSubscriptionTest.java
+++ /dev/null
@@ -1,85 +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.test;
-
-import junit.framework.TestCase;
-import org.apache.stratos.adc.mgt.exception.ADCException;
-import org.apache.stratos.adc.mgt.subscription.CartridgeSubscription;
-import org.apache.stratos.adc.mgt.subscription.factory.CartridgeSubscriptionFactory;
-import org.apache.stratos.adc.mgt.subscription.tenancy.SubscriptionMultiTenantBehaviour;
-import org.apache.stratos.adc.mgt.subscription.tenancy.SubscriptionSingleTenantBehaviour;
-import org.apache.stratos.adc.mgt.subscription.tenancy.SubscriptionTenancyBehaviour;
-import org.apache.stratos.cloud.controller.pojo.CartridgeInfo;
-
-public class CartridgeSubscriptionTest extends TestCase {
-
-    private CartridgeSubscription getCartridgeInstance (CartridgeInfo cartridgeInfo) {
-
-        SubscriptionTenancyBehaviour tenancyBehaviour;
-        if(cartridgeInfo.getMultiTenant()) {
-            tenancyBehaviour = new SubscriptionMultiTenantBehaviour();
-        } else {
-            tenancyBehaviour = new SubscriptionSingleTenantBehaviour();
-        }
-
-        try {
-            return CartridgeSubscriptionFactory.getCartridgeSubscriptionInstance(cartridgeInfo, tenancyBehaviour);
-
-        } catch (ADCException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    public void testCarbonCartridge () {
-
-        CartridgeInfo cartridgeInfo = new CartridgeInfo();
-        cartridgeInfo.setProvider("carbon");
-        cartridgeInfo.setMultiTenant(true);
-        cartridgeInfo.setType("esb");
-        assertNotNull(getCartridgeInstance(cartridgeInfo));
-    }
-
-    public void testPhpCartridgeInstance () {
-
-        CartridgeInfo cartridgeInfo = new CartridgeInfo();
-        cartridgeInfo.setProvider("php-provider");
-        cartridgeInfo.setMultiTenant(false);
-        cartridgeInfo.setType("php");
-        assertNotNull(getCartridgeInstance(cartridgeInfo));
-    }
-
-    public void testMySqlCartridgeInstance () {
-
-        CartridgeInfo cartridgeInfo = new CartridgeInfo();
-        cartridgeInfo.setProvider("data");
-        cartridgeInfo.setMultiTenant(false);
-        cartridgeInfo.setType("mysql");
-        assertNotNull(getCartridgeInstance(cartridgeInfo));
-    }
-
-    public void testTomcatCartridgeInstance () {
-
-        CartridgeInfo cartridgeInfo = new CartridgeInfo();
-        cartridgeInfo.setProvider("tomcat-provider");
-        cartridgeInfo.setMultiTenant(false);
-        cartridgeInfo.setType("tomcat");
-        assertNotNull(getCartridgeInstance(cartridgeInfo));
-    }
-}