You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by ra...@apache.org on 2015/09/10 16:10:41 UTC

stratos git commit: Fixing STRATOS-1548: integration tests should dynamically pickup open ports

Repository: stratos
Updated Branches:
  refs/heads/stratos-4.1.x 13c42e809 -> f14d74169


Fixing STRATOS-1548: integration tests should dynamically pickup open ports


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

Branch: refs/heads/stratos-4.1.x
Commit: f14d7416912274184c6b6f70a20b05802fa63473
Parents: 13c42e8
Author: Akila Perera <ra...@gmail.com>
Authored: Thu Sep 10 19:39:37 2015 +0530
Committer: Akila Perera <ra...@gmail.com>
Committed: Thu Sep 10 19:40:05 2015 +0530

----------------------------------------------------------------------
 .../common/StratosTestServerManager.java        | 132 +++++++++++++++++--
 .../apache/stratos/integration/common/Util.java |  55 +++++++-
 .../extensions/StratosServerExtension.java      | 119 ++++++++++++-----
 .../tests/StratosIntegrationTest.java           |  38 +-----
 .../test/resources/common/JMSOutputAdaptor.xml  |   2 +-
 .../src/test/resources/common/autoscaler.xml    |   6 +-
 .../common/cartridge-config.properties          |   6 +-
 .../test/resources/common/cloud-controller.xml  |   2 +-
 .../src/test/resources/common/identity.xml      |  14 +-
 .../src/test/resources/common/jndi.properties   |   2 +-
 .../resources/common/thrift-client-config.xml   |   2 +-
 11 files changed, 277 insertions(+), 101 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/StratosTestServerManager.java
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/StratosTestServerManager.java b/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/StratosTestServerManager.java
index f3e0475..be73c6e 100644
--- a/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/StratosTestServerManager.java
+++ b/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/StratosTestServerManager.java
@@ -17,9 +17,11 @@
 package org.apache.stratos.integration.common;
 
 import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.ArrayUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.common.constants.StratosConstants;
 import org.wso2.carbon.automation.engine.context.AutomationContext;
 import org.wso2.carbon.automation.engine.context.beans.User;
 import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException;
@@ -36,7 +38,11 @@ import org.wso2.carbon.automation.extensions.servers.utils.ServerLogReader;
 
 import javax.xml.xpath.XPathExpressionException;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
 import java.io.IOException;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Set;
