You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by sa...@apache.org on 2013/07/02 10:19:00 UTC
[07/12] Refactoring org.wso2.carbon to org.apache.stratos
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PersistenceManager.java
new file mode 100644
index 0000000..307ffe3
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/PolicyHolder.java
new file mode 100644
index 0000000..3a83a54
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryCreator.java
new file mode 100644
index 0000000..30f8149
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/RepositoryFactory.java
new file mode 100644
index 0000000..d0dd919
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/StratosDBUtils.java
new file mode 100644
index 0000000..7a4736d
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/java/org/apache/stratos/adc/mgt/utils/SynchronizeRepositoryRequest.java
new file mode 100644
index 0000000..6905a51
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..a7ddc11
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/policies.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/policies.xsd b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/main/resources/policies.xsd
new file mode 100644
index 0000000..87f7b58
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/scripts/append_zone_file.sh
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/scripts/append_zone_file.sh b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/scripts/append_zone_file.sh
new file mode 100755
index 0000000..45491df
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/test/java/org/apache/stratos/adc/mgt/test/PolicyHolderTest.java
new file mode 100644
index 0000000..ba350aa
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/log4j.properties b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/log4j.properties
new file mode 100644
index 0000000..d30536d
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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/6724d973/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/policies-1.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/policies-1.xml b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/src/test/resources/policies-1.xml
new file mode 100644
index 0000000..7dd37d5
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.apache.stratos.adc.mgt/2.1.3/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