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:37 UTC
[26/46] renaming package adc.mgt to manager
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeAppType.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeAppType.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeAppType.java
new file mode 100644
index 0000000..ed794dc
--- /dev/null
+++ b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeAppType.java
@@ -0,0 +1,44 @@
+///*
+// * Licensed to the Apache Software Foundation (ASF) under one
+// * or more contributor license agreements. See the NOTICE file
+// * distributed with this work for additional information
+// * regarding copyright ownership. The ASF licenses this file
+// * to you under the Apache License, Version 2.0 (the
+// * "License"); you may not use this file except in compliance
+// * with the License. You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing,
+// * software distributed under the License is distributed on an
+// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
+//
+///**
+// *
+// */
+//public class CartridgeAppType {
+// private String appType;
+// private boolean appSpecificMapping;
+//
+// public String getAppType() {
+// return appType;
+// }
+//
+// public void setAppType(String appType) {
+// this.appType = appType;
+// }
+//
+// public boolean isAppSpecificMapping() {
+// return appSpecificMapping;
+// }
+//
+// public void setAppSpecificMapping(boolean appSpecificMapping) {
+// this.appSpecificMapping = appSpecificMapping;
+// }
+//}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeConfigFileReader.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeConfigFileReader.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeConfigFileReader.java
new file mode 100644
index 0000000..32950ee
--- /dev/null
+++ b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeConfigFileReader.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.FileInputStream;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.utils.CarbonUtils;
+
+public class CartridgeConfigFileReader {
+
+ private static String carbonHome = CarbonUtils.getCarbonHome();
+
+ private static final Log log = LogFactory.getLog(CartridgeConfigFileReader.class);
+
+ /**
+ *
+ * Reads cartridge-config.properties file and assign properties to system
+ * properties
+ *
+ */
+ public static void readProperties() {
+
+ Properties properties = new Properties();
+ try {
+ properties.load(new FileInputStream(carbonHome + File.separator + "repository" +
+ File.separator + "conf" + File.separator +
+ "cartridge-config.properties"));
+ } catch (Exception e) {
+ log.error("Exception is occurred in reading properties file. Reason:" + e.getMessage());
+ }
+ if (log.isInfoEnabled()) {
+ log.info("Setting config properties into System properties");
+ }
+
+ for (String name : properties.stringPropertyNames()) {
+ String value = properties.getProperty(name);
+ System.setProperty(name, value);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeConstants.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeConstants.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeConstants.java
new file mode 100644
index 0000000..0130fb9
--- /dev/null
+++ b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeConstants.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.manager.utils;
+
+public class CartridgeConstants {
+ public static final String SC_IP = "sc.ip";
+ public static final String AUTOSCALER_SERVICE_URL = "autoscaler.service.url";
+ public static final String CLOUD_CONTROLLER_SERVICE_URL = "cloud.controller.service.url";
+ public static final String ALIAS_NAMESPACE ="http://org.wso2.securevault/configuration";
+ public static final String ALIAS_LOCALPART ="secretAlias";
+ public static final String ALIAS_PREFIX ="svns";
+ public static final String CARTRIDGE_AGENT_EPR = "cartridge.agent.epr";
+ public static final String GIT_HOST_NAME = "git.host.name";
+ public static final String GIT_HOST_IP = "git.host.ip";
+ public static final String SUBSCRIPTION_ACTIVE = "SUBSCRIPTION_ACTIVE";
+ public static final String SUBSCRIPTION_INACTIVE = "SUBSCRIPTION_INACTIVE";
+ public static final String REPO_NOTIFICATION_URL = "git.repo.notification.url";
+ public static final String ACTIVE = "ACTIVE";
+ public static final String NOT_READY = "NOT-READY";
+ public static final String SUBSCRIBED = "SUBSCRIBED";
+ public static final String UNSUBSCRIBED = "UNSUBSCRIBED";
+ public static final String MB_IP = "mb.ip";
+ public static final String MB_PORT = "mb.port";
+ public static final String CEP_IP = "cep.ip";
+ public static final String CEP_PORT = "cep.port";
+ public static final String PUPPET_IP = "puppet.ip";
+
+
+ public static final String DB_DATASOURCE = "adc.datasource";
+ public static final String DB_URL = "adc.jdbc.url";
+ public static final String DB_DRIVER = "adc.jdbc.driver";
+ public static final String DB_USERNAME = "adc.jdbc.username";
+ public static final String DB_PASSWORD = "adc.jdbc.password";
+ public static final String BAM_IP = "bam.ip";
+ public static final String BAM_PORT = "bam.port";
+ public static final String SUDO_SH = "sudo sh";
+ public static final String APPEND_SCRIPT = "append.script";
+ public static final String REMOVE_SCRIPT = "remove.script";
+ public static final String BIND_FILE_PATH = "bind.file.path";
+ public static final String ELB_IP = "elb.ip";
+ public static final String REPO_KEY_PATH = "repo.key.path";
+ public static final String REPO_KEY = "repo.key";
+ public static final String MAX_ATTEMPTS = "max.attempts";
+ public static final String CARTRIDGE_KEY = "cartridge.key";
+
+ public static final String FEATURE_EXTERNAL_REPO_VAIDATION_ENABLED = "feature.externalrepo.validation.enabled";
+ public static final String FEATURE_INTERNAL_REPO_ENABLED = "feature.internalrepo.enabled";
+ public static final String FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED = "feature.multitenant.multiplesubscription.enabled";
+
+ public static final String MYSQL_CARTRIDGE_NAME = "mysql";
+ public static final String PHP_CARTRIDGE_NAME = "php";
+ public static final String TOMCAT_CARTRIDGE_NAME = "tomcat";
+
+ public static final String DEFAULT_SUBDOMAIN = "__$default";
+ public static final String DEFAULT_MGT_SUBDOMAIN = "mgt";
+ public static final String MYSQL_DEFAULT_USER = "root";
+ public static final String PROVIDER_NAME_WSO2 = "wso2";
+ public static final String NOT_SUBSCRIBED = "NOT-SUBSCRIBED";
+ public static final String SECURITY_KEY_FILE = "gitRepoKey.xml";
+ public static final String SECURITY_KEY = "securityKey";
+ public static final String DEFAULT_SECURITY_KEY = "tvnw63ufg9gh5111";
+ public static final String DATA_CARTRIDGE_PROVIDER = "data";
+ public static final String REPO_INFO_EPR = "repository.info.epr";
+ public static final String INTERNAL_GIT_USERNAME = "internal.repo.username";
+ public static final String INTERNAL_GIT_PASSWORD = "internal.repo.password";
+
+ public static final String CUSTOM_PAYLOAD_PARAM_NAME_PREFIX = "payload_parameter.";
+
+ public static final String CC_SOCKET_TIMEOUT = "cc.socket.timeout";
+ public static final String CC_CONNECTION_TIMEOUT = "cc.connection.timeout";
+ public static final String AUTOSCALER_SOCKET_TIMEOUT = "autoscaler.socket.timeout";
+ public static final String AUTOSCALER_CONNECTION_TIMEOUT = "autoscaler.connection.timeout";
+
+ public static final class DomainMappingInfo {
+ public static final String ACTUAL_HOST = "actual.host";
+ public static final String HOSTINFO = "hostinfo/";
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeDomain.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeDomain.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeDomain.java
new file mode 100644
index 0000000..9d0d7a7
--- /dev/null
+++ b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/CartridgeDomain.java
@@ -0,0 +1,146 @@
+///*
+// * Licensed to the Apache Software Foundation (ASF) under one
+// * or more contributor license agreements. See the NOTICE file
+// * distributed with this work for additional information
+// * regarding copyright ownership. The ASF licenses this file
+// * to you under the Apache License, Version 2.0 (the
+// * "License"); you may not use this file except in compliance
+// * with the License. You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing,
+// * software distributed under the License is distributed on an
+// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// * KIND, either express or implied. See the License for the
+// * specific language governing permissions and limitations
+// * under the License.
+// */
+//
+//package org.apache.stratos.manager.utils;
+//
+///**
+// *
+// */
+//public class CartridgeDomain {
+//
+// private String primaryPort;
+// private String proxyPort;
+// private String type;
+// private String tenantId;
+// private int min;
+// private int max;
+// private String cartridgeType;
+// private boolean volume;
+// private String tenantDomain;
+// private String clusterDomain;
+// private String clusterSubDomain;
+//
+// private String hostName;
+// private boolean started;
+//
+// public String getPrimaryPort() {
+// return primaryPort;
+// }
+//
+// public String getProxyPort() {
+// return proxyPort;
+// }
+//
+// public String getType() {
+// return type;
+// }
+//
+// public String getTenantId() {
+// return tenantId;
+// }
+//
+// public int getMin() {
+// return min;
+// }
+//
+// public int getMax() {
+// return max;
+// }
+//
+// public String getCartridgeType() {
+// return cartridgeType;
+// }
+//
+// public boolean getVolume() {
+// return volume;
+// }
+//
+// public String getTenantDomain() {
+// return tenantDomain;
+// }
+//
+// public void setPrimaryPort(String primaryPort) {
+// this.primaryPort = primaryPort;
+// }
+//
+// public void setProxyPort(String proxyPort) {
+// this.proxyPort = proxyPort;
+// }
+//
+// public void setType(String type) {
+// this.type = type;
+// }
+//
+// public void setTenantId(String tenantId) {
+// this.tenantId = tenantId;
+// }
+//
+// public void setMin(int min) {
+// this.min = min;
+// }
+//
+// public void setMax(int max) {
+// this.max = max;
+// }
+//
+// public void setCartridgeType(String cartridgeType) {
+// this.cartridgeType = cartridgeType;
+// }
+//
+// public void setVolume(boolean volume) {
+// this.volume = volume;
+// }
+//
+// public void setTenantDomain(String tenantDomain) {
+// this.tenantDomain = tenantDomain;
+// }
+//
+// public void setStarted(boolean started) {
+// this.started = started;
+// }
+//
+// public boolean isStarted() {
+// return started;
+// }
+//
+// public String getHostName() {
+// return hostName;
+// }
+//
+// public void setHostName(String hostName) {
+// this.hostName = hostName;
+// }
+//
+// public String getClusterDomain() {
+// return clusterDomain;
+// }
+//
+// public void setClusterDomain(String clusterDomain) {
+// this.clusterDomain = clusterDomain;
+// }
+//
+// public String getClusterSubDomain() {
+// return clusterSubDomain;
+// }
+//
+// public void setClusterSubDomain(String clusterSubDomain) {
+// this.clusterSubDomain = clusterSubDomain;
+// }
+//
+//}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/Deserializer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/Deserializer.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/Deserializer.java
new file mode 100644
index 0000000..3f78f3b
--- /dev/null
+++ b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/Deserializer.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.ByteArrayInputStream;
+import java.io.ObjectInput;
+import java.io.ObjectInputStream;
+
+public class Deserializer {
+
+
+ /**
+ * Deserialize a byte array and retrieve the object.
+ * @param bytes bytes to be deserialized
+ * @return the deserialized {@link Object}
+ * @throws Exception if the deserialization is failed.
+ */
+ public static Object deserializeFromByteArray(byte[] bytes) throws Exception {
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
+ ObjectInput in = null;
+ try {
+ in = new ObjectInputStream(bis);
+ Object o = in.readObject();
+
+ return o;
+
+ } finally {
+ bis.close();
+ if (in != null) {
+ in.close();
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/DomainInfo.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/DomainInfo.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/DomainInfo.java
new file mode 100644
index 0000000..1c91921
--- /dev/null
+++ b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/DomainInfo.java
@@ -0,0 +1,43 @@
+///*
+// * Licensed to the Apache Software Foundation (ASF) under one
+// * or more contributor license agreements. See the NOTICE file
+// * distributed with this work for additional information
+// * regarding copyright ownership. The ASF licenses this file
+// * to you under the Apache License, Version 2.0 (the
+// * "License"); you may not use this file except in compliance
+// * with the License. You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing,
+// * software distributed under the License is distributed on an
+// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// * KIND, either express or implied. See the License for the
+// * specific language governing permissions and limitations
+// * under the License.
+// */
+//
+//package org.apache.stratos.manager.utils;
+//
+//public class DomainInfo {
+//
+// String domain;
+// String subDomain;
+//
+// public String getDomain() {
+// return domain;
+// }
+//
+// public void setDomain(String domain) {
+// this.domain = domain;
+// }
+//
+// public String getSubDomain() {
+// return subDomain;
+// }
+//
+// public void setSubDomain(String subDomain) {
+// this.subDomain = subDomain;
+// }
+//
+//}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/PersistenceManager.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/PersistenceManager.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/PersistenceManager.java
new file mode 100644
index 0000000..4caa60b
--- /dev/null
+++ b/components/org.apache.stratos.manager/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.deploy.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/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/PolicyHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/PolicyHolder.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/PolicyHolder.java
new file mode 100644
index 0000000..98ddd3d
--- /dev/null
+++ b/components/org.apache.stratos.manager/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/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/RepoPasswordMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/RepoPasswordMgtUtil.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/RepoPasswordMgtUtil.java
new file mode 100644
index 0000000..3e266f9
--- /dev/null
+++ b/components/org.apache.stratos.manager/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/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/RepositoryCreator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/RepositoryCreator.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/RepositoryCreator.java
new file mode 100644
index 0000000..da5c27d
--- /dev/null
+++ b/components/org.apache.stratos.manager/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/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/RepositoryFactory.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/RepositoryFactory.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/RepositoryFactory.java
new file mode 100644
index 0000000..d4cb14d
--- /dev/null
+++ b/components/org.apache.stratos.manager/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/9d280533/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/Serializer.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/Serializer.java b/components/org.apache.stratos.manager/src/main/java/org/apache/stratos/manager/utils/Serializer.java
new file mode 100644
index 0000000..fa56b24
--- /dev/null
+++ b/components/org.apache.stratos.manager/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.deploy.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();
+ }
+
+ }
+}