@@ -57,6 +63,13 @@ public class StratosTestServerManager extends TestServerManager {
     public static final String IDENTITY_FILENAME = "identity.xml";
     private static final String LOG4J_PROPERTIES_FILENAME = "log4j.properties";
     private static final String THRIFT_CLIENT_CONFIG_FILENAME = "thrift-client-config.xml";
+    private int activeMQDynamicPort;
+    private int stratosSecureDynamicPort;
+    private int stratosDynamicPort;
+    private int thriftDynamicPort;
+    private int thriftSecureDynamicPort;
+    private String webAppURL;
+    private String webAppURLHttps;
 
     public StratosTestServerManager(AutomationContext context) {
         super(context);
@@ -117,10 +130,13 @@ public class StratosTestServerManager extends TestServerManager {
     public void configureServer() throws AutomationFrameworkException {
         try {
             log.info("Configuring server using CARBON_HOME: " + carbonHome);
-            copyArtifacts(carbonHome);
+            copyArtifacts();
+
+            // set truststores and jndi.properties path
+            setSystemproperties();
         }
         catch (IOException e) {
-            log.error("Could not configure Stratos server", e);
+            throw new AutomationFrameworkException("Could not configure Stratos server", e);
         }
     }
 
@@ -128,24 +144,24 @@ public class StratosTestServerManager extends TestServerManager {
         super.stopServer();
     }
 
-    protected void copyArtifacts(String carbonHome) throws IOException {
+    protected void copyArtifacts() throws IOException {
         String commonResourcesPath = Util.getCommonResourcesFolderPath();
-        copyConfigFile(carbonHome, commonResourcesPath, MOCK_IAAS_XML_FILENAME, Util.CARBON_CONF_PATH);
-        copyConfigFile(carbonHome, commonResourcesPath, JNDI_PROPERTIES_FILENAME, Util.CARBON_CONF_PATH);
-        copyConfigFile(carbonHome, commonResourcesPath, LOG4J_PROPERTIES_FILENAME, Util.CARBON_CONF_PATH);
-        copyConfigFile(carbonHome, commonResourcesPath, CLOUD_CONTROLLER_FILENAME, Util.CARBON_CONF_PATH);
-        copyConfigFile(carbonHome, commonResourcesPath, AUTOSCALER_FILENAME, Util.CARBON_CONF_PATH);
-        copyConfigFile(carbonHome, commonResourcesPath, CARTRIDGE_CONFIG_PROPERTIES_FILENAME, Util.CARBON_CONF_PATH);
-        copyConfigFile(carbonHome, commonResourcesPath, IDENTITY_FILENAME, Util.CARBON_CONF_PATH);
-        copyConfigFile(carbonHome, commonResourcesPath, THRIFT_CLIENT_CONFIG_FILENAME, Util.CARBON_CONF_PATH);
-        copyConfigFile(carbonHome, commonResourcesPath, SCALING_DROOL_FILENAME,
+        copyConfigFile(commonResourcesPath, MOCK_IAAS_XML_FILENAME, Util.CARBON_CONF_PATH);
+        copyConfigFile(commonResourcesPath, JNDI_PROPERTIES_FILENAME, Util.CARBON_CONF_PATH);
+        copyConfigFile(commonResourcesPath, LOG4J_PROPERTIES_FILENAME, Util.CARBON_CONF_PATH);
+        copyConfigFile(commonResourcesPath, CLOUD_CONTROLLER_FILENAME, Util.CARBON_CONF_PATH);
+        copyConfigFile(commonResourcesPath, AUTOSCALER_FILENAME, Util.CARBON_CONF_PATH);
+        copyConfigFile(commonResourcesPath, CARTRIDGE_CONFIG_PROPERTIES_FILENAME, Util.CARBON_CONF_PATH);
+        copyConfigFile(commonResourcesPath, IDENTITY_FILENAME, Util.CARBON_CONF_PATH);
+        copyConfigFile(commonResourcesPath, THRIFT_CLIENT_CONFIG_FILENAME, Util.CARBON_CONF_PATH);
+        copyConfigFile(commonResourcesPath, SCALING_DROOL_FILENAME,
                 Util.CARBON_CONF_PATH + PATH_SEP + "drools");
-        copyConfigFile(carbonHome, commonResourcesPath, JMS_OUTPUT_ADAPTER_FILENAME,
+        copyConfigFile(commonResourcesPath, JMS_OUTPUT_ADAPTER_FILENAME,
                 "repository" + PATH_SEP + "deployment" + PATH_SEP + "server" + PATH_SEP + "outputeventadaptors");
 
     }
 
-    private void copyConfigFile(String carbonHome, String filePath, String fileName, String destinationFolder)
+    private void copyConfigFile(String filePath, String fileName, String destinationFolder)
             throws IOException {
         assertNotNull(carbonHome, "CARBON_HOME is null");
         String fileAbsPath = filePath + PATH_SEP + fileName;
@@ -155,6 +171,94 @@ public class StratosTestServerManager extends TestServerManager {
         File destFile = new File(carbonHome + PATH_SEP + destinationFolder + PATH_SEP + fileName);
         FileUtils.copyFile(srcFile, destFile);
         log.info("Copying file [source] " + srcFile.getAbsolutePath() + " to [dest] " + destFile.getAbsolutePath());
+
+        // replace placeholders with dynamic values
+        String content = IOUtils.toString(new FileInputStream(destFile), StandardCharsets.UTF_8.displayName());
+        content = content.replaceAll(Util.ACTIVEMQ_DYNAMIC_PORT_PLACEHOLDER, String.valueOf(activeMQDynamicPort));
+        content = content.replaceAll(Util.STRATOS_SECURE_DYNAMIC_PORT_PLACEHOLDER,
+                String.valueOf(stratosSecureDynamicPort));
+        content = content.replaceAll(Util.STRATOS_DYNAMIC_PORT_PLACEHOLDER,
+                String.valueOf(stratosDynamicPort));
+        content = content.replaceAll(Util.THRIFT_SECURE_DYNAMIC_PORT_PLACEHOLDER,
+                String.valueOf(thriftSecureDynamicPort));
+        content = content.replaceAll(Util.THRIFT_DYNAMIC_PORT_PLACEHOLDER, String.valueOf(thriftDynamicPort));
+        IOUtils.write(content, new FileOutputStream(destFile), StandardCharsets.UTF_8.displayName());
+    }
+
+    public void setSystemproperties() throws AutomationFrameworkException {
+        URL resourceUrl = getClass().getResource(File.separator + "keystores" + File.separator
+                + "products" + File.separator + "wso2carbon.jks");
+        System.setProperty("javax.net.ssl.trustStore", resourceUrl.getPath());
+        System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
+        System.setProperty("javax.net.ssl.trustStoreType", "JKS");
+        log.info("trustStore set to " + resourceUrl.getPath());
+
+        // Set jndi.properties.dir system property for initializing event receivers
+        System.setProperty("jndi.properties.dir", carbonHome + PATH_SEP + Util.CARBON_CONF_PATH);
+        try {
+            String autoscalerServiceURL = webAppURLHttps + "/services/AutoscalerService";
+            System.setProperty(StratosConstants.AUTOSCALER_SERVICE_URL, autoscalerServiceURL);
+            log.info("Autoscaler service URL set to " + autoscalerServiceURL);
+        }
+        catch (Exception e) {
+            throw new AutomationFrameworkException("Could not set autoscaler service URL system property", e);
+        }
+    }
+
+    public int getActiveMQDynamicPort() {
+        return activeMQDynamicPort;
+    }
+
+    public void setActiveMQDynamicPort(int activeMQDynamicPort) {
+        this.activeMQDynamicPort = activeMQDynamicPort;
+    }
+
+    public int getStratosSecureDynamicPort() {
+        return stratosSecureDynamicPort;
+    }
+
+    public void setStratosSecureDynamicPort(int stratosSecureDynamicPort) {
+        this.stratosSecureDynamicPort = stratosSecureDynamicPort;
+    }
+
+    public int getStratosDynamicPort() {
+        return stratosDynamicPort;
+    }
+
+    public void setStratosDynamicPort(int stratosDynamicPort) {
+        this.stratosDynamicPort = stratosDynamicPort;
+    }
+
+    public int getThriftDynamicPort() {
+        return thriftDynamicPort;
+    }
+
+    public void setThriftDynamicPort(int thriftDynamicPort) {
+        this.thriftDynamicPort = thriftDynamicPort;
+    }
+
+    public int getThriftSecureDynamicPort() {
+        return thriftSecureDynamicPort;
+    }
+
+    public void setThriftSecureDynamicPort(int thriftSecureDynamicPort) {
+        this.thriftSecureDynamicPort = thriftSecureDynamicPort;
+    }
+
+    public String getWebAppURL() {
+        return webAppURL;
+    }
+
+    public String getWebAppURLHttps() {
+        return webAppURLHttps;
+    }
+
+    public void setWebAppURL(String webAppURL) {
+        this.webAppURL = webAppURL;
+    }
+
+    public void setWebAppURLHttps(String webAppURLHttps) {
+        this.webAppURLHttps = webAppURLHttps;
     }
 }
 

http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/Util.java
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/Util.java b/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/Util.java
index 547ee16..2249dd0 100644
--- a/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/Util.java
+++ b/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/Util.java
@@ -16,23 +16,68 @@
 
 package org.apache.stratos.integration.common;
 
-import org.apache.commons.lang.StringUtils;
-
 import java.io.File;
+import java.io.IOException;
+import java.net.ServerSocket;
 
 public class Util {
     public static final String CARBON_ZIP_KEY = "carbon.zip";
     public static final String ACTIVEMQ_BIND_ADDRESS = "activemq.bind.address";
     public static final String CARBON_CONF_PATH = "repository" + File.separator + "conf";
     public static final String BASE_PATH = Util.class.getResource(File.separator).getPath();
+    public static final int MIN_PORT_NUMBER = 1;
+    public static final int MAX_PORT_NUMBER = 65535;
+
+    public static final String STRATOS_SECURE_DYNAMIC_PORT_PLACEHOLDER = "STRATOS_SECURE_DYNAMIC_PORT";
+    public static final String ACTIVEMQ_DYNAMIC_PORT_PLACEHOLDER = "ACTIVEMQ_DYNAMIC_PORT";
+    public static final String THRIFT_DYNAMIC_PORT_PLACEHOLDER = "THRIFT_DYNAMIC_PORT";
+    public static final String STRATOS_DYNAMIC_PORT_PLACEHOLDER = "STRATOS_DYNAMIC_PORT";
+    public static final String THRIFT_SECURE_DYNAMIC_PORT_PLACEHOLDER = "THRIFT_SECURE_DYNAMIC_PORT";
+
+    public static final int THRIFT_DEFAULT_PORT = 7611;
+    public static final int THRIFT_DEFAULT_SECURE_PORT = 7711;
+    public static final int STRATOS_DEFAULT_PORT = 9763;
+    public static final int STRATOS_DEFAULT_SECURE_PORT = 9443;
+    public static final int STRATOS_DEFAULT_RMI_REGISTRY_PORT = 9999;
+    public static final int STRATOS_DEFAULT_RMI_SERVER_PORT = 11111;
 
     /**
      * Get resources folder path
      *
-     * @return
+     * @return path to resources folder
      */
     public static String getCommonResourcesFolderPath() {
-        String path = Util.class.getResource(File.separator + "common").getPath();
-        return StringUtils.removeEnd(path, File.separator);
+        return BASE_PATH + ".." + File.separator + ".." + File.separator + "src" + File.separator + "test" +
+                File.separator + "resources" + File.separator + "common";
+    }
+
+    /**
+     * Checks to see if a specific port is available.
+     *
+     * @param port the port to check for availability
+     */
+    public static boolean isPortAvailable(int port) {
+        if (port < Util.MIN_PORT_NUMBER || port > Util.MAX_PORT_NUMBER) {
+            throw new IllegalArgumentException("Invalid start port: " + port);
+        }
+
+        ServerSocket ss = null;
+        try {
+            ss = new ServerSocket(port);
+            ss.setReuseAddress(true);
+            return true;
+        }
+        catch (IOException ignored) {
+        }
+        finally {
+            if (ss != null) {
+                try {
+                    ss.close();
+                }
+                catch (IOException ignored) {
+                }
+            }
+        }
+        return false;
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/extensions/StratosServerExtension.java
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/extensions/StratosServerExtension.java b/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/extensions/StratosServerExtension.java
index 3d260e5..3de05c3 100644
--- a/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/extensions/StratosServerExtension.java
+++ b/products/stratos/modules/integration/test-common/src/main/java/org/apache/stratos/integration/common/extensions/StratosServerExtension.java
@@ -31,15 +31,15 @@ import org.wso2.carbon.automation.engine.extensions.ExecutionListenerExtension;
 import org.wso2.carbon.automation.extensions.ExtensionConstants;
 
 import java.io.File;
+import java.net.URI;
 
 import static org.testng.Assert.assertNotNull;
 
 public class StratosServerExtension extends ExecutionListenerExtension {
     private static final Log log = LogFactory.getLog(StratosServerExtension.class);
-    public static final String PATH_SEP = File.separator;
     private TestLogAppender testLogAppender;
-    private StratosTestServerManager carbonTestServerManager;
-    private BrokerService broker;
+    private static StratosTestServerManager stratosTestServerManager;
+    private static BrokerService broker;
 
     @Override
     public void initiate() throws AutomationFrameworkException {
@@ -51,65 +51,78 @@ public class StratosServerExtension extends ExecutionListenerExtension {
     public void onExecutionStart() throws AutomationFrameworkException {
         Logger.getRootLogger().addAppender(testLogAppender);
         Logger.getRootLogger().setLevel(Level.INFO);
-        try {
-            String activemqBindAddress = getParameters().get(Util.ACTIVEMQ_BIND_ADDRESS);
-            long time1 = System.currentTimeMillis();
-            log.info("Starting ActiveMQ...");
-            broker.setDataDirectory(StratosServerExtension.class.getResource(File.separator).getPath() +
-                    File.separator + ".." + File.separator + "activemq-data");
-            broker.setBrokerName("testBroker");
-            broker.addConnector(activemqBindAddress);
-            broker.start();
-            long time2 = System.currentTimeMillis();
-            log.info(String.format("ActiveMQ started in %d sec", (time2 - time1) / 1000));
-        }
-        catch (Exception e) {
-            throw new RuntimeException("Could not start ActiveMQ", e);
-        }
+        int activeMQDynamicPort = startActiveMQServer();
+        startStratosServer(activeMQDynamicPort);
+    }
 
+    private void startStratosServer(int activeMQDynamicPort) throws AutomationFrameworkException {
         try {
             log.info("Setting up Stratos server...");
             AutomationContext stratosAutomationCtx =
                     new AutomationContext("STRATOS", "stratos-001", TestUserMode.SUPER_TENANT_ADMIN);
-            String stratosBackendURL = stratosAutomationCtx.getContextUrls().getWebAppURL();
-            //if port offset is not set, setting it to 0
-            if (getParameters().get(ExtensionConstants.SERVER_STARTUP_PORT_OFFSET_COMMAND) == null) {
-                getParameters().put(ExtensionConstants.SERVER_STARTUP_PORT_OFFSET_COMMAND, "0");
+            String stratosInitPortOffsetStr =
+                    getParameters().get(ExtensionConstants.SERVER_STARTUP_PORT_OFFSET_COMMAND);
+            if (stratosInitPortOffsetStr == null) {
+                throw new AutomationFrameworkException("Port offset not found in automation.xml");
             }
-            carbonTestServerManager =
+            int stratosInitPortOffset = Integer.parseInt(stratosInitPortOffsetStr);
+            int stratosInitSecurePort = Util.STRATOS_DEFAULT_SECURE_PORT + stratosInitPortOffset;
+            int stratosInitPort = Util.STRATOS_DEFAULT_PORT + stratosInitPortOffset;
+            int thriftInitPort = Util.THRIFT_DEFAULT_PORT + stratosInitPortOffset;
+            int thriftInitSecurePort = Util.THRIFT_DEFAULT_SECURE_PORT + stratosInitPortOffset;
+            int rmiRegistryPort = Util.STRATOS_DEFAULT_RMI_REGISTRY_PORT + stratosInitPortOffset;
+            int rmiServerPort = Util.STRATOS_DEFAULT_RMI_SERVER_PORT + stratosInitPortOffset;
+
+            while (!Util.isPortAvailable(stratosInitPort) || !Util.isPortAvailable(stratosInitSecurePort) ||
+                    !Util.isPortAvailable(thriftInitPort) || !Util.isPortAvailable(thriftInitSecurePort) ||
+                    !Util.isPortAvailable(rmiRegistryPort) || !Util.isPortAvailable(rmiServerPort)) {
+                stratosInitPortOffset++;
+                stratosInitSecurePort++;
+                stratosInitPort++;
+                thriftInitPort++;
+                thriftInitSecurePort++;
+                rmiRegistryPort++;
+                rmiServerPort++;
+            }
+            getParameters()
+                    .put(ExtensionConstants.SERVER_STARTUP_PORT_OFFSET_COMMAND, String.valueOf(stratosInitPortOffset));
+            stratosTestServerManager =
                     new StratosTestServerManager(stratosAutomationCtx, System.getProperty(Util.CARBON_ZIP_KEY),
                             getParameters());
-
-            log.info("Stratos server port offset: " + carbonTestServerManager.getPortOffset());
-            log.info("Stratos backend URL: " + stratosBackendURL);
-
+            stratosTestServerManager.setStratosDynamicPort(stratosInitPort);
+            stratosTestServerManager.setStratosSecureDynamicPort(stratosInitSecurePort);
+            stratosTestServerManager.setThriftDynamicPort(thriftInitPort);
+            stratosTestServerManager.setThriftSecureDynamicPort(thriftInitSecurePort);
+            stratosTestServerManager.setActiveMQDynamicPort(activeMQDynamicPort);
+            stratosTestServerManager.setWebAppURL("http://localhost:" + stratosInitPort);
+            stratosTestServerManager.setWebAppURLHttps("https://localhost:" + stratosInitSecurePort);
+
+            log.info("Stratos server dynamic port offset: " + stratosTestServerManager.getPortOffset());
+            log.info("Stratos dynamic backend URL: " + stratosTestServerManager.getWebAppURL());
+            log.info("Stratos secure dynamic backend URL: " + stratosTestServerManager.getWebAppURLHttps());
             long time3 = System.currentTimeMillis();
-            String carbonHome = carbonTestServerManager.startServer();
+            String carbonHome = stratosTestServerManager.startServer();
             assertNotNull(carbonHome, "CARBON_HOME is null");
-
             while (!serverStarted()) {
                 log.info("Waiting for topology to be initialized...");
                 Thread.sleep(5000);
             }
-
             while (!mockServiceStarted()) {
                 log.info("Waiting for mock service to be initialized...");
                 Thread.sleep(1000);
             }
-
             long time4 = System.currentTimeMillis();
             log.info(String.format("Stratos server started in %d sec", (time4 - time3) / 1000));
-
         }
         catch (Exception e) {
-            throw new RuntimeException("Could not start Stratos server", e);
+            throw new AutomationFrameworkException("Could not start Stratos server", e);
         }
     }
 
     @Override
     public void onExecutionFinish() throws AutomationFrameworkException {
         try {
-            carbonTestServerManager.stopServer();
+            stratosTestServerManager.stopServer();
             log.info("Stopped Stratos server");
         }
         catch (Exception e) {
@@ -125,6 +138,36 @@ public class StratosServerExtension extends ExecutionListenerExtension {
         }
     }
 
+    private int startActiveMQServer() throws AutomationFrameworkException {
+        try {
+            String activemqBindAddress = getParameters().get(Util.ACTIVEMQ_BIND_ADDRESS);
+            if (activemqBindAddress == null) {
+                throw new AutomationFrameworkException("ActiveMQ bind address not found in automation.xml");
+            }
+            URI givenURI = new URI(activemqBindAddress);
+            int initAMQPort = givenURI.getPort();
+            // dynamically pick an open port starting from initial port given in automation.xml
+            while (!Util.isPortAvailable(initAMQPort)) {
+                initAMQPort++;
+            }
+            URI dynamicURL = new URI(givenURI.getScheme(), givenURI.getUserInfo(), givenURI.getHost(), initAMQPort,
+                    givenURI.getPath(), givenURI.getQuery(), givenURI.getFragment());
+            long time1 = System.currentTimeMillis();
+            log.info("Starting ActiveMQ with dynamic bind address: " + dynamicURL.toString());
+            broker.setDataDirectory(StratosServerExtension.class.getResource(File.separator).getPath() +
+                    File.separator + ".." + File.separator + "activemq-data");
+            broker.setBrokerName("testBroker");
+            broker.addConnector(dynamicURL.toString());
+            broker.start();
+            long time2 = System.currentTimeMillis();
+            log.info(String.format("ActiveMQ started in %d sec", (time2 - time1) / 1000));
+            return initAMQPort;
+        }
+        catch (Exception e) {
+            throw new AutomationFrameworkException("Could not start ActiveMQ", e);
+        }
+    }
+
     private boolean serverStarted() {
         for (String message : testLogAppender.getMessages()) {
             if (message.contains("Topology initialized")) {
@@ -142,4 +185,12 @@ public class StratosServerExtension extends ExecutionListenerExtension {
         }
         return false;
     }
+
+    public static StratosTestServerManager getStratosTestServerManager() {
+        return stratosTestServerManager;
+    }
+
+    public static BrokerService getBroker() {
+        return broker;
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-integration/src/test/java/org/apache/stratos/integration/tests/StratosIntegrationTest.java
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-integration/src/test/java/org/apache/stratos/integration/tests/StratosIntegrationTest.java b/products/stratos/modules/integration/test-integration/src/test/java/org/apache/stratos/integration/tests/StratosIntegrationTest.java
index 6bcb8a7..0f90dcb 100644
--- a/products/stratos/modules/integration/test-integration/src/test/java/org/apache/stratos/integration/tests/StratosIntegrationTest.java
+++ b/products/stratos/modules/integration/test-integration/src/test/java/org/apache/stratos/integration/tests/StratosIntegrationTest.java
@@ -18,16 +18,12 @@ package org.apache.stratos.integration.tests;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.common.constants.StratosConstants;
-import org.apache.stratos.integration.common.Util;
+import org.apache.stratos.integration.common.extensions.StratosServerExtension;
 import org.apache.stratos.integration.common.rest.IntegrationMockClient;
 import org.apache.stratos.integration.common.rest.RestClient;
 import org.wso2.carbon.automation.engine.context.AutomationContext;
 import org.wso2.carbon.automation.engine.context.TestUserMode;
 
-import java.io.File;
-import java.net.URL;
-
 public class StratosIntegrationTest {
     private static final Log log = LogFactory.getLog(StratosIntegrationTest.class);
     protected AutomationContext stratosAutomationCtx;
@@ -36,8 +32,8 @@ public class StratosIntegrationTest {
     protected String stratosBackendURL;
     protected RestClient restClient;
     protected IntegrationMockClient mockIaasApiClient;
-    public static final int GLOBAL_TEST_TIMEOUT = 5 * 60 * 1000;
-    public static final int APPLICATION_TEST_TIMEOUT = 20 * 60 * 1000;
+    public static final int GLOBAL_TEST_TIMEOUT = 5 * 60 * 1000; // 5 mins
+    public static final int APPLICATION_TEST_TIMEOUT = 20 * 60 * 1000; // 20 mins
 
     public StratosIntegrationTest() {
         try {
@@ -46,34 +42,14 @@ public class StratosIntegrationTest {
                     ("/automation/userManagement/superTenant/tenant/admin/user/userName");
             adminPassword = stratosAutomationCtx.getConfigurationValue
                     ("/automation/userManagement/superTenant/tenant/admin/user/password");
-            stratosBackendURL = stratosAutomationCtx.getContextUrls().getWebAppURL();
+
+            // Do not rely on automation context for context URLs since ports are dynamically picked
+            stratosBackendURL = StratosServerExtension.getStratosTestServerManager().getWebAppURL();
             restClient = new RestClient(stratosBackendURL, adminUsername, adminPassword);
             mockIaasApiClient = new IntegrationMockClient(stratosBackendURL + "/mock-iaas/api");
-            setSystemproperties();
-        }
-        catch (Exception e) {
-            log.error("Could not initialize StratosIntegrationTest base parameters");
-        }
-    }
-
-    public void setSystemproperties() {
-        URL resourceUrl = getClass().getResource(File.separator + "keystores" + File.separator
-                + "products" + File.separator + "wso2carbon.jks");
-        System.setProperty("javax.net.ssl.trustStore", resourceUrl.getPath());
-        System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
-        System.setProperty("javax.net.ssl.trustStoreType", "JKS");
-        log.info("trustStore set to " + resourceUrl.getPath());
-
-        // Set jndi.properties.dir system property for initializing event receivers
-        System.setProperty("jndi.properties.dir", Util.getCommonResourcesFolderPath());
-        try {
-            String autoscalerServiceURL = stratosAutomationCtx.getContextUrls().getSecureServiceUrl() +
-                    "/AutoscalerService";
-            System.setProperty(StratosConstants.AUTOSCALER_SERVICE_URL, autoscalerServiceURL);
-            log.info("Autoscaler service URL set to " + autoscalerServiceURL);
         }
         catch (Exception e) {
-            throw new RuntimeException("Could not set autoscaler service URL system property");
+            throw new RuntimeException("Could not initialize StratosIntegrationTest", e);
         }
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-integration/src/test/resources/common/JMSOutputAdaptor.xml
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-integration/src/test/resources/common/JMSOutputAdaptor.xml b/products/stratos/modules/integration/test-integration/src/test/resources/common/JMSOutputAdaptor.xml
index 045660b..f00a8d8 100755
--- a/products/stratos/modules/integration/test-integration/src/test/resources/common/JMSOutputAdaptor.xml
+++ b/products/stratos/modules/integration/test-integration/src/test/resources/common/JMSOutputAdaptor.xml
@@ -23,7 +23,7 @@
 <outputEventAdaptor name="JMSOutputAdaptor" statistics="disable"
   trace="enable" type="jms" xmlns="http://wso2.org/carbon/eventadaptormanager">
   <!--property name="java.naming.provider.url">CEP_HOME/repository/conf/jndi.properties</property-->
-  <property name="java.naming.provider.url">tcp://localhost:61716</property>
+  <property name="java.naming.provider.url">tcp://localhost:ACTIVEMQ_DYNAMIC_PORT</property>
   <property name="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</property>
   <property name="transport.jms.ConnectionFactoryJNDIName">TopicConnectionFactory</property>
   <property name="transport.jms.DestinationType">topic</property>

http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-integration/src/test/resources/common/autoscaler.xml
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-integration/src/test/resources/common/autoscaler.xml b/products/stratos/modules/integration/test-integration/src/test/resources/common/autoscaler.xml
index 74cabd6..f4a40d1 100644
--- a/products/stratos/modules/integration/test-integration/src/test/resources/common/autoscaler.xml
+++ b/products/stratos/modules/integration/test-integration/src/test/resources/common/autoscaler.xml
@@ -21,19 +21,19 @@
     <autoscaler>
         <cloudController>
             <hostname>localhost</hostname>
-            <port>9543</port>
+            <port>STRATOS_SECURE_DYNAMIC_PORT</port>
             <!-- CC client timout in ms -->
             <clientTimeout>300000</clientTimeout>
         </cloudController>
         <stratosManager>
             <hostname>localhost</hostname>
-            <port>9543</port>
+            <port>STRATOS_SECURE_DYNAMIC_PORT</port>
             <!-- SM client timeout in ms -->
             <clientTimeout>300000</clientTimeout>
         </stratosManager>
 	<identity>
                 <hostname>localhost</hostname>
-                <port>9543</port>                    
+                <port>STRATOS_SECURE_DYNAMIC_PORT</port>
                 <clientTimeout>300000</clientTimeout>
         </identity>
         <member>

http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-integration/src/test/resources/common/cartridge-config.properties
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-integration/src/test/resources/common/cartridge-config.properties b/products/stratos/modules/integration/test-integration/src/test/resources/common/cartridge-config.properties
index 677d178..553c20c 100644
--- a/products/stratos/modules/integration/test-integration/src/test/resources/common/cartridge-config.properties
+++ b/products/stratos/modules/integration/test-integration/src/test/resources/common/cartridge-config.properties
@@ -17,9 +17,9 @@
 # under the License.
 #
 
-autoscaler.service.url=https://localhost:9543/services/AutoscalerService/
-cloud.controller.service.url=https://localhost:9543/services/CloudControllerService/
-stratos.manager.service.url=https://localhost:9543/services/StratosManagerService/
+autoscaler.service.url=https://localhost:STRATOS_SECURE_DYNAMIC_PORT/services/AutoscalerService/
+cloud.controller.service.url=https://localhost:STRATOS_SECURE_DYNAMIC_PORT/services/CloudControllerService/
+stratos.manager.service.url=https://localhost:STRATOS_SECURE_DYNAMIC_PORT/services/StratosManagerService/
 puppet.ip=127.0.0.1
 puppet.hostname=puppet.stratos.apache.org
 puppet.dns.available=false

http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-integration/src/test/resources/common/cloud-controller.xml
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-integration/src/test/resources/common/cloud-controller.xml b/products/stratos/modules/integration/test-integration/src/test/resources/common/cloud-controller.xml
index a7ac531..7620fbe 100644
--- a/products/stratos/modules/integration/test-integration/src/test/resources/common/cloud-controller.xml
+++ b/products/stratos/modules/integration/test-integration/src/test/resources/common/cloud-controller.xml
@@ -75,7 +75,7 @@
             <provider>mock</provider>
             <identity svns:secretAlias="cloud.controller.mock.identity">identity</identity>
             <credential svns:secretAlias="cloud.controller.mock.credential">credential</credential>
-            <property name="api.endpoint" value="https://localhost:9543/mock-iaas/api"/>
+            <property name="api.endpoint" value="https://localhost:STRATOS_SECURE_DYNAMIC_PORT/mock-iaas/api"/>
         </iaasProvider>
     </iaasProviders>
 </cloudController>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-integration/src/test/resources/common/identity.xml
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-integration/src/test/resources/common/identity.xml b/products/stratos/modules/integration/test-integration/src/test/resources/common/identity.xml
index 3547372..55e86eb 100644
--- a/products/stratos/modules/integration/test-integration/src/test/resources/common/identity.xml
+++ b/products/stratos/modules/integration/test-integration/src/test/resources/common/identity.xml
@@ -61,8 +61,8 @@
 	</Identity>
 
 	<OpenID>
-		<OpenIDServerUrl>https://localhost:9543/openidserver</OpenIDServerUrl>
-		<OpenIDUserPattern>https://localhost:9543/openid/</OpenIDUserPattern>
+		<OpenIDServerUrl>https://localhost:STRATOS_SECURE_DYNAMIC_PORT/openidserver</OpenIDServerUrl>
+		<OpenIDUserPattern>https://localhost:STRATOS_SECURE_DYNAMIC_PORT/openid/</OpenIDUserPattern>
 		<!-- If the users must be prompted for approval -->
 		<OpenIDSkipUserConsent>false</OpenIDSkipUserConsent>
 		<!-- Expiry time of the OpenID RememberMe token in minutes -->
@@ -79,9 +79,9 @@
 	</OpenID>
 
 	<OAuth>
-		<RequestTokenUrl>https://localhost:9543/oauth/request-token</RequestTokenUrl>
-		<AccessTokenUrl>https://localhost:9543/oauth/access-token</AccessTokenUrl>
-		<AuthorizeUrl>https://localhost:9543/oauth/authorize-url</AuthorizeUrl>
+		<RequestTokenUrl>https://localhost:STRATOS_SECURE_DYNAMIC_PORT/oauth/request-token</RequestTokenUrl>
+		<AccessTokenUrl>https://localhost:STRATOS_SECURE_DYNAMIC_PORT/oauth/access-token</AccessTokenUrl>
+		<AuthorizeUrl>https://localhost:STRATOS_SECURE_DYNAMIC_PORT/oauth/authorize-url</AuthorizeUrl>
 		<!-- Default validity period for Authorization Code in seconds -->
 		<AuthorizationCodeDefaultValidityPeriod>300</AuthorizationCodeDefaultValidityPeriod>
 		<!-- Default validity period for user access tokens in seconds -->
@@ -175,7 +175,7 @@
 		</SAML2Grant>
                 <OpenIDConnect>
                          <IDTokenBuilder>org.wso2.carbon.identity.openidconnect.DefaultIDTokenBuilder</IDTokenBuilder>
-                         <IDTokenIssuerID>https://localhost:9543/oauth2endpoints/token</IDTokenIssuerID>
+                         <IDTokenIssuerID>https://localhost:STRATOS_SECURE_DYNAMIC_PORT/oauth2endpoints/token</IDTokenIssuerID>
                          <IDTokenSubjectClaim>http://wso2.org/claims/givenname</IDTokenSubjectClaim>
                          <IDTokenCustomClaimsCallBackHandler>org.wso2.carbon.identity.openidconnect.SAMLAssertionClaimsCallback</IDTokenCustomClaimsCallBackHandler>
                          <IDTokenExpiration>-1</IDTokenExpiration>
@@ -203,7 +203,7 @@
 
 	<SSOService>
 		<EntityId>localhost</EntityId>
-		<IdentityProviderURL>https://localhost:9543/samlsso</IdentityProviderURL>
+		<IdentityProviderURL>https://localhost:STRATOS_SECURE_DYNAMIC_PORT/samlsso</IdentityProviderURL>
 		<SingleLogoutRetryCount>5</SingleLogoutRetryCount>
 		<SingleLogoutRetryInterval>60000</SingleLogoutRetryInterval> <!-- in milli seconds -->
 		<TenantPartitioningEnabled>false</TenantPartitioningEnabled>

http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-integration/src/test/resources/common/jndi.properties
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-integration/src/test/resources/common/jndi.properties b/products/stratos/modules/integration/test-integration/src/test/resources/common/jndi.properties
index f2d6baf..a2cfea7 100644
--- a/products/stratos/modules/integration/test-integration/src/test/resources/common/jndi.properties
+++ b/products/stratos/modules/integration/test-integration/src/test/resources/common/jndi.properties
@@ -18,5 +18,5 @@
 #
 
 connectionfactoryName=TopicConnectionFactory
-java.naming.provider.url=tcp://localhost:61716
+java.naming.provider.url=tcp://localhost:ACTIVEMQ_DYNAMIC_PORT
 java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory

http://git-wip-us.apache.org/repos/asf/stratos/blob/f14d7416/products/stratos/modules/integration/test-integration/src/test/resources/common/thrift-client-config.xml
----------------------------------------------------------------------
diff --git a/products/stratos/modules/integration/test-integration/src/test/resources/common/thrift-client-config.xml b/products/stratos/modules/integration/test-integration/src/test/resources/common/thrift-client-config.xml
index 1751bdf..f89e2c2 100644
--- a/products/stratos/modules/integration/test-integration/src/test/resources/common/thrift-client-config.xml
+++ b/products/stratos/modules/integration/test-integration/src/test/resources/common/thrift-client-config.xml
@@ -23,5 +23,5 @@
     <username>admin</username>
     <password>admin</password>
     <ip>localhost</ip>
-    <port>7711</port>
+    <port>THRIFT_DYNAMIC_PORT</port>
 </thriftClientConfiguration